import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
import { A as getEnvString, D as getEnvBool, N as isCI, o as logger } from "./logger-CfDSdx1q.js";
import { F as CONSENT_ENDPOINT, I as EVENTS_ENDPOINT, L as R_ENDPOINT, U as POSTHOG_KEY, W as VERSION, r as fetchWithTimeout, t as fetchWithProxy } from "./fetch-CHx36OdV.js";
import { c as getUserId, o as getUserAuthInfo } from "./accounts-Dz-Gsg_B.js";
import { z } from "zod";
import { PostHog } from "posthog-node";
//#region src/telemetryEvents.ts
/** Closed list of telemetry event names. Shared by telemetry recording and API DTOs. */
const TELEMETRY_EVENTS = [
	"assertion_used",
	"command_used",
	"eval setup",
	"eval_ran",
	"feature_used",
	"funnel",
	"redteam discover",
	"redteam generate",
	"redteam init",
	"redteam poison",
	"redteam report",
	"redteam run",
	"redteam setup",
	"webui_action",
	"webui_api",
	"webui_page_view"
];
const TelemetryPropertyValueSchema = z.union([
	z.string(),
	z.number(),
	z.boolean(),
	z.array(z.string())
]);
const TelemetryEventSchema = z.object({
	event: z.enum(TELEMETRY_EVENTS),
	packageVersion: z.string().optional().prefault(VERSION),
	properties: z.record(z.string(), TelemetryPropertyValueSchema)
});
//#endregion
//#region src/telemetry.ts
var telemetry_exports = /* @__PURE__ */ __exportAll({
	Telemetry: () => Telemetry,
	default: () => telemetry
});
let posthogClient = null;
let isShuttingDown = false;
function getPostHogClient() {
	if (getEnvBool("PROMPTFOO_DISABLE_TELEMETRY") || getEnvBool("IS_TESTING")) return null;
	if (posthogClient === null && "phc_E5n5uHnDo2eREJL1uqX1cIlbkoRby4yFWt3V94HqRRg") try {
		posthogClient = new PostHog(POSTHOG_KEY, {
			host: EVENTS_ENDPOINT,
			fetch: fetchWithProxy,
			flushInterval: 0
		});
	} catch {
		posthogClient = null;
	}
	return posthogClient;
}
const TELEMETRY_TIMEOUT_MS = 1e3;
function getRuntimeMetadata() {
	return {
		nodeVersion: process.version,
		nodeMajor: Number.parseInt(process.versions.node, 10),
		platform: process.platform,
		arch: process.arch
	};
}
var Telemetry = class {
	telemetryDisabledRecorded = false;
	id;
	constructor() {
		this.id = getUserId();
		this.identify();
	}
	getPersonProperties(ciFlag) {
		return {
			...getUserAuthInfo(),
			isRunningInCi: ciFlag
		};
	}
	async identify() {
		if (this.disabled || getEnvBool("IS_TESTING")) return;
		const client = getPostHogClient();
		if (client) try {
			const personProperties = this.getPersonProperties(isCI());
			client.identify({
				distinctId: this.id,
				properties: personProperties
			});
			client.flush().catch(() => {});
		} catch (error) {
			logger.debug(`PostHog identify error: ${error}`);
		}
	}
	get disabled() {
		return getEnvBool("PROMPTFOO_DISABLE_TELEMETRY");
	}
	recordTelemetryDisabled() {
		if (!this.telemetryDisabledRecorded) {
			this.sendEvent("feature_used", { feature: "telemetry disabled" });
			this.telemetryDisabledRecorded = true;
		}
	}
	record(eventName, properties) {
		if (this.disabled) this.recordTelemetryDisabled();
		else this.sendEvent(eventName, properties);
	}
	sendEvent(eventName, properties) {
		const ciFlag = isCI();
		const personProperties = this.getPersonProperties(ciFlag);
		const propertiesWithMetadata = {
			...properties,
			packageVersion: VERSION,
			isRunningInCi: ciFlag,
			...getRuntimeMetadata()
		};
		const client = getPostHogClient();
		if (client && !getEnvBool("IS_TESTING")) try {
			client.capture({
				distinctId: this.id,
				event: eventName,
				properties: {
					...propertiesWithMetadata,
					$set: personProperties
				}
			});
			client.flush().catch(() => {});
		} catch (error) {
			logger.debug(`PostHog capture error: ${error}`);
		}
		fetchWithProxy(R_ENDPOINT, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				event: eventName,
				environment: getEnvString("NODE_ENV", "development"),
				email: personProperties.email,
				meta: {
					user_id: this.id,
					...propertiesWithMetadata
				}
			})
		}).catch(() => {});
	}
	async shutdown() {
		if (isShuttingDown) return;
		const client = getPostHogClient();
		if (!client) return;
		isShuttingDown = true;
		try {
			await client.shutdown();
		} catch (error) {
			logger.debug(`PostHog shutdown error: ${error}`);
		}
	}
	/**
	* This is a separate endpoint to save consent used only for redteam data synthesis for "harmful" plugins.
	*/
	async saveConsent(email, metadata) {
		try {
			const response = await fetchWithTimeout(CONSENT_ENDPOINT, {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({
					email,
					metadata
				})
			}, TELEMETRY_TIMEOUT_MS);
			if (!response.ok) throw new Error(`Failed to save consent: ${response.statusText}`);
		} catch (err) {
			logger.debug(`Failed to save consent: ${err.message}`);
		}
	}
};
const telemetry = new Telemetry();
const TELEMETRY_INSTANCE_KEY = Symbol.for("promptfoo.telemetry.instance");
const SHUTDOWN_HANDLER_KEY = Symbol.for("promptfoo.telemetry.shutdownHandler");
process[TELEMETRY_INSTANCE_KEY] = telemetry;
if (!process[SHUTDOWN_HANDLER_KEY]) {
	process[SHUTDOWN_HANDLER_KEY] = true;
	process.once("beforeExit", () => {
		const instance = process[TELEMETRY_INSTANCE_KEY];
		if (instance) instance.shutdown().catch(() => {});
	});
}
//#endregion
export { telemetry_exports as n, TelemetryEventSchema as r, telemetry as t };

//# sourceMappingURL=telemetry-BU_HX4xA.js.map