|
| 1 | +import { randomUUID } from "node:crypto" |
| 2 | +import { getVersion } from "lib/getVersion" |
| 3 | + |
| 4 | +const POSTHOG_HOST = "https://us.i.posthog.com" |
| 5 | +const TSCI_POSTHOG_PROJECT_API_KEY = |
| 6 | + "phc_htd8AQjSfVEsFCLQMAiUooG4Q0DKBCjqYuQglc9V3Wo" |
| 7 | +const POSTHOG_CAPTURE_PATH = "/capture" |
| 8 | + |
| 9 | +export interface TelemetryConfig { |
| 10 | + enabled: boolean |
| 11 | + projectApiKey?: string |
| 12 | + host?: string |
| 13 | + distinctId?: string |
| 14 | +} |
| 15 | + |
| 16 | +type TelemetryProperties = Record< |
| 17 | + string, |
| 18 | + string | number | boolean | null | undefined |
| 19 | +> |
| 20 | + |
| 21 | +const isTruthy = (value: string | undefined) => |
| 22 | + value ? ["1", "true", "yes", "on"].includes(value.toLowerCase()) : false |
| 23 | + |
| 24 | +const joinUrl = (host: string, path: string) => |
| 25 | + `${host.replace(/\/$/, "")}${path}` |
| 26 | + |
| 27 | +export const getTelemetryConfigFromEnv = ( |
| 28 | + env: NodeJS.ProcessEnv = process.env, |
| 29 | +): TelemetryConfig => { |
| 30 | + if (isTruthy(env.TSCI_TELEMETRY_DISABLED)) { |
| 31 | + return { enabled: false } |
| 32 | + } |
| 33 | + |
| 34 | + if (env.TSCI_TEST_MODE === "true" && !isTruthy(env.TSCI_TELEMETRY_FORCE)) { |
| 35 | + return { enabled: false } |
| 36 | + } |
| 37 | + |
| 38 | + if (!TSCI_POSTHOG_PROJECT_API_KEY) return { enabled: false } |
| 39 | + |
| 40 | + return { |
| 41 | + enabled: true, |
| 42 | + projectApiKey: TSCI_POSTHOG_PROJECT_API_KEY, |
| 43 | + host: POSTHOG_HOST, |
| 44 | + distinctId: `tscircuit-cli-${randomUUID()}`, |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +export const captureTelemetryEvent = async ( |
| 49 | + event: string, |
| 50 | + properties: TelemetryProperties, |
| 51 | +) => { |
| 52 | + const telemetryConfig = getTelemetryConfigFromEnv() |
| 53 | + if (!telemetryConfig.enabled || !telemetryConfig.projectApiKey) return |
| 54 | + |
| 55 | + const url = joinUrl(POSTHOG_HOST, POSTHOG_CAPTURE_PATH) |
| 56 | + const payload = { |
| 57 | + api_key: telemetryConfig.projectApiKey, |
| 58 | + distinct_id: telemetryConfig.distinctId, |
| 59 | + event, |
| 60 | + properties: { |
| 61 | + ...properties, |
| 62 | + cli_version: getVersion(), |
| 63 | + source: "@tscircuit/cli", |
| 64 | + }, |
| 65 | + } |
| 66 | + |
| 67 | + try { |
| 68 | + await fetch(url, { |
| 69 | + method: "POST", |
| 70 | + headers: { |
| 71 | + "Content-Type": "application/json", |
| 72 | + }, |
| 73 | + body: JSON.stringify(payload), |
| 74 | + }) |
| 75 | + } catch { |
| 76 | + // Telemetry must never make CLI commands fail. |
| 77 | + } |
| 78 | +} |
0 commit comments