-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathanalytics.ts
More file actions
169 lines (141 loc) · 4.4 KB
/
Copy pathanalytics.ts
File metadata and controls
169 lines (141 loc) · 4.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import { PostHog } from 'posthog-node';
import type { EventMessage, IdentifyMessage } from 'posthog-node';
import { screen } from 'electron';
import os from 'node:os';
import crypto from 'node:crypto';
import type { DashboardLayout } from '@irdashies/types';
import { readData, writeData } from './storage/storage';
import { getAnalyticsOptOut } from './storage/analytics';
import logger from './logger';
import type ElectronLog from 'electron-log';
import type { LogMessage } from 'electron-log';
declare const POSTHOG_KEY: string;
const DEDUP_WINDOW_MS = 60 * 60 * 1000;
const DEDUP_KEY_LENGTH = 30;
const DEDUP_MAX_ENTRIES = 5000;
export interface AnalyticsProvider {
capture(event: EventMessage): void;
identify(message: IdentifyMessage): void;
shutdown(shutdownTimeoutMs?: number): void;
}
class PostHogProvider implements AnalyticsProvider {
constructor(private posthog: PostHog) {}
capture(event: EventMessage): void {
this.posthog.capture(event);
}
identify(message: IdentifyMessage): void {
this.posthog.identify(message);
}
shutdown(shutdownTimeoutMs?: number): void {
this.posthog.shutdown(shutdownTimeoutMs);
}
}
export class Analytics {
private provider: AnalyticsProvider | null = null;
constructor(provider?: AnalyticsProvider) {
if (provider) {
this.provider = provider;
} else {
this.initialize();
}
}
private initialize(): void {
const optOut = getAnalyticsOptOut();
if (optOut === true) {
logger.warn(
'[Analytics] Analytics opt-out is enabled, skipping initialization'
);
return;
}
// POSTHOG_KEY is defined at build time via Vite's define option
const key: string = POSTHOG_KEY || '';
if (!key) {
return;
}
const posthog = new PostHog(key, {
host: 'https://eu.i.posthog.com',
disableGeoip: false,
enableExceptionAutocapture: true,
});
this.provider = new PostHogProvider(posthog);
}
capture(event: EventMessage): void {
this.provider?.capture(event);
}
identify(message: IdentifyMessage): void {
this.provider?.identify(message);
}
shutdown(shutdownTimeoutMs?: number): void {
if (this.provider) {
this.provider.shutdown(shutdownTimeoutMs);
}
}
isInitialized(): boolean {
return this.provider !== null;
}
private getOrCreateUserId(): string {
let userId = readData<string>('userId');
if (!userId) {
userId = crypto.randomUUID();
writeData('userId', userId);
}
return userId;
}
setupLogTransport(): void {
if (!this.provider) return;
const lastSent = new Map<string, number>();
const transport = ((message: LogMessage) => {
const text = message.data
.map((d: unknown) => (typeof d === 'string' ? d : JSON.stringify(d)))
.join(' ');
const key = `${message.level}:${text.slice(0, DEDUP_KEY_LENGTH)}`;
const now = Date.now();
const last = lastSent.get(key);
if (last !== undefined && now - last < DEDUP_WINDOW_MS) return;
lastSent.set(key, now);
if (lastSent.size > DEDUP_MAX_ENTRIES) {
for (const [k, t] of lastSent) {
if (now - t >= DEDUP_WINDOW_MS) lastSent.delete(k);
}
}
// Not the nicest way to do this, but avoids having to implement OTEL to get logging in posthog
this.capture({
event: 'log_message',
properties: {
level: message.level,
message: text,
},
});
}) as ElectronLog.Transport;
transport.level = 'warn';
transport.transforms = [];
logger.transports.posthog = transport;
}
async init(version: string, dashboard: DashboardLayout): Promise<void> {
const displays = screen.getAllDisplays();
const primaryDisplay = screen.getPrimaryDisplay();
const cpus = os.cpus();
const cpuName = cpus.length > 0 ? cpus[0].model : undefined;
const userId = this.getOrCreateUserId();
this.identify({
distinctId: userId,
disableGeoip: false,
properties: {
$os: os.platform(),
$os_version: os.release(),
os_arch: os.arch(),
cpu_count: os.cpus().length,
total_memory: os.totalmem(),
$screen_width: primaryDisplay.size.width,
$screen_height: primaryDisplay.size.height,
number_of_screens: displays.length,
cpu: cpuName,
version,
dashboard,
},
});
this.capture({
event: 'app_started',
});
}
}