@testchimp/flags 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,272 @@
1
+ // src/shared/header.ts
2
+ var FLAG_HEADER = "x-testchimp-flags";
3
+ var FLAG_TRUNCATED_HEADER = "x-testchimp-flags-truncated";
4
+ var MAX_HEADER_BYTES = 4096;
5
+ var UNKNOWN_PROVIDER = "unknown";
6
+ var MAX_COLLECTED_ENTRIES = 1e3;
7
+ var FlagCollector = class {
8
+ constructor() {
9
+ this.entries = /* @__PURE__ */ new Map();
10
+ }
11
+ add(flagKey, variant, providerId = UNKNOWN_PROVIDER) {
12
+ if (!flagKey) return;
13
+ const key = `${flagKey}\0${variant}`;
14
+ if (this.entries.has(key) || this.entries.size >= MAX_COLLECTED_ENTRIES) return;
15
+ this.entries.set(key, { k: flagKey, v: variant, p: providerId || UNKNOWN_PROVIDER });
16
+ }
17
+ get size() {
18
+ return this.entries.size;
19
+ }
20
+ list() {
21
+ return [...this.entries.values()];
22
+ }
23
+ };
24
+ function utf8ByteLength(text) {
25
+ return new TextEncoder().encode(text).length;
26
+ }
27
+ function base64UrlEncode(text) {
28
+ const bytes = new TextEncoder().encode(text);
29
+ let binary = "";
30
+ for (const byte of bytes) binary += String.fromCharCode(byte);
31
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
32
+ }
33
+ function encodeFlagHeader(entries) {
34
+ const kept = [];
35
+ let truncated = false;
36
+ for (const entry of entries) {
37
+ const candidate = `v1.${base64UrlEncode(JSON.stringify([...kept, entry]))}`;
38
+ if (utf8ByteLength(candidate) > MAX_HEADER_BYTES) {
39
+ truncated = true;
40
+ break;
41
+ }
42
+ kept.push(entry);
43
+ }
44
+ if (kept.length === 0) return { value: "", truncated };
45
+ return { value: `v1.${base64UrlEncode(JSON.stringify(kept))}`, truncated };
46
+ }
47
+ function flagResponseHeaders(collector) {
48
+ if (collector.size === 0) return void 0;
49
+ const { value, truncated } = encodeFlagHeader(collector.list());
50
+ if (value === "") return void 0;
51
+ const headers = { [FLAG_HEADER]: value };
52
+ if (truncated) headers[FLAG_TRUNCATED_HEADER] = "1";
53
+ return headers;
54
+ }
55
+
56
+ // src/shared/variant.ts
57
+ var MAX_VARIANT_LENGTH = 128;
58
+ function normalizeVariant(value) {
59
+ if (value === void 0) return void 0;
60
+ let text;
61
+ if (value === null) {
62
+ text = "null";
63
+ } else if (typeof value === "string") {
64
+ text = value;
65
+ } else if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
66
+ text = String(value);
67
+ } else {
68
+ try {
69
+ text = JSON.stringify(value);
70
+ } catch {
71
+ return void 0;
72
+ }
73
+ }
74
+ if (text === void 0) return void 0;
75
+ return text.length > MAX_VARIANT_LENGTH ? text.slice(0, MAX_VARIANT_LENGTH) : text;
76
+ }
77
+
78
+ // src/shared/openfeature.ts
79
+ function openFeatureHook(report) {
80
+ return {
81
+ after(hookContext, details) {
82
+ const flagKey = details?.flagKey || hookContext?.flagKey;
83
+ if (!flagKey) return;
84
+ const variant = details?.variant !== void 0 && details.variant !== "" ? details.variant : details?.value;
85
+ report(flagKey, variant, "openfeature");
86
+ }
87
+ };
88
+ }
89
+
90
+ // src/server/als.ts
91
+ import { AsyncLocalStorage } from "async_hooks";
92
+ var STORE_KEY = /* @__PURE__ */ Symbol.for("@testchimp/flags:collector-store");
93
+ function collectorStorage() {
94
+ const g = globalThis;
95
+ let store = g[STORE_KEY];
96
+ if (!store) {
97
+ store = new AsyncLocalStorage();
98
+ g[STORE_KEY] = store;
99
+ }
100
+ return store;
101
+ }
102
+
103
+ // src/server/index.ts
104
+ function isEchoActive() {
105
+ const raw = (typeof process !== "undefined" ? process.env.TESTCHIMP_FLAG_ECHO : void 0) ?? "";
106
+ const value = raw.trim().toLowerCase();
107
+ return value === "1" || value === "true";
108
+ }
109
+ function reportFlag(flagKey, variant, providerId = UNKNOWN_PROVIDER) {
110
+ try {
111
+ if (!flagKey || !isEchoActive()) return;
112
+ const collector = collectorStorage().getStore();
113
+ if (!collector) return;
114
+ const v = normalizeVariant(variant);
115
+ if (v === void 0) return;
116
+ collector.add(flagKey, v, providerId);
117
+ } catch {
118
+ }
119
+ }
120
+ var wrappedResponses = /* @__PURE__ */ new WeakSet();
121
+ function applyFlagHeaders(res, collector) {
122
+ if (res.headersSent) return;
123
+ const headers = flagResponseHeaders(collector);
124
+ if (!headers) return;
125
+ for (const [name, value] of Object.entries(headers)) {
126
+ res.setHeader(name, value);
127
+ }
128
+ }
129
+ function attachHeaderWriter(res, collector) {
130
+ if (wrappedResponses.has(res)) return;
131
+ wrappedResponses.add(res);
132
+ const originalWriteHead = res.writeHead;
133
+ res.writeHead = function(...args) {
134
+ applyFlagHeaders(this, collector);
135
+ return originalWriteHead.apply(this, args);
136
+ };
137
+ }
138
+ function flagCollectionMiddleware() {
139
+ return function testchimpFlagCollection(_req, res, next) {
140
+ if (!isEchoActive()) {
141
+ next();
142
+ return;
143
+ }
144
+ const collector = new FlagCollector();
145
+ attachHeaderWriter(res, collector);
146
+ collectorStorage().run(collector, () => next());
147
+ };
148
+ }
149
+ var fastifyCollectors = /* @__PURE__ */ new WeakMap();
150
+ function fastifyFlagCollection(fastify, _opts, done) {
151
+ fastify.addHook("onRequest", (request, _reply, hookDone) => {
152
+ if (!isEchoActive()) {
153
+ hookDone();
154
+ return;
155
+ }
156
+ const collector = new FlagCollector();
157
+ fastifyCollectors.set(request.raw, collector);
158
+ collectorStorage().run(collector, () => hookDone());
159
+ });
160
+ fastify.addHook(
161
+ "onSend",
162
+ (request, reply, payload, hookDone) => {
163
+ const collector = fastifyCollectors.get(request.raw);
164
+ const headers = collector ? flagResponseHeaders(collector) : void 0;
165
+ if (headers) {
166
+ for (const [name, value] of Object.entries(headers)) reply.header(name, value);
167
+ }
168
+ hookDone(null, payload);
169
+ }
170
+ );
171
+ done();
172
+ }
173
+ fastifyFlagCollection[/* @__PURE__ */ Symbol.for("skip-override")] = true;
174
+ function findServerResponse(args) {
175
+ const candidate = args[1];
176
+ if (candidate && typeof candidate.setHeader === "function" && typeof candidate.writeHead === "function") {
177
+ return candidate;
178
+ }
179
+ return void 0;
180
+ }
181
+ function withResponseHeaders(response, collector) {
182
+ const headers = flagResponseHeaders(collector);
183
+ if (!headers) return response;
184
+ const next = new Response(response.body, {
185
+ status: response.status,
186
+ statusText: response.statusText,
187
+ headers: response.headers
188
+ });
189
+ for (const [name, value] of Object.entries(headers)) next.headers.set(name, value);
190
+ return next;
191
+ }
192
+ function withFlagCollection(handler) {
193
+ return async (...args) => {
194
+ if (!isEchoActive()) return handler(...args);
195
+ const collector = new FlagCollector();
196
+ const res = findServerResponse(args);
197
+ if (res) attachHeaderWriter(res, collector);
198
+ const result = await collectorStorage().run(collector, () => handler(...args));
199
+ if (typeof Response !== "undefined" && result instanceof Response) {
200
+ return withResponseHeaders(result, collector);
201
+ }
202
+ return result;
203
+ };
204
+ }
205
+ function createOpenFeatureServerHook() {
206
+ return openFeatureHook(reportFlag);
207
+ }
208
+ var instrumentedClients = /* @__PURE__ */ new WeakSet();
209
+ function launchDarklyNodeHook() {
210
+ return {
211
+ getMetadata: () => ({ name: "testchimp-flags" }),
212
+ afterEvaluation(hookContext, data, detail) {
213
+ if (hookContext?.flagKey) reportFlag(hookContext.flagKey, detail?.value, "launchdarkly");
214
+ return data;
215
+ }
216
+ };
217
+ }
218
+ function instrumentLaunchDarklyNode(client) {
219
+ if (!isEchoActive() || instrumentedClients.has(client)) return client;
220
+ const addHook = client.addHook;
221
+ if (typeof addHook !== "function") return client;
222
+ instrumentedClients.add(client);
223
+ addHook.call(client, launchDarklyNodeHook());
224
+ return client;
225
+ }
226
+ function wrapMethod(target, name, after) {
227
+ const holder = target;
228
+ const original = holder[name];
229
+ if (typeof original !== "function") return;
230
+ const fn = original;
231
+ try {
232
+ holder[name] = function(...args) {
233
+ const result = fn.apply(this, args);
234
+ if (result && typeof result.then === "function") {
235
+ return result.then((value) => {
236
+ after(args, value);
237
+ return value;
238
+ });
239
+ }
240
+ after(args, result);
241
+ return result;
242
+ };
243
+ } catch {
244
+ }
245
+ }
246
+ function instrumentPostHogNode(client) {
247
+ if (!isEchoActive() || instrumentedClients.has(client)) return client;
248
+ instrumentedClients.add(client);
249
+ const recordFirstArg = (args, value) => {
250
+ if (typeof args[0] === "string") reportFlag(args[0], value, "posthog");
251
+ };
252
+ wrapMethod(client, "getFeatureFlag", recordFirstArg);
253
+ wrapMethod(client, "isFeatureEnabled", recordFirstArg);
254
+ wrapMethod(client, "evaluateFlags", (_args, snapshot) => {
255
+ if (snapshot && typeof snapshot === "object") {
256
+ wrapMethod(snapshot, "getFlag", recordFirstArg);
257
+ wrapMethod(snapshot, "isEnabled", recordFirstArg);
258
+ }
259
+ });
260
+ return client;
261
+ }
262
+ export {
263
+ createOpenFeatureServerHook,
264
+ fastifyFlagCollection,
265
+ flagCollectionMiddleware,
266
+ instrumentLaunchDarklyNode,
267
+ instrumentPostHogNode,
268
+ isEchoActive,
269
+ reportFlag,
270
+ withFlagCollection
271
+ };
272
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shared/header.ts","../../src/shared/variant.ts","../../src/shared/openfeature.ts","../../src/server/als.ts","../../src/server/index.ts"],"sourcesContent":["/**\n * The echo header contract (see README, \"Header contract\"):\n *\n * x-testchimp-flags: v1.<base64url(JSON array of {k, v, p})>\n * x-testchimp-flags-truncated: 1 (only when entries were dropped to fit the cap)\n *\n * The encoded value stays within 4096 bytes. Entries are deduplicated by (k, v).\n */\n\nexport const FLAG_HEADER = 'x-testchimp-flags';\nexport const FLAG_TRUNCATED_HEADER = 'x-testchimp-flags-truncated';\nexport const MAX_HEADER_BYTES = 4096;\nexport const UNKNOWN_PROVIDER = 'unknown';\n\n/** Bounds per-request memory. A request that evaluates more distinct arms than this keeps the first ones. */\nconst MAX_COLLECTED_ENTRIES = 1000;\n\nexport interface FlagEntry {\n /** Flag key. */\n k: string;\n /** Arm (variant) value, already normalized to a string. */\n v: string;\n /** Provider id: openfeature, launchdarkly, posthog, statsig or unknown. */\n p: string;\n}\n\n/** Per-request set of distinct (flag, arm) pairs. The first provider seen for a pair wins. */\nexport class FlagCollector {\n private readonly entries = new Map<string, FlagEntry>();\n\n add(flagKey: string, variant: string, providerId: string = UNKNOWN_PROVIDER): void {\n if (!flagKey) return;\n const key = `${flagKey}\\u0000${variant}`;\n if (this.entries.has(key) || this.entries.size >= MAX_COLLECTED_ENTRIES) return;\n this.entries.set(key, { k: flagKey, v: variant, p: providerId || UNKNOWN_PROVIDER });\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n list(): FlagEntry[] {\n return [...this.entries.values()];\n }\n}\n\nfunction utf8ByteLength(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\n/** base64url without padding, computed from UTF-8 bytes. Uses btoa, so it runs in browsers and Node. */\nexport function base64UrlEncode(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/**\n * Encode entries under the 4096-byte cap. Keeps the first entries that fit, in order, and reports whether any\n * were dropped. The value is empty when not even the first entry fits.\n */\nexport function encodeFlagHeader(entries: readonly FlagEntry[]): { value: string; truncated: boolean } {\n const kept: FlagEntry[] = [];\n let truncated = false;\n for (const entry of entries) {\n const candidate = `v1.${base64UrlEncode(JSON.stringify([...kept, entry]))}`;\n if (utf8ByteLength(candidate) > MAX_HEADER_BYTES) {\n truncated = true;\n break;\n }\n kept.push(entry);\n }\n if (kept.length === 0) return { value: '', truncated };\n return { value: `v1.${base64UrlEncode(JSON.stringify(kept))}`, truncated };\n}\n\n/** Headers to add to a response, or undefined when there is nothing to report. */\nexport function flagResponseHeaders(collector: FlagCollector): Record<string, string> | undefined {\n if (collector.size === 0) return undefined;\n const { value, truncated } = encodeFlagHeader(collector.list());\n if (value === '') return undefined;\n const headers: Record<string, string> = { [FLAG_HEADER]: value };\n if (truncated) headers[FLAG_TRUNCATED_HEADER] = '1';\n return headers;\n}\n","/** Longest variant string kept. JSON and number values with no named variations can be long. */\nexport const MAX_VARIANT_LENGTH = 128;\n\n/**\n * Normalize a flag value to the string the coverage model stores, matching `@testchimp/playwright`:\n * booleans become \"true\"/\"false\", numbers become their decimal text, objects become JSON. Returns undefined\n * when the value has no representation (for example a function), so the caller skips it.\n */\nexport function normalizeVariant(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n let text: string | undefined;\n if (value === null) {\n text = 'null';\n } else if (typeof value === 'string') {\n text = value;\n } else if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n text = String(value);\n } else {\n try {\n text = JSON.stringify(value);\n } catch {\n return undefined;\n }\n }\n if (text === undefined) return undefined;\n return text.length > MAX_VARIANT_LENGTH ? text.slice(0, MAX_VARIANT_LENGTH) : text;\n}\n","/**\n * OpenFeature hook shared by the web and server entry points. It is structural: it does not import\n * `@openfeature/*`, so the package has no runtime dependency on OpenFeature. The hook object is what the\n * OpenFeature SDK expects: an object with an `after(hookContext, evaluationDetails)` method.\n */\n\nexport type ReportFlag = (flagKey: string, variant: unknown, providerId: string) => void;\n\nexport interface HookContextLike {\n flagKey?: string;\n}\n\nexport interface EvaluationDetailsLike {\n flagKey?: string;\n variant?: string;\n value?: unknown;\n}\n\nexport function openFeatureHook(report: ReportFlag) {\n return {\n after(hookContext: HookContextLike | undefined, details: EvaluationDetailsLike | undefined): void {\n const flagKey = details?.flagKey || hookContext?.flagKey;\n if (!flagKey) return;\n // Named variant when the provider gives one, otherwise the resolved value.\n const variant = details?.variant !== undefined && details.variant !== '' ? details.variant : details?.value;\n report(flagKey, variant, 'openfeature');\n },\n };\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { FlagCollector } from '../shared/header';\n\n/**\n * The request-scoped collector. It lives on globalThis under a Symbol.for key, so that two copies of this\n * package in one process (for example a bundled and an installed copy) share one store.\n */\nconst STORE_KEY = Symbol.for('@testchimp/flags:collector-store');\n\nexport function collectorStorage(): AsyncLocalStorage<FlagCollector> {\n const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<FlagCollector> | undefined>;\n let store = g[STORE_KEY];\n if (!store) {\n store = new AsyncLocalStorage<FlagCollector>();\n g[STORE_KEY] = store;\n }\n return store;\n}\n","/**\n * `@testchimp/flags/server`: echo the flag arms a request evaluated back to the test in a response header.\n *\n * Activation: nothing happens unless `TESTCHIMP_FLAG_ECHO=1` (or `true`) is set in the process env. Set it only in\n * test environments. Prod never sets it, so no header is ever added and no request state is kept.\n *\n * Collection is per request, through AsyncLocalStorage, so concurrent requests never see each other's flags.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { FlagCollector, flagResponseHeaders, UNKNOWN_PROVIDER } from '../shared/header';\nimport { normalizeVariant } from '../shared/variant';\nimport { openFeatureHook } from '../shared/openfeature';\nimport { collectorStorage } from './als';\n\n/** True when `TESTCHIMP_FLAG_ECHO` is 1 or true. */\nexport function isEchoActive(): boolean {\n const raw = (typeof process !== 'undefined' ? process.env.TESTCHIMP_FLAG_ECHO : undefined) ?? '';\n const value = raw.trim().toLowerCase();\n return value === '1' || value === 'true';\n}\n\n/**\n * Low-level: record one evaluation in the current request's collector. Does nothing outside a request or when\n * echo is off. `variant` is normalized (booleans become \"true\"/\"false\", objects JSON).\n */\nexport function reportFlag(flagKey: string, variant: unknown, providerId: string = UNKNOWN_PROVIDER): void {\n try {\n if (!flagKey || !isEchoActive()) return;\n const collector = collectorStorage().getStore();\n if (!collector) return;\n const v = normalizeVariant(variant);\n if (v === undefined) return;\n collector.add(flagKey, v, providerId);\n } catch {\n /* reporting must never affect the response */\n }\n}\n\n/** Responses whose writeHead is already wrapped. */\nconst wrappedResponses = new WeakSet<object>();\n\nfunction applyFlagHeaders(res: ServerResponse, collector: FlagCollector): void {\n if (res.headersSent) return;\n const headers = flagResponseHeaders(collector);\n if (!headers) return;\n for (const [name, value] of Object.entries(headers)) {\n res.setHeader(name, value);\n }\n}\n\n/**\n * Node sends headers at the first write or at end(). Both go through writeHead, so the header is added there,\n * after the handler has finished evaluating flags for that request.\n */\nfunction attachHeaderWriter(res: ServerResponse, collector: FlagCollector): void {\n if (wrappedResponses.has(res)) return;\n wrappedResponses.add(res);\n const originalWriteHead = res.writeHead;\n res.writeHead = function (this: ServerResponse, ...args: unknown[]) {\n applyFlagHeaders(this, collector);\n return (originalWriteHead as (...a: unknown[]) => ServerResponse).apply(this, args);\n } as ServerResponse['writeHead'];\n}\n\n/**\n * Express and Connect middleware:\n * app.use(flagCollectionMiddleware());\n * Register it before the routes whose flags you want echoed.\n */\nexport function flagCollectionMiddleware() {\n return function testchimpFlagCollection(_req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void): void {\n if (!isEchoActive()) {\n next();\n return;\n }\n const collector = new FlagCollector();\n attachHeaderWriter(res, collector);\n collectorStorage().run(collector, () => next());\n };\n}\n\ninterface FastifyRequestLike {\n raw: object;\n}\n\ninterface FastifyReplyLike {\n header: (name: string, value: string) => unknown;\n}\n\ninterface FastifyInstanceLike {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addHook: (name: string, hook: (...args: any[]) => void) => unknown;\n}\n\nconst fastifyCollectors = new WeakMap<object, FlagCollector>();\n\n/**\n * Fastify plugin: `await app.register(fastifyFlagCollection)`. It is not encapsulated (like fastify-plugin), so\n * its hooks apply to every route.\n */\nexport function fastifyFlagCollection(fastify: FastifyInstanceLike, _opts: unknown, done: (err?: Error) => void): void {\n fastify.addHook('onRequest', (request: FastifyRequestLike, _reply: unknown, hookDone: (err?: Error) => void) => {\n if (!isEchoActive()) {\n hookDone();\n return;\n }\n const collector = new FlagCollector();\n fastifyCollectors.set(request.raw, collector);\n collectorStorage().run(collector, () => hookDone());\n });\n fastify.addHook(\n 'onSend',\n (\n request: FastifyRequestLike,\n reply: FastifyReplyLike,\n payload: unknown,\n hookDone: (err: Error | null, payload?: unknown) => void\n ) => {\n const collector = fastifyCollectors.get(request.raw);\n const headers = collector ? flagResponseHeaders(collector) : undefined;\n if (headers) {\n for (const [name, value] of Object.entries(headers)) reply.header(name, value);\n }\n hookDone(null, payload);\n }\n );\n done();\n}\n// Mark as not encapsulated, the same flag fastify-plugin sets, so the hooks above apply to all routes.\n(fastifyFlagCollection as unknown as Record<symbol, boolean>)[Symbol.for('skip-override')] = true;\n\nfunction findServerResponse(args: unknown[]): ServerResponse | undefined {\n const candidate = args[1] as Partial<ServerResponse> | undefined;\n if (candidate && typeof candidate.setHeader === 'function' && typeof candidate.writeHead === 'function') {\n return candidate as ServerResponse;\n }\n return undefined;\n}\n\nfunction withResponseHeaders(response: Response, collector: FlagCollector): Response {\n const headers = flagResponseHeaders(collector);\n if (!headers) return response;\n const next = new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n for (const [name, value] of Object.entries(headers)) next.headers.set(name, value);\n return next;\n}\n\n/**\n * Generic wrapper for any handler. It covers Next.js App Router route handlers (they return a `Response`) and\n * Pages-style or raw Node handlers that take `(req, res)` and write to `res`.\n *\n * export const GET = withFlagCollection(async (request: Request) => Response.json(...));\n */\nexport function withFlagCollection<A extends unknown[], R>(\n handler: (...args: A) => R | Promise<R>\n): (...args: A) => Promise<R> {\n return async (...args: A): Promise<R> => {\n if (!isEchoActive()) return handler(...args);\n const collector = new FlagCollector();\n const res = findServerResponse(args);\n if (res) attachHeaderWriter(res, collector);\n const result = (await collectorStorage().run(collector, () => handler(...args))) as R;\n if (typeof Response !== 'undefined' && result instanceof Response) {\n return withResponseHeaders(result, collector) as R;\n }\n return result;\n };\n}\n\n// ---- OpenFeature ----------------------------------------------------------\n\n/**\n * OpenFeature server SDK hook: `OpenFeature.setProvider(...)` then `OpenFeature.addHooks(createOpenFeatureServerHook())`.\n */\nexport function createOpenFeatureServerHook() {\n return openFeatureHook(reportFlag);\n}\n\n// ---- LaunchDarkly Node ----------------------------------------------------\n\nconst instrumentedClients = new WeakSet<object>();\n\ninterface LaunchDarklyNodeHookLike {\n getMetadata: () => { name: string };\n afterEvaluation: (hookContext: { flagKey?: string }, data: unknown, detail: { value?: unknown } | undefined) => unknown;\n}\n\nfunction launchDarklyNodeHook(): LaunchDarklyNodeHookLike {\n return {\n getMetadata: () => ({ name: 'testchimp-flags' }),\n afterEvaluation(hookContext, data, detail) {\n if (hookContext?.flagKey) reportFlag(hookContext.flagKey, detail?.value, 'launchdarkly');\n return data;\n },\n };\n}\n\n/**\n * LaunchDarkly Node SDK (v9.3+). Adds a hook that records every variation result. Call it once, after\n * `init(...)`. Older SDKs without `addHook` are left alone.\n */\nexport function instrumentLaunchDarklyNode<T extends object>(client: T): T {\n if (!isEchoActive() || instrumentedClients.has(client)) return client;\n const addHook = (client as { addHook?: (hook: unknown) => void }).addHook;\n if (typeof addHook !== 'function') return client;\n instrumentedClients.add(client);\n addHook.call(client, launchDarklyNodeHook());\n return client;\n}\n\n// ---- PostHog Node ---------------------------------------------------------\n\ntype AnyFn = (...args: unknown[]) => unknown;\n\n/**\n * Wrap a method so `after(args, value)` runs with its result. A promise result is awaited first. The result the\n * caller gets is unchanged.\n */\nfunction wrapMethod(target: object, name: string, after: (args: unknown[], value: unknown) => void): void {\n const holder = target as Record<string, unknown>;\n const original = holder[name];\n if (typeof original !== 'function') return;\n const fn = original as AnyFn;\n try {\n holder[name] = function (this: unknown, ...args: unknown[]) {\n const result = fn.apply(this, args);\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<unknown>).then((value) => {\n after(args, value);\n return value;\n });\n }\n after(args, result);\n return result;\n };\n } catch {\n /* a frozen or read-only object is left as it is */\n }\n}\n\n/**\n * PostHog Node SDK. Wraps `getFeatureFlag`, `isFeatureEnabled` and `evaluateFlags` (including the `getFlag` and\n * `isEnabled` methods of the snapshot it returns). Call it once after creating the client.\n */\nexport function instrumentPostHogNode<T extends object>(client: T): T {\n if (!isEchoActive() || instrumentedClients.has(client)) return client;\n instrumentedClients.add(client);\n const recordFirstArg = (args: unknown[], value: unknown) => {\n if (typeof args[0] === 'string') reportFlag(args[0], value, 'posthog');\n };\n wrapMethod(client, 'getFeatureFlag', recordFirstArg);\n wrapMethod(client, 'isFeatureEnabled', recordFirstArg);\n wrapMethod(client, 'evaluateFlags', (_args, snapshot) => {\n if (snapshot && typeof snapshot === 'object') {\n wrapMethod(snapshot, 'getFlag', recordFirstArg);\n wrapMethod(snapshot, 'isEnabled', recordFirstArg);\n }\n });\n return client;\n}\n"],"mappings":";AASO,IAAM,cAAc;AACpB,IAAM,wBAAwB;AAC9B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAGhC,IAAM,wBAAwB;AAYvB,IAAM,gBAAN,MAAoB;AAAA,EAApB;AACL,SAAiB,UAAU,oBAAI,IAAuB;AAAA;AAAA,EAEtD,IAAI,SAAiB,SAAiB,aAAqB,kBAAwB;AACjF,QAAI,CAAC,QAAS;AACd,UAAM,MAAM,GAAG,OAAO,KAAS,OAAO;AACtC,QAAI,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,QAAQ,QAAQ,sBAAuB;AACzE,SAAK,QAAQ,IAAI,KAAK,EAAE,GAAG,SAAS,GAAG,SAAS,GAAG,cAAc,iBAAiB,CAAC;AAAA,EACrF;AAAA,EAEA,IAAI,OAAe;AACjB,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,OAAoB;AAClB,WAAO,CAAC,GAAG,KAAK,QAAQ,OAAO,CAAC;AAAA,EAClC;AACF;AAEA,SAAS,eAAe,MAAsB;AAC5C,SAAO,IAAI,YAAY,EAAE,OAAO,IAAI,EAAE;AACxC;AAGO,SAAS,gBAAgB,MAAsB;AACpD,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;AAC3C,MAAI,SAAS;AACb,aAAW,QAAQ,MAAO,WAAU,OAAO,aAAa,IAAI;AAC5D,SAAO,KAAK,MAAM,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OA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2
+
3
+ /** True only inside a TestChimp test. Use it to skip any setup that is not needed in production. */
4
+ declare function isTestChimpCaptureActive(): boolean;
5
+ /**
6
+ * Low-level: report one evaluation. `variant` is normalized (booleans become "true"/"false", objects JSON).
7
+ * `providerId` is the provider the value came from (`launchdarkly`, `posthog`, `openfeature` or your own id).
8
+ */
9
+ declare function reportFlag(flagKey: string, variant: unknown, providerId?: string): void;
10
+ /**
11
+ * OpenFeature web SDK hook. Add it globally or per client:
12
+ * OpenFeature.addHooks(createOpenFeatureHook());
13
+ * Reports the flag key and variant after each successful evaluation, falling back to the resolved value.
14
+ */
15
+ declare function createOpenFeatureHook(): {
16
+ after(hookContext: HookContextLike | undefined, details: EvaluationDetailsLike | undefined): void;
17
+ };
18
+ interface LaunchDarklyFlagUsedInspector {
19
+ type: 'flag-used';
20
+ name: string;
21
+ method: (flagKey: string, flagDetail: {
22
+ value?: unknown;
23
+ } | undefined) => void;
24
+ }
25
+ /** The LaunchDarkly `flag-used` inspector. Use `instrumentLaunchDarkly` instead unless you build options yourself. */
26
+ declare function launchDarklyInspector(): LaunchDarklyFlagUsedInspector;
27
+ /**
28
+ * LaunchDarkly JS client. Inspectors can only be set when the client is initialized, so pass the options you
29
+ * give to `LDClient.initialize` through this function. It returns a new options object with the inspector
30
+ * added, or the same options object unchanged when TestChimp is not capturing.
31
+ *
32
+ * const client = LDClient.initialize(id, context, instrumentLaunchDarkly({ bootstrap }));
33
+ */
34
+ declare function instrumentLaunchDarkly<T extends {
35
+ inspectors?: unknown[];
36
+ }>(options: T): T;
37
+ /**
38
+ * PostHog JS. PostHog reports each evaluation as a `$feature_flag_called` event, emitted through
39
+ * `posthog.capture`. This wraps `capture` on the instance and reads the event; the original call and its
40
+ * result are unchanged. Lookups made with `send_event: false` emit no event, so they are not captured.
41
+ *
42
+ * posthog.init(key, options); instrumentPostHog(posthog);
43
+ */
44
+ declare function instrumentPostHog<T extends object>(posthog: T): T;
45
+
46
+ export { createOpenFeatureHook, instrumentLaunchDarkly, instrumentPostHog, isTestChimpCaptureActive, launchDarklyInspector, reportFlag };
@@ -0,0 +1,46 @@
1
+ import { H as HookContextLike, E as EvaluationDetailsLike } from '../openfeature-BIO-k-VW.js';
2
+
3
+ /** True only inside a TestChimp test. Use it to skip any setup that is not needed in production. */
4
+ declare function isTestChimpCaptureActive(): boolean;
5
+ /**
6
+ * Low-level: report one evaluation. `variant` is normalized (booleans become "true"/"false", objects JSON).
7
+ * `providerId` is the provider the value came from (`launchdarkly`, `posthog`, `openfeature` or your own id).
8
+ */
9
+ declare function reportFlag(flagKey: string, variant: unknown, providerId?: string): void;
10
+ /**
11
+ * OpenFeature web SDK hook. Add it globally or per client:
12
+ * OpenFeature.addHooks(createOpenFeatureHook());
13
+ * Reports the flag key and variant after each successful evaluation, falling back to the resolved value.
14
+ */
15
+ declare function createOpenFeatureHook(): {
16
+ after(hookContext: HookContextLike | undefined, details: EvaluationDetailsLike | undefined): void;
17
+ };
18
+ interface LaunchDarklyFlagUsedInspector {
19
+ type: 'flag-used';
20
+ name: string;
21
+ method: (flagKey: string, flagDetail: {
22
+ value?: unknown;
23
+ } | undefined) => void;
24
+ }
25
+ /** The LaunchDarkly `flag-used` inspector. Use `instrumentLaunchDarkly` instead unless you build options yourself. */
26
+ declare function launchDarklyInspector(): LaunchDarklyFlagUsedInspector;
27
+ /**
28
+ * LaunchDarkly JS client. Inspectors can only be set when the client is initialized, so pass the options you
29
+ * give to `LDClient.initialize` through this function. It returns a new options object with the inspector
30
+ * added, or the same options object unchanged when TestChimp is not capturing.
31
+ *
32
+ * const client = LDClient.initialize(id, context, instrumentLaunchDarkly({ bootstrap }));
33
+ */
34
+ declare function instrumentLaunchDarkly<T extends {
35
+ inspectors?: unknown[];
36
+ }>(options: T): T;
37
+ /**
38
+ * PostHog JS. PostHog reports each evaluation as a `$feature_flag_called` event, emitted through
39
+ * `posthog.capture`. This wraps `capture` on the instance and reads the event; the original call and its
40
+ * result are unchanged. Lookups made with `send_event: false` emit no event, so they are not captured.
41
+ *
42
+ * posthog.init(key, options); instrumentPostHog(posthog);
43
+ */
44
+ declare function instrumentPostHog<T extends object>(posthog: T): T;
45
+
46
+ export { createOpenFeatureHook, instrumentLaunchDarkly, instrumentPostHog, isTestChimpCaptureActive, launchDarklyInspector, reportFlag };
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/web/index.ts
21
+ var web_exports = {};
22
+ __export(web_exports, {
23
+ createOpenFeatureHook: () => createOpenFeatureHook,
24
+ instrumentLaunchDarkly: () => instrumentLaunchDarkly,
25
+ instrumentPostHog: () => instrumentPostHog,
26
+ isTestChimpCaptureActive: () => isTestChimpCaptureActive,
27
+ launchDarklyInspector: () => launchDarklyInspector,
28
+ reportFlag: () => reportFlag
29
+ });
30
+ module.exports = __toCommonJS(web_exports);
31
+
32
+ // src/shared/variant.ts
33
+ var MAX_VARIANT_LENGTH = 128;
34
+ function normalizeVariant(value) {
35
+ if (value === void 0) return void 0;
36
+ let text;
37
+ if (value === null) {
38
+ text = "null";
39
+ } else if (typeof value === "string") {
40
+ text = value;
41
+ } else if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
42
+ text = String(value);
43
+ } else {
44
+ try {
45
+ text = JSON.stringify(value);
46
+ } catch {
47
+ return void 0;
48
+ }
49
+ }
50
+ if (text === void 0) return void 0;
51
+ return text.length > MAX_VARIANT_LENGTH ? text.slice(0, MAX_VARIANT_LENGTH) : text;
52
+ }
53
+
54
+ // src/shared/openfeature.ts
55
+ function openFeatureHook(report) {
56
+ return {
57
+ after(hookContext, details) {
58
+ const flagKey = details?.flagKey || hookContext?.flagKey;
59
+ if (!flagKey) return;
60
+ const variant = details?.variant !== void 0 && details.variant !== "" ? details.variant : details?.value;
61
+ report(flagKey, variant, "openfeature");
62
+ }
63
+ };
64
+ }
65
+
66
+ // src/web/index.ts
67
+ var instrumented = /* @__PURE__ */ new WeakSet();
68
+ function flagsGlobal() {
69
+ const candidate = globalThis.__TESTCHIMP_FLAGS__;
70
+ return candidate && typeof candidate.record === "function" ? candidate : void 0;
71
+ }
72
+ function isTestChimpCaptureActive() {
73
+ return flagsGlobal() !== void 0;
74
+ }
75
+ function reportFlag(flagKey, variant, providerId = "unknown") {
76
+ try {
77
+ const target = flagsGlobal();
78
+ if (!target || !flagKey) return;
79
+ const v = normalizeVariant(variant);
80
+ if (v === void 0) return;
81
+ target.record?.({ k: flagKey, v, p: providerId });
82
+ } catch {
83
+ }
84
+ }
85
+ function createOpenFeatureHook() {
86
+ return openFeatureHook(reportFlag);
87
+ }
88
+ function launchDarklyInspector() {
89
+ return {
90
+ type: "flag-used",
91
+ name: "testchimp-flags",
92
+ method: (flagKey, flagDetail) => reportFlag(flagKey, flagDetail?.value, "launchdarkly")
93
+ };
94
+ }
95
+ function instrumentLaunchDarkly(options) {
96
+ if (!isTestChimpCaptureActive()) return options;
97
+ const others = (options.inspectors ?? []).filter(
98
+ (inspector) => inspector?.name !== "testchimp-flags"
99
+ );
100
+ return { ...options, inspectors: [...others, launchDarklyInspector()] };
101
+ }
102
+ function instrumentPostHog(posthog) {
103
+ if (!isTestChimpCaptureActive() || instrumented.has(posthog)) return posthog;
104
+ const target = posthog;
105
+ const original = target.capture;
106
+ if (typeof original !== "function") return posthog;
107
+ instrumented.add(posthog);
108
+ target.capture = function(...args) {
109
+ try {
110
+ const [event, properties] = args;
111
+ if (event === "$feature_flag_called" && properties && typeof properties === "object") {
112
+ const p = properties;
113
+ if (typeof p.$feature_flag === "string") {
114
+ reportFlag(p.$feature_flag, p.$feature_flag_response, "posthog");
115
+ }
116
+ }
117
+ } catch {
118
+ }
119
+ return original.apply(this, args);
120
+ };
121
+ return posthog;
122
+ }
123
+ // Annotate the CommonJS export names for ESM import in node:
124
+ 0 && (module.exports = {
125
+ createOpenFeatureHook,
126
+ instrumentLaunchDarkly,
127
+ instrumentPostHog,
128
+ isTestChimpCaptureActive,
129
+ launchDarklyInspector,
130
+ reportFlag
131
+ });
132
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/web/index.ts","../../src/shared/variant.ts","../../src/shared/openfeature.ts"],"sourcesContent":["/**\n * `@testchimp/flags/web`: report flag evaluations made in the browser to a TestChimp test.\n *\n * Safety: every function here does nothing unless `globalThis.__TESTCHIMP_FLAGS__` exists. The TestChimp\n * Playwright fixture defines that global, and only in tests. In production there is no global, so the hooks\n * install no wrappers, make no calls and throw nothing.\n */\nimport { normalizeVariant } from '../shared/variant';\nimport { openFeatureHook } from '../shared/openfeature';\n\ninterface FlagsGlobal {\n record?: (entry: { k: string; v: string; p: string }) => void;\n}\n\nconst instrumented = new WeakSet<object>();\n\nfunction flagsGlobal(): FlagsGlobal | undefined {\n const candidate = (globalThis as unknown as { __TESTCHIMP_FLAGS__?: FlagsGlobal }).__TESTCHIMP_FLAGS__;\n return candidate && typeof candidate.record === 'function' ? candidate : undefined;\n}\n\n/** True only inside a TestChimp test. Use it to skip any setup that is not needed in production. */\nexport function isTestChimpCaptureActive(): boolean {\n return flagsGlobal() !== undefined;\n}\n\n/**\n * Low-level: report one evaluation. `variant` is normalized (booleans become \"true\"/\"false\", objects JSON).\n * `providerId` is the provider the value came from (`launchdarkly`, `posthog`, `openfeature` or your own id).\n */\nexport function reportFlag(flagKey: string, variant: unknown, providerId = 'unknown'): void {\n try {\n const target = flagsGlobal();\n if (!target || !flagKey) return;\n const v = normalizeVariant(variant);\n if (v === undefined) return;\n target.record?.({ k: flagKey, v, p: providerId });\n } catch {\n /* reporting must never affect the app */\n }\n}\n\n/**\n * OpenFeature web SDK hook. Add it globally or per client:\n * OpenFeature.addHooks(createOpenFeatureHook());\n * Reports the flag key and variant after each successful evaluation, falling back to the resolved value.\n */\nexport function createOpenFeatureHook() {\n return openFeatureHook(reportFlag);\n}\n\ninterface LaunchDarklyFlagUsedInspector {\n type: 'flag-used';\n name: string;\n method: (flagKey: string, flagDetail: { value?: unknown } | undefined) => void;\n}\n\n/** The LaunchDarkly `flag-used` inspector. Use `instrumentLaunchDarkly` instead unless you build options yourself. */\nexport function launchDarklyInspector(): LaunchDarklyFlagUsedInspector {\n return {\n type: 'flag-used',\n name: 'testchimp-flags',\n method: (flagKey, flagDetail) => reportFlag(flagKey, flagDetail?.value, 'launchdarkly'),\n };\n}\n\n/**\n * LaunchDarkly JS client. Inspectors can only be set when the client is initialized, so pass the options you\n * give to `LDClient.initialize` through this function. It returns a new options object with the inspector\n * added, or the same options object unchanged when TestChimp is not capturing.\n *\n * const client = LDClient.initialize(id, context, instrumentLaunchDarkly({ bootstrap }));\n */\nexport function instrumentLaunchDarkly<T extends { inspectors?: unknown[] }>(options: T): T {\n if (!isTestChimpCaptureActive()) return options;\n const others = (options.inspectors ?? []).filter(\n (inspector) => (inspector as { name?: string } | undefined)?.name !== 'testchimp-flags'\n );\n return { ...options, inspectors: [...others, launchDarklyInspector()] };\n}\n\ntype CaptureFn = (...args: unknown[]) => unknown;\n\n/**\n * PostHog JS. PostHog reports each evaluation as a `$feature_flag_called` event, emitted through\n * `posthog.capture`. This wraps `capture` on the instance and reads the event; the original call and its\n * result are unchanged. Lookups made with `send_event: false` emit no event, so they are not captured.\n *\n * posthog.init(key, options); instrumentPostHog(posthog);\n */\nexport function instrumentPostHog<T extends object>(posthog: T): T {\n if (!isTestChimpCaptureActive() || instrumented.has(posthog)) return posthog;\n const target = posthog as unknown as { capture?: CaptureFn };\n const original = target.capture;\n if (typeof original !== 'function') return posthog;\n instrumented.add(posthog);\n target.capture = function (this: unknown, ...args: unknown[]) {\n try {\n const [event, properties] = args;\n if (event === '$feature_flag_called' && properties && typeof properties === 'object') {\n const p = properties as Record<string, unknown>;\n if (typeof p.$feature_flag === 'string') {\n reportFlag(p.$feature_flag, p.$feature_flag_response, 'posthog');\n }\n }\n } catch {\n /* never affects the app */\n }\n return original.apply(this, args);\n };\n return posthog;\n}\n","/** Longest variant string kept. JSON and number values with no named variations can be long. */\nexport const MAX_VARIANT_LENGTH = 128;\n\n/**\n * Normalize a flag value to the string the coverage model stores, matching `@testchimp/playwright`:\n * booleans become \"true\"/\"false\", numbers become their decimal text, objects become JSON. Returns undefined\n * when the value has no representation (for example a function), so the caller skips it.\n */\nexport function normalizeVariant(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n let text: string | undefined;\n if (value === null) {\n text = 'null';\n } else if (typeof value === 'string') {\n text = value;\n } else if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n text = String(value);\n } else {\n try {\n text = JSON.stringify(value);\n } catch {\n return undefined;\n }\n }\n if (text === undefined) return undefined;\n return text.length > MAX_VARIANT_LENGTH ? text.slice(0, MAX_VARIANT_LENGTH) : text;\n}\n","/**\n * OpenFeature hook shared by the web and server entry points. It is structural: it does not import\n * `@openfeature/*`, so the package has no runtime dependency on OpenFeature. The hook object is what the\n * OpenFeature SDK expects: an object with an `after(hookContext, evaluationDetails)` method.\n */\n\nexport type ReportFlag = (flagKey: string, variant: unknown, providerId: string) => void;\n\nexport interface HookContextLike {\n flagKey?: string;\n}\n\nexport interface EvaluationDetailsLike {\n flagKey?: string;\n variant?: string;\n value?: unknown;\n}\n\nexport function openFeatureHook(report: ReportFlag) {\n return {\n after(hookContext: HookContextLike | undefined, details: EvaluationDetailsLike | undefined): void {\n const flagKey = details?.flagKey || hookContext?.flagKey;\n if (!flagKey) return;\n // Named variant when the provider gives one, otherwise the resolved value.\n const variant = details?.variant !== undefined && details.variant !== '' ? details.variant : details?.value;\n report(flagKey, variant, 'openfeature');\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,qBAAqB;AAO3B,SAAS,iBAAiB,OAAoC;AACnE,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI;AACJ,MAAI,UAAU,MAAM;AAClB,WAAO;AAAA,EACT,WAAW,OAAO,UAAU,UAAU;AACpC,WAAO;AAAA,EACT,WAAW,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AAC/F,WAAO,OAAO,KAAK;AAAA,EACrB,OAAO;AACL,QAAI;AACF,aAAO,KAAK,UAAU,KAAK;AAAA,IAC7B,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,MAAI,SAAS,OAAW,QAAO;AAC/B,SAAO,KAAK,SAAS,qBAAqB,KAAK,MAAM,GAAG,kBAAkB,IAAI;AAChF;;;ACRO,SAAS,gBAAgB,QAAoB;AAClD,SAAO;AAAA,IACL,MAAM,aAA0C,SAAkD;AAChG,YAAM,UAAU,SAAS,WAAW,aAAa;AACjD,UAAI,CAAC,QAAS;AAEd,YAAM,UAAU,SAAS,YAAY,UAAa,QAAQ,YAAY,KAAK,QAAQ,UAAU,SAAS;AACtG,aAAO,SAAS,SAAS,aAAa;AAAA,IACxC;AAAA,EACF;AACF;;;AFdA,IAAM,eAAe,oBAAI,QAAgB;AAEzC,SAAS,cAAuC;AAC9C,QAAM,YAAa,WAAgE;AACnF,SAAO,aAAa,OAAO,UAAU,WAAW,aAAa,YAAY;AAC3E;AAGO,SAAS,2BAAoC;AAClD,SAAO,YAAY,MAAM;AAC3B;AAMO,SAAS,WAAW,SAAiB,SAA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-0,0 +1,100 @@
1
+ // src/shared/variant.ts
2
+ var MAX_VARIANT_LENGTH = 128;
3
+ function normalizeVariant(value) {
4
+ if (value === void 0) return void 0;
5
+ let text;
6
+ if (value === null) {
7
+ text = "null";
8
+ } else if (typeof value === "string") {
9
+ text = value;
10
+ } else if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
11
+ text = String(value);
12
+ } else {
13
+ try {
14
+ text = JSON.stringify(value);
15
+ } catch {
16
+ return void 0;
17
+ }
18
+ }
19
+ if (text === void 0) return void 0;
20
+ return text.length > MAX_VARIANT_LENGTH ? text.slice(0, MAX_VARIANT_LENGTH) : text;
21
+ }
22
+
23
+ // src/shared/openfeature.ts
24
+ function openFeatureHook(report) {
25
+ return {
26
+ after(hookContext, details) {
27
+ const flagKey = details?.flagKey || hookContext?.flagKey;
28
+ if (!flagKey) return;
29
+ const variant = details?.variant !== void 0 && details.variant !== "" ? details.variant : details?.value;
30
+ report(flagKey, variant, "openfeature");
31
+ }
32
+ };
33
+ }
34
+
35
+ // src/web/index.ts
36
+ var instrumented = /* @__PURE__ */ new WeakSet();
37
+ function flagsGlobal() {
38
+ const candidate = globalThis.__TESTCHIMP_FLAGS__;
39
+ return candidate && typeof candidate.record === "function" ? candidate : void 0;
40
+ }
41
+ function isTestChimpCaptureActive() {
42
+ return flagsGlobal() !== void 0;
43
+ }
44
+ function reportFlag(flagKey, variant, providerId = "unknown") {
45
+ try {
46
+ const target = flagsGlobal();
47
+ if (!target || !flagKey) return;
48
+ const v = normalizeVariant(variant);
49
+ if (v === void 0) return;
50
+ target.record?.({ k: flagKey, v, p: providerId });
51
+ } catch {
52
+ }
53
+ }
54
+ function createOpenFeatureHook() {
55
+ return openFeatureHook(reportFlag);
56
+ }
57
+ function launchDarklyInspector() {
58
+ return {
59
+ type: "flag-used",
60
+ name: "testchimp-flags",
61
+ method: (flagKey, flagDetail) => reportFlag(flagKey, flagDetail?.value, "launchdarkly")
62
+ };
63
+ }
64
+ function instrumentLaunchDarkly(options) {
65
+ if (!isTestChimpCaptureActive()) return options;
66
+ const others = (options.inspectors ?? []).filter(
67
+ (inspector) => inspector?.name !== "testchimp-flags"
68
+ );
69
+ return { ...options, inspectors: [...others, launchDarklyInspector()] };
70
+ }
71
+ function instrumentPostHog(posthog) {
72
+ if (!isTestChimpCaptureActive() || instrumented.has(posthog)) return posthog;
73
+ const target = posthog;
74
+ const original = target.capture;
75
+ if (typeof original !== "function") return posthog;
76
+ instrumented.add(posthog);
77
+ target.capture = function(...args) {
78
+ try {
79
+ const [event, properties] = args;
80
+ if (event === "$feature_flag_called" && properties && typeof properties === "object") {
81
+ const p = properties;
82
+ if (typeof p.$feature_flag === "string") {
83
+ reportFlag(p.$feature_flag, p.$feature_flag_response, "posthog");
84
+ }
85
+ }
86
+ } catch {
87
+ }
88
+ return original.apply(this, args);
89
+ };
90
+ return posthog;
91
+ }
92
+ export {
93
+ createOpenFeatureHook,
94
+ instrumentLaunchDarkly,
95
+ instrumentPostHog,
96
+ isTestChimpCaptureActive,
97
+ launchDarklyInspector,
98
+ reportFlag
99
+ };
100
+ //# sourceMappingURL=index.mjs.map