-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathanalytics.test.ts
More file actions
819 lines (694 loc) · 25.9 KB
/
Copy pathanalytics.test.ts
File metadata and controls
819 lines (694 loc) · 25.9 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import { Analytics, groupsFromUser } from '@utils/analytics';
import { PostHog } from 'posthog-node';
import { AxiosError } from 'axios';
import { v4 as uuidv4 } from 'uuid';
import { ANALYTICS_TEAM_TAG, WIZARD_FLAG_KEYS } from '@lib/constants';
import { VERSION } from '@lib/version';
import { handleApiError, type ApiUser } from '@lib/api';
vi.mock('posthog-node');
vi.mock('uuid');
// IS_PRODUCTION_BUILD is read live (property access) in the Analytics
// constructor, so a getter backed by this mutable flag lets a test flip the
// build type without re-importing the module. Defaults falsy → 'dev',
// matching every other test. vi.hoisted() runs before the hoisted vi.mock
// factory, so the getter can read the flag at import time without hitting the
// temporal dead zone.
const envState = vi.hoisted(() => ({
isProductionBuild: false,
runSurface: 'local' as 'cloud' | 'local',
taskRunId: undefined as string | undefined,
taskId: undefined as string | undefined,
}));
vi.mock('@env', async (importOriginal) => ({
...(await importOriginal<typeof import('@env')>()),
get IS_PRODUCTION_BUILD() {
return envState.isProductionBuild;
},
get RUN_SURFACE() {
return envState.runSurface;
},
get TASK_RUN_ID() {
return envState.taskRunId;
},
get TASK_ID() {
return envState.taskId;
},
}));
const mockUuidv4 = uuidv4 as unknown as MockedFunction<typeof uuidv4>;
const MockedPostHog = PostHog as MockedClass<typeof PostHog>;
describe('Analytics', () => {
let analytics: Analytics;
let mockPostHogInstance: Mocked<PostHog>;
beforeEach(() => {
vi.clearAllMocks();
envState.isProductionBuild = false;
envState.taskRunId = undefined;
envState.taskId = undefined;
// Each run mints several distinct uuids; mock them to different values
// so the tests reflect reality (run_id !== $session_id) rather than
// collapsing them. Call order: anonymousId, runId (both in the
// constructor), then sessionId (lazily, on first identify).
let uuidCall = 0;
mockUuidv4.mockImplementation((() => {
uuidCall += 1;
if (uuidCall === 1) return 'test-uuid'; // anonymousId
if (uuidCall === 2) return 'run-uuid'; // runId
return 'session-uuid'; // sessionId (first identify)
}) as any);
mockPostHogInstance = {
capture: vi.fn(),
captureException: vi.fn(),
alias: vi.fn(),
identify: vi.fn(),
shutdown: vi.fn().mockResolvedValue(undefined),
} as any;
MockedPostHog.mockImplementation(() => mockPostHogInstance);
analytics = new Analytics();
});
describe('captureException', () => {
it('should capture exception with error object and properties', () => {
const error = new Error('Test error');
const properties = { integration: 'nextjs' };
analytics.captureException(error, properties);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
...properties,
},
);
});
it('should capture exception with tags included in properties', () => {
const error = new Error('Test error');
const properties = { integration: 'nextjs' };
analytics.setTag('testTag', 'testValue');
analytics.captureException(error, properties);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
testTag: 'testValue',
...properties,
},
);
});
it('should capture exception with distinct ID when set', () => {
const error = new Error('Test error');
const distinctId = 'user-123';
analytics.identifyUser({ distinct_id: distinctId } as unknown as ApiUser);
analytics.captureException(error);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
distinctId,
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
$session_id: 'session-uuid',
},
);
});
it('should capture exception without properties when not provided', () => {
const error = new Error('Test error');
analytics.captureException(error);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
},
);
});
it('should merge tags with provided properties', () => {
const error = new Error('Test error');
const properties = { integration: 'nextjs', step: 'installation' };
analytics.setTag('environment', 'test');
// Not `version`: that key is now one of the constructor's own tags.
analytics.setTag('framework_version', '1.0.0');
analytics.captureException(error, properties);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
environment: 'test',
framework_version: '1.0.0',
integration: 'nextjs',
step: 'installation',
},
);
});
it('should override tags with properties when keys conflict', () => {
const error = new Error('Test error');
const properties = { integration: 'react' };
analytics.setTag('integration', 'nextjs');
analytics.captureException(error, properties);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
integration: 'react',
},
);
});
it('should always include team property in exceptions', () => {
const error = new Error('Test error');
analytics.captureException(error);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
},
);
});
it('drops a raw socket error carrying a transport errno code', () => {
const error = Object.assign(new Error('read ECONNRESET'), {
code: 'ECONNRESET',
});
analytics.captureException(error);
expect(mockPostHogInstance.captureException).not.toHaveBeenCalled();
});
it('drops a host-unreachable socket error', () => {
const error = Object.assign(
new Error('connect EHOSTUNREACH 1.2.3.4:443'),
{
code: 'EHOSTUNREACH',
},
);
analytics.captureException(error);
expect(mockPostHogInstance.captureException).not.toHaveBeenCalled();
});
it('drops a wrapped API error that folds the errno into its message', () => {
// api.ts drops `code` and leaves the errno only in the message text.
const error = new Error('Failed to fetch user data (ECONNRESET)');
analytics.captureException(error);
expect(mockPostHogInstance.captureException).not.toHaveBeenCalled();
});
it('still captures an install failure whose embedded CLI stderr mentions an errno', () => {
// A wrapped tool failure that merely quotes a benign errno in its stderr
// must still report — the errno is not the "(ECONNRESET)" wrapper api.ts
// emits, so it does not mean the user's own transport dropped.
const error = new Error(
'Codex MCP add failed: request failed ECONNRESET, retrying\npermission denied',
);
analytics.captureException(error);
expect(mockPostHogInstance.captureException).toHaveBeenCalledTimes(1);
});
it('drops an ENOTFOUND ApiError produced by handleApiError (DNS lookup failure)', () => {
// A user with no working DNS. api.ts folds the errno into the message and
// drops `code`, so the "(ENOTFOUND)" wrapper is the only trace — the same
// path the message scan handles. Must not open an error tracking issue.
const axiosError = new AxiosError('connect error');
axiosError.config = { url: '/api/users/@me/' } as never;
axiosError.code = 'ENOTFOUND';
const apiError = handleApiError(axiosError, 'fetch user data');
analytics.captureException(apiError);
expect(mockPostHogInstance.captureException).not.toHaveBeenCalled();
});
it('drops a filesystem timeout on a network-backed mount', () => {
const error = Object.assign(new Error('ETIMEDOUT: operation timed out'), {
code: 'ETIMEDOUT',
});
analytics.captureException(error);
expect(mockPostHogInstance.captureException).not.toHaveBeenCalled();
});
it('still captures a genuine wizard error', () => {
const error = new Error('Something the wizard did wrong');
analytics.captureException(error);
expect(mockPostHogInstance.captureException).toHaveBeenCalledTimes(1);
});
});
describe('flag exposure', () => {
// The getFlag spy *is* the exposure assertion — the SDK emits the event, not the wizard.
let snapshot: {
getFlag: MockedFunction<(key: string) => string | boolean | undefined>;
getFlagPayload: MockedFunction<() => undefined>;
};
function mockFlags(flags: Record<string, string | boolean>): void {
snapshot = {
getFlag: vi.fn((key: string) => flags[key]),
getFlagPayload: vi.fn(() => undefined),
};
(mockPostHogInstance as any).evaluateFlags = vi
.fn()
.mockResolvedValue(snapshot);
}
beforeEach(() => {
mockFlags({
'wizard-orchestrator': true,
'wizard-orchestrator-override': 'sol-review',
'unrelated-flag': 'variant-x',
});
});
it('reads each wizard flag through getFlag', async () => {
await analytics.getAllFlagsForWizard();
expect(snapshot.getFlag.mock.calls.map(([k]) => k)).toEqual([
...WIZARD_FLAG_KEYS,
]);
});
it("skips another team's flag", async () => {
await analytics.getAllFlagsForWizard();
expect(snapshot.getFlag).not.toHaveBeenCalledWith('unrelated-flag');
});
it('does not hand-roll $feature_flag_called', async () => {
await analytics.getAllFlagsForWizard();
const handRolled = mockPostHogInstance.capture.mock.calls.filter(
([arg]) => (arg as any).event === '$feature_flag_called',
);
expect(handRolled).toEqual([]);
});
it('resolves only wizard flags into the map', async () => {
const flags = await analytics.getAllFlagsForWizard();
expect(flags).toEqual({
'wizard-orchestrator': 'true',
'wizard-orchestrator-override': 'sol-review',
});
});
it('stamps $feature/<key> for wizard flags only', async () => {
await analytics.getAllFlagsForWizard();
analytics.wizardCapture('switchboard resolved', { program: 'x' });
const call = mockPostHogInstance.capture.mock.calls.find(
([arg]) => (arg as any).event === 'wizard: switchboard resolved',
);
const props = (call![0] as any).properties;
expect(props['$feature/wizard-orchestrator']).toBe(true);
expect(props['$feature/wizard-orchestrator-override']).toBe('sol-review');
expect(props['$feature/unrelated-flag']).toBeUndefined();
});
it('lists only enabled wizard flags in $active_feature_flags', async () => {
mockFlags({
'wizard-orchestrator': true,
'wizard-self-driving-use-pi-harness': false,
'wizard-orchestrator-override': 'sol-review',
'unrelated-flag': 'variant-x',
});
await analytics.getAllFlagsForWizard();
analytics.wizardCapture('switchboard resolved');
const call = mockPostHogInstance.capture.mock.calls.find(
([arg]) => (arg as any).event === 'wizard: switchboard resolved',
);
expect((call![0] as any).properties.$active_feature_flags).toEqual([
'wizard-orchestrator',
'wizard-orchestrator-override',
]);
});
it("tags the SDK's exposure event", () => {
const beforeSend = MockedPostHog.mock.calls[0][1]!.before_send as (
e: any,
) => any;
const sent = beforeSend({
event: '$feature_flag_called',
properties: { $feature_flag: 'wizard-orchestrator' },
});
expect(sent.properties).toMatchObject({
$feature_flag: 'wizard-orchestrator',
$app_name: 'wizard',
run_id: 'run-uuid',
run_surface: 'local',
build: 'dev',
});
});
it('carries no $feature props before the fetch', () => {
analytics.wizardCapture('early event');
const call = mockPostHogInstance.capture.mock.calls.find(
([arg]) => (arg as any).event === 'wizard: early event',
);
const keys = Object.keys((call![0] as any).properties).filter((k) =>
k.startsWith('$feature/'),
);
expect(keys).toEqual([]);
});
});
describe('build tag', () => {
it("tags dev/test runs as 'dev'", () => {
analytics.captureException(new Error('e'));
expect(
(mockPostHogInstance.captureException as Mock).mock.calls.at(-1)?.[2],
).toMatchObject({ build: 'dev' });
});
it("tags production builds as 'prod'", () => {
envState.isProductionBuild = true;
const prodAnalytics = new Analytics();
prodAnalytics.captureException(new Error('e'));
expect(
(mockPostHogInstance.captureException as Mock).mock.calls.at(-1)?.[2],
).toMatchObject({ build: 'prod' });
});
});
describe('run_surface tag', () => {
it("defaults every event to 'local'", () => {
analytics.captureException(new Error('e'));
expect(
(mockPostHogInstance.captureException as Mock).mock.calls.at(-1)?.[2],
).toMatchObject({ run_surface: 'local' });
});
it("tags 'cloud' on the headless launch surface", () => {
envState.runSurface = 'cloud';
try {
const cloud = new Analytics();
cloud.captureException(new Error('e'));
expect(
(mockPostHogInstance.captureException as Mock).mock.calls.at(-1)?.[2],
).toMatchObject({ run_surface: 'cloud' });
} finally {
envState.runSurface = 'local';
}
});
});
describe('task run tags', () => {
it('omits both ids on a run the sandbox did not launch', () => {
analytics.capture('wizard: test');
const properties = (mockPostHogInstance.capture as Mock).mock.calls.at(
-1,
)?.[0].properties;
expect(properties).not.toHaveProperty('task_run_id');
expect(properties).not.toHaveProperty('task_id');
});
it('tags every event with the launching task run', () => {
envState.taskRunId = 'task-run-uuid';
envState.taskId = 'task-uuid';
const cloud = new Analytics();
cloud.capture('wizard: test');
cloud.captureException(new Error('e'));
// Both paths merge the same tag bag, so the join back to the task run has
// to hold for exceptions too, not just explicit captures.
expect(
(mockPostHogInstance.capture as Mock).mock.calls.at(-1)?.[0].properties,
).toMatchObject({ task_run_id: 'task-run-uuid', task_id: 'task-uuid' });
expect(
(mockPostHogInstance.captureException as Mock).mock.calls.at(-1)?.[2],
).toMatchObject({ task_run_id: 'task-run-uuid', task_id: 'task-uuid' });
});
});
describe('identifyUser', () => {
const user = {
distinct_id: 'user-123',
email: 'v@posthog.com',
first_name: 'Vincent',
last_name: null,
} as unknown as ApiUser;
it('identifies the user, then merges the anonymous person in', () => {
analytics.identifyUser(user);
expect(mockPostHogInstance.identify).toHaveBeenCalledWith({
distinctId: 'user-123',
properties: {
$set: { email: 'v@posthog.com', name: 'Vincent' },
},
});
expect(mockPostHogInstance.alias).toHaveBeenCalledWith({
distinctId: 'user-123',
alias: 'test-uuid',
});
// Alias only ever fires after identification.
expect(
(mockPostHogInstance.identify as Mock).mock.invocationCallOrder[0],
).toBeLessThan(
(mockPostHogInstance.alias as Mock).mock.invocationCallOrder[0],
);
});
it('runs once per user — re-login does not re-identify or re-merge', () => {
analytics.identifyUser(user);
analytics.identifyUser(user);
expect(mockPostHogInstance.identify).toHaveBeenCalledTimes(1);
expect(mockPostHogInstance.alias).toHaveBeenCalledTimes(1);
});
it('does nothing when the id is the run anonymous id itself', () => {
analytics.identifyUser({
distinct_id: 'test-uuid',
} as unknown as ApiUser);
expect(mockPostHogInstance.identify).not.toHaveBeenCalled();
expect(mockPostHogInstance.alias).not.toHaveBeenCalled();
});
it('opens the session ($session_id) only once the user is identified', () => {
const error = new Error('e');
// Pre-login: run_id is present, $session_id is not.
analytics.captureException(error);
const beforeLogin = (mockPostHogInstance.captureException as Mock).mock
.calls[0][2];
expect(beforeLogin).toMatchObject({ run_id: 'run-uuid' });
expect(beforeLogin).not.toHaveProperty('$session_id');
// Post-login: both ids ride along.
analytics.identifyUser({ distinct_id: 'user-123' } as unknown as ApiUser);
analytics.captureException(error);
expect(
(mockPostHogInstance.captureException as Mock).mock.calls[1][2],
).toMatchObject({ run_id: 'run-uuid', $session_id: 'session-uuid' });
});
it('omits person properties the user does not have', () => {
analytics.identifyUser({
distinct_id: 'user-123',
} as unknown as ApiUser);
expect(mockPostHogInstance.identify).toHaveBeenCalledWith({
distinctId: 'user-123',
properties: { $set: {} },
});
});
});
describe('exception repair (before_send)', () => {
type TestEvent = Record<string, unknown> & {
distinctId?: string;
properties?: Record<string, unknown>;
};
type BeforeSendFn = (event: TestEvent | null) => TestEvent | null;
const getBeforeSend = (): BeforeSendFn =>
(MockedPostHog.mock.calls[0][1] as { before_send: BeforeSendFn })
.before_send;
it('reattaches identity and tags to autocaptured exceptions', () => {
analytics.setTag('command', 'slack');
const beforeSend = getBeforeSend();
const result = beforeSend({
event: '$exception',
distinctId: 'random-uuidv7',
properties: {
$exception_list: [{ type: 'Error' }],
$process_person_profile: false,
},
});
expect(result?.distinctId).toBe('test-uuid');
expect(result?.properties).toEqual({
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
command: 'slack',
$exception_list: [{ type: 'Error' }],
});
});
it('uses the real distinct id once set', () => {
analytics.identifyUser({ distinct_id: 'user-123' } as unknown as ApiUser);
const beforeSend = getBeforeSend();
const result = beforeSend({
event: '$exception',
distinctId: 'random-uuidv7',
properties: {},
});
expect(result?.distinctId).toBe('user-123');
});
it('leaves non-exception events untouched', () => {
const beforeSend = getBeforeSend();
const event = { event: 'x', distinctId: 'd', properties: { a: 1 } };
expect(beforeSend(event)).toBe(event);
expect(event.distinctId).toBe('d');
expect(event.properties).toEqual({ a: 1 });
});
});
describe('shutdown', () => {
it('emits the terminal event once — the first status wins over the interrupt fallback', async () => {
analytics.setTag('program_id', 'warehouse-source');
await analytics.shutdown('success');
// start-tui's ctrl+c fallback fires this on every TUI teardown.
await analytics.shutdown('cancelled');
const finishedCalls = mockPostHogInstance.capture.mock.calls.filter(
([arg]) => arg.event === 'setup wizard finished',
);
expect(finishedCalls).toHaveLength(1);
expect(finishedCalls[0][0].properties).toMatchObject({
status: 'success',
});
});
});
describe('groups (before_send injection)', () => {
type TestEvent = Record<string, unknown> & {
groups?: Record<string, string>;
};
type BeforeSendFn = (event: TestEvent | null) => TestEvent | null;
const getBeforeSend = (): BeforeSendFn =>
(MockedPostHog.mock.calls[0][1] as { before_send: BeforeSendFn })
.before_send;
it('does not attach groups before setGroups is called', () => {
const beforeSend = getBeforeSend();
const event = { event: 'x', distinctId: 'd', properties: {} };
expect(beforeSend(event)).toBe(event);
expect(event).not.toHaveProperty('groups');
});
it('injects the active group map into every event', () => {
analytics.setGroups({
instance: 'https://us.posthog.com',
organization: 'org-1',
project: 'team-uuid',
});
const beforeSend = getBeforeSend();
const result = beforeSend({
event: 'x',
distinctId: 'd',
properties: {},
});
expect(result?.groups).toEqual({
instance: 'https://us.posthog.com',
organization: 'org-1',
project: 'team-uuid',
});
});
it('lets per-event groups override the active map', () => {
analytics.setGroups({ instance: 'https://us.posthog.com', project: 'a' });
const beforeSend = getBeforeSend();
const result = beforeSend({
event: 'x',
distinctId: 'd',
properties: {},
groups: { project: 'override' },
});
expect(result?.groups).toEqual({
instance: 'https://us.posthog.com',
project: 'override',
});
});
it('passes null events through untouched', () => {
analytics.setGroups({ instance: 'https://us.posthog.com' });
const beforeSend = getBeforeSend();
expect(beforeSend(null)).toBeNull();
});
});
describe('groupsFromUser', () => {
const userWith = (overrides: Partial<ApiUser>): ApiUser =>
({
distinct_id: 'd',
organization: { id: 'org-1' },
team: { id: 1, uuid: 'team-uuid', organization: 'org-1' },
organizations: [],
...overrides,
} as unknown as ApiUser);
it('always includes the host as the instance group', () => {
expect(groupsFromUser(null, 'https://us.posthog.com')).toEqual({
instance: 'https://us.posthog.com',
});
});
it('maps org id, customer id, and team uuid (not numeric project id)', () => {
const user = userWith({
organization: {
id: 'org-uuid',
customer_id: 'cus_123',
} as ApiUser['organization'],
team: {
id: 42,
uuid: 'team-uuid',
organization: 'org-uuid',
} as ApiUser['team'],
});
expect(groupsFromUser(user, 'https://eu.posthog.com')).toEqual({
instance: 'https://eu.posthog.com',
organization: 'org-uuid',
customer: 'cus_123',
project: 'team-uuid',
});
});
it('omits optional keys that are absent', () => {
const user = userWith({
organization: { id: 'org-uuid' } as ApiUser['organization'],
team: { id: 42, organization: 'org-uuid' } as ApiUser['team'],
});
expect(groupsFromUser(user, 'https://us.posthog.com')).toEqual({
instance: 'https://us.posthog.com',
organization: 'org-uuid',
});
});
});
describe('integration with other methods', () => {
it('should work correctly with setTag and captureException', () => {
const error = new Error('Test error');
analytics.setTag('integration', 'nextjs');
analytics.setTag('localMcp', true);
analytics.setTag('debug', false);
analytics.captureException(error, {
arguments: JSON.stringify({ installDir: '/test' }),
step: 'wizard-execution',
});
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
'test-uuid',
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
integration: 'nextjs',
localMcp: true,
debug: false,
arguments: JSON.stringify({ installDir: '/test' }),
step: 'wizard-execution',
},
);
});
it('attributes exceptions to the identified user', () => {
const error = new Error('Test error');
const distinctId = 'user-456';
analytics.identifyUser({ distinct_id: distinctId } as unknown as ApiUser);
analytics.setTag('integration', 'svelte');
analytics.captureException(error);
expect(mockPostHogInstance.captureException).toHaveBeenCalledWith(
error,
distinctId,
{
team: ANALYTICS_TEAM_TAG,
$app_name: 'wizard',
build: 'dev',
run_id: 'run-uuid',
run_surface: 'local',
version: VERSION,
$session_id: 'session-uuid',
integration: 'svelte',
},
);
});
});
});