| 1 | import os from "node:os"; |
| 2 | |
| 3 | import node_machine_id from "node-machine-id"; |
| 4 | import type { PostHog as PostHogType } from "posthog-node"; |
| 5 | |
| 6 | import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js"; |
| 7 | import { logger } from "../util/logger.js"; |
| 8 | |
| 9 | export class PosthogService { |
| 10 | private os: string | undefined; |
| 11 | private uniqueId: string; |
| 12 | |
| 13 | constructor() { |
| 14 | this.os = os.platform(); |
| 15 | this.uniqueId = this.getEventUserId(); |
| 16 | } |
| 17 | |
| 18 | get isEnabled() { |
| 19 | return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0"; |
| 20 | } |
| 21 | |
| 22 | private _client: PostHogType | undefined; |
| 23 | private async getClient() { |
| 24 | if (this.isEnabled) { |
| 25 | if (!this._client) { |
| 26 | const { PostHog } = await import("posthog-node"); |
| 27 | this._client = new PostHog( |
| 28 | "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", |
| 29 | { |
| 30 | host: "https://app.posthog.com", |
| 31 | }, |
| 32 | ); |
| 33 | } |
| 34 | } else { |
| 35 | this._client = undefined; |
| 36 | } |
| 37 | return this._client; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * - Continue user id if signed in |
| 42 | * - Unique machine id if not signed in |
| 43 | */ |
| 44 | private getEventUserId(): string { |
| 45 | const authConfig = loadAuthConfig(); |
| 46 | |
| 47 | if (isAuthenticatedConfig(authConfig)) { |
| 48 | return authConfig.userId; |
| 49 | } |
| 50 | |
| 51 | // Fall back to unique machine id if not signed in |
| 52 | return node_machine_id.machineIdSync(); |
| 53 | } |
| 54 | |
| 55 | async capture(event: string, properties: { [key: string]: any }) { |
| 56 | try { |
| 57 | const client = await this.getClient(); |
| 58 | if (!client) { |
| 59 | return; |
| 60 | } |
| 61 | |
| 62 | const augmentedProperties = { |
| 63 | ...properties, |
| 64 | os: this.os, |
| 65 | extensionVersion: "", // TODO cn version |
| 66 | ideName: "cn", |
| 67 | ideType: "cli", |
| 68 | }; |
| 69 | const payload = { |
| 70 | distinctId: this.uniqueId, |
| 71 | event, |
| 72 | properties: augmentedProperties, |
| 73 | sendFeatureFlags: true, |
| 74 | }; |
| 75 | |
| 76 | client?.capture(payload); |
| 77 | } catch (e) { |
| 78 | logger.debug(`Failed to capture telemetry event '${event}': ${e}`); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | async shutdown() { |
| 83 | try { |
| 84 | const client = await this.getClient(); |
| 85 | if (client) { |
| 86 | await client.shutdown(); |
| 87 | } |
| 88 | } catch (e) { |
| 89 | logger.debug(`Failed to shutdown PostHog client: ${e}`); |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | export const posthogService = new PosthogService(); |