Elffuss BraidHub

kikocis/continue public

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