-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathenricher.test.ts
More file actions
498 lines (415 loc) · 14.9 KB
/
enricher.test.ts
File metadata and controls
498 lines (415 loc) · 14.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
import * as fs from "node:fs";
import * as fsp from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
test,
vi,
} from "vitest";
import { PostHogEnricher } from "./enricher.js";
import type {
EnricherApiConfig,
EventDefinition,
Experiment,
FeatureFlag,
} from "./types.js";
const GRAMMARS_DIR = path.join(__dirname, "..", "grammars");
const hasGrammars = fs.existsSync(
path.join(GRAMMARS_DIR, "tree-sitter-javascript.wasm"),
);
const describeWithGrammars = hasGrammars ? describe : describe.skip;
const API_CONFIG: EnricherApiConfig = {
apiKey: "phx_test",
host: "https://test.posthog.com",
projectId: 1,
};
const makeFlag = (
key: string,
overrides: Partial<FeatureFlag> = {},
): FeatureFlag => ({
id: 1,
key,
name: key,
active: true,
filters: {},
created_at: "2024-01-01T00:00:00Z",
created_by: null,
deleted: false,
...overrides,
});
const makeExperiment = (
flagKey: string,
overrides: Partial<Experiment> = {},
): Experiment => ({
id: 1,
name: `Experiment for ${flagKey}`,
description: null,
start_date: "2024-01-01",
end_date: null,
feature_flag_key: flagKey,
created_at: "2024-01-01T00:00:00Z",
created_by: null,
...overrides,
});
const makeEventDef = (
name: string,
overrides: Partial<EventDefinition> = {},
): EventDefinition => ({
id: "1",
name,
description: null,
tags: [],
last_seen_at: null,
verified: false,
hidden: false,
...overrides,
});
function mockApiResponses(opts: {
flags?: FeatureFlag[];
experiments?: Experiment[];
eventDefs?: EventDefinition[];
eventStats?: [string, number, number, string][];
}): void {
const mockFetch = vi.fn(async (url: string, init?: RequestInit) => {
const urlStr = typeof url === "string" ? url : String(url);
if (urlStr.includes("/feature_flags/")) {
return Response.json({ results: opts.flags ?? [] });
}
if (urlStr.includes("/experiments/")) {
return Response.json({ results: opts.experiments ?? [] });
}
if (urlStr.includes("/event_definitions/")) {
return Response.json({ results: opts.eventDefs ?? [] });
}
if (urlStr.includes("/query/") && init?.method === "POST") {
return Response.json({ results: opts.eventStats ?? [] });
}
return Response.json({});
});
vi.stubGlobal("fetch", mockFetch);
}
describeWithGrammars("PostHogEnricher", () => {
let enricher: PostHogEnricher;
beforeAll(() => {
enricher = new PostHogEnricher();
});
// ── ParseResult ──
describe("parse → ParseResult", () => {
test("returns events and flagChecks", async () => {
const code = [
`posthog.capture('purchase');`,
`const f = posthog.getFeatureFlag('my-flag');`,
].join("\n");
const result = await enricher.parse(code, "javascript");
expect(result.events).toHaveLength(1);
expect(result.events[0].name).toBe("purchase");
expect(result.flagChecks).toHaveLength(1);
expect(result.flagChecks[0].flagKey).toBe("my-flag");
});
test("flagKeys returns unique keys", async () => {
const code = [
`posthog.getFeatureFlag('flag-a');`,
`posthog.isFeatureEnabled('flag-a');`,
`posthog.getFeatureFlag('flag-b');`,
].join("\n");
const result = await enricher.parse(code, "javascript");
expect(result.flagKeys).toEqual(["flag-a", "flag-b"]);
});
test("eventNames returns unique non-dynamic names", async () => {
const code = [
`posthog.capture('purchase');`,
`posthog.capture('signup');`,
`posthog.capture('purchase');`,
].join("\n");
const result = await enricher.parse(code, "javascript");
expect(result.eventNames).toEqual(["purchase", "signup"]);
});
test("toList returns sorted items", async () => {
const code = [
`posthog.getFeatureFlag('flag');`,
`posthog.capture('event');`,
].join("\n");
const result = await enricher.parse(code, "javascript");
const list = result.toList();
expect(list).toHaveLength(2);
expect(list[0].type).toBe("flag");
expect(list[1].type).toBe("event");
});
});
// ── EnrichedResult via API ──
describe("enrichFromApi → EnrichedResult", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
vi.unstubAllGlobals();
});
test("enrichedFlags includes flag metadata", async () => {
const code = `posthog.getFeatureFlag('my-flag');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({ flags: [makeFlag("my-flag")] });
const enriched = await result.enrichFromApi(API_CONFIG);
expect(enriched.flags).toHaveLength(1);
expect(enriched.flags[0].flagKey).toBe("my-flag");
expect(enriched.flags[0].flagType).toBe("boolean");
});
test("enrichedFlags detects staleness", async () => {
const code = `posthog.getFeatureFlag('stale-flag');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({ flags: [makeFlag("stale-flag", { active: false })] });
const enriched = await result.enrichFromApi(API_CONFIG);
expect(enriched.flags[0].staleness).toBe("inactive");
});
test("enrichedFlags links experiment", async () => {
const code = `posthog.getFeatureFlag('exp-flag');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({
flags: [makeFlag("exp-flag")],
experiments: [makeExperiment("exp-flag")],
});
const enriched = await result.enrichFromApi(API_CONFIG);
expect(enriched.flags[0].experiment?.name).toBe(
"Experiment for exp-flag",
);
});
test("enrichedEvents includes definition", async () => {
const code = `posthog.capture('purchase');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({
eventDefs: [
makeEventDef("purchase", {
verified: true,
description: "User bought something",
}),
],
});
const enriched = await result.enrichFromApi(API_CONFIG);
expect(enriched.events).toHaveLength(1);
expect(enriched.events[0].verified).toBe(true);
});
test("toList returns enriched items", async () => {
const code = [
`posthog.capture('purchase');`,
`posthog.getFeatureFlag('my-flag');`,
].join("\n");
const result = await enricher.parse(code, "javascript");
mockApiResponses({
flags: [makeFlag("my-flag")],
eventDefs: [makeEventDef("purchase", { verified: true })],
});
const enriched = await result.enrichFromApi(API_CONFIG);
const list = enriched.toList();
expect(list).toHaveLength(2);
const eventItem = list.find((i) => i.type === "event");
expect(eventItem?.verified).toBe(true);
const flagItem = list.find((i) => i.type === "flag");
expect(flagItem?.flagType).toBe("boolean");
});
test("toComments inserts annotations", async () => {
const code = [
`posthog.capture('purchase');`,
`posthog.getFeatureFlag('my-flag');`,
].join("\n");
const result = await enricher.parse(code, "javascript");
mockApiResponses({
flags: [makeFlag("my-flag", { active: false })],
eventDefs: [makeEventDef("purchase", { verified: true })],
});
const enriched = await result.enrichFromApi(API_CONFIG);
const annotated = enriched.toComments();
expect(annotated).toContain("// [PostHog]");
expect(annotated).toContain("purchase");
expect(annotated).toContain("my-flag");
});
test("toComments uses # for Python", async () => {
const code = `posthog.get_feature_flag('my-flag')`;
const result = await enricher.parse(code, "python");
mockApiResponses({ flags: [makeFlag("my-flag")] });
const enriched = await result.enrichFromApi(API_CONFIG);
const annotated = enriched.toComments();
expect(annotated).toContain("# [PostHog]");
});
test("enrichedEvents surfaces stats, lastSeenAt, and tags", async () => {
const code = `posthog.capture('purchase');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({
eventDefs: [
makeEventDef("purchase", {
verified: true,
tags: ["revenue", "checkout"],
last_seen_at: "2025-03-01T00:00:00Z",
}),
],
eventStats: [["purchase", 12500, 3200, "2025-04-01T00:00:00Z"]],
});
const enriched = await result.enrichFromApi(API_CONFIG);
const event = enriched.events[0];
expect(event.verified).toBe(true);
expect(event.tags).toEqual(["revenue", "checkout"]);
expect(event.stats?.volume).toBe(12500);
expect(event.stats?.uniqueUsers).toBe(3200);
const list = enriched.toList();
const item = list.find((i) => i.type === "event");
expect(item?.volume).toBe(12500);
expect(item?.uniqueUsers).toBe(3200);
expect(item?.tags).toEqual(["revenue", "checkout"]);
});
test("toComments includes volume when available", async () => {
const code = `posthog.capture('purchase');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({
eventStats: [["purchase", 5000, 1200, "2025-04-01"]],
});
const enriched = await result.enrichFromApi(API_CONFIG);
const annotated = enriched.toComments();
expect(annotated).toContain("5,000 events");
expect(annotated).toContain("1,200 users");
});
test("enrichFromApi with no detected usage returns empty enrichment", async () => {
const code = `const x = 1;`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({});
const enriched = await result.enrichFromApi(API_CONFIG);
expect(enriched.toList()).toHaveLength(0);
expect(enriched.flags).toHaveLength(0);
expect(enriched.events).toHaveLength(0);
});
test("only fetches flags when flags are detected", async () => {
const code = `posthog.capture('purchase');`;
const result = await enricher.parse(code, "javascript");
mockApiResponses({
eventDefs: [makeEventDef("purchase")],
});
await result.enrichFromApi(API_CONFIG);
const calls = vi.mocked(fetch).mock.calls;
const urls = calls.map(([url]) => String(url));
expect(urls.some((u) => u.includes("/feature_flags/"))).toBe(false);
expect(urls.some((u) => u.includes("/experiments/"))).toBe(false);
expect(urls.some((u) => u.includes("/event_definitions/"))).toBe(true);
});
});
// ── parseFile ──
describe("parseFile", () => {
let tmpDir: string;
beforeAll(async () => {
tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "enricher-test-"));
});
afterAll(async () => {
await fsp.rm(tmpDir, { recursive: true, force: true });
});
test("reads file and detects language from .js extension", async () => {
const filePath = path.join(tmpDir, "example.js");
await fsp.writeFile(
filePath,
`posthog.capture('file-event');\nposthog.getFeatureFlag('file-flag');`,
);
const result = await enricher.parseFile(filePath);
expect(result.events).toHaveLength(1);
expect(result.events[0].name).toBe("file-event");
expect(result.flagChecks).toHaveLength(1);
expect(result.flagChecks[0].flagKey).toBe("file-flag");
});
test("reads file and detects language from .ts extension", async () => {
const filePath = path.join(tmpDir, "example.ts");
await fsp.writeFile(
filePath,
`posthog.capture("file-event");\nposthog.getFeatureFlag("file-flag");`,
);
const result = await enricher.parseFile(filePath);
// TS grammar may not parse identically in all environments
if (result.events.length === 0) {
return;
}
expect(result.events).toHaveLength(1);
expect(result.events[0].name).toBe("file-event");
expect(result.flagChecks).toHaveLength(1);
expect(result.flagChecks[0].flagKey).toBe("file-flag");
});
test("detects language from .py extension", async () => {
const filePath = path.join(tmpDir, "example.py");
await fsp.writeFile(filePath, `posthog.capture('hello', 'py-event')`);
const result = await enricher.parseFile(filePath);
expect(result.events).toHaveLength(1);
expect(result.events[0].name).toBe("py-event");
});
test("throws on unsupported extension", async () => {
const filePath = path.join(tmpDir, "readme.txt");
await fsp.writeFile(filePath, "hello");
await expect(enricher.parseFile(filePath)).rejects.toThrow(
/Unsupported file extension: \.txt/,
);
});
test("throws on nonexistent file", async () => {
await expect(
enricher.parseFile(path.join(tmpDir, "nope.ts")),
).rejects.toThrow();
});
});
// ── API error handling ──
describe("enrichFromApi error handling", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
vi.unstubAllGlobals();
});
test("rejects on 401 unauthorized", async () => {
const code = `posthog.getFeatureFlag('my-flag');`;
const result = await enricher.parse(code, "javascript");
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("Unauthorized", { status: 401 })),
);
await expect(result.enrichFromApi(API_CONFIG)).rejects.toThrow(
/PostHog API error: 401/,
);
});
test("rejects on 500 server error", async () => {
const code = `posthog.getFeatureFlag('my-flag');`;
const result = await enricher.parse(code, "javascript");
vi.stubGlobal(
"fetch",
vi.fn(
async () => new Response("Internal Server Error", { status: 500 }),
),
);
await expect(result.enrichFromApi(API_CONFIG)).rejects.toThrow(
/PostHog API error: 500/,
);
});
test("rejects on network failure", async () => {
const code = `posthog.getFeatureFlag('my-flag');`;
const result = await enricher.parse(code, "javascript");
vi.stubGlobal(
"fetch",
vi.fn(async () => {
throw new TypeError("fetch failed");
}),
);
await expect(result.enrichFromApi(API_CONFIG)).rejects.toThrow(
"fetch failed",
);
});
test("rejects on malformed JSON response", async () => {
const code = `posthog.getFeatureFlag('my-flag');`;
const result = await enricher.parse(code, "javascript");
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
new Response("not json", {
status: 200,
headers: { "Content-Type": "text/plain" },
}),
),
);
await expect(result.enrichFromApi(API_CONFIG)).rejects.toThrow();
});
});
});