@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.
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/dist/openfeature-BIO-k-VW.d.mts +10 -0
- package/dist/openfeature-BIO-k-VW.d.ts +10 -0
- package/dist/server/index.d.mts +49 -0
- package/dist/server/index.d.ts +49 -0
- package/dist/server/index.js +306 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/index.mjs +272 -0
- package/dist/server/index.mjs.map +1 -0
- package/dist/web/index.d.mts +46 -0
- package/dist/web/index.d.ts +46 -0
- package/dist/web/index.js +132 -0
- package/dist/web/index.js.map +1 -0
- package/dist/web/index.mjs +100 -0
- package/dist/web/index.mjs.map +1 -0
- package/package.json +66 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TestChimp
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,152 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @testchimp/flags
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Feature flag hooks for apps under test. They tell [TestChimp](https://testchimp.io) which flag arms your tests actually ran, so the coverage view can show untested arms.
|
|
4
|
+
|
|
5
|
+
- **Web (`@testchimp/flags/web`)**: reports flags the browser evaluates, through OpenFeature, the LaunchDarkly JS SDK or PostHog JS.
|
|
6
|
+
- **Server (`@testchimp/flags/server`)**: echoes the flags a backend evaluated for a request back to the test, in a response header. It works with Express, Connect, Fastify, Next.js route handlers, and any `(req, res)` handler, and includes hooks for OpenFeature, LaunchDarkly Node and PostHog Node.
|
|
7
|
+
|
|
8
|
+
No runtime dependencies. OpenFeature, LaunchDarkly and PostHog are not imported, so the hooks work with any version that has the callbacks described below.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @testchimp/flags
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Safety: nothing happens outside a test
|
|
15
|
+
|
|
16
|
+
This is the most important property, and it is tested.
|
|
17
|
+
|
|
18
|
+
- **Web:** every function checks for `globalThis.__TESTCHIMP_FLAGS__`. The TestChimp Playwright fixture defines that global, and only in tests. In production there is no global, so the hooks install no wrappers, make no network calls, and throw nothing.
|
|
19
|
+
- **Server:** nothing happens unless `TESTCHIMP_FLAG_ECHO=1` (or `true`) is set. Set it only in test environments. When it is unset, no header is added and no per-request state is kept.
|
|
20
|
+
|
|
21
|
+
## Web
|
|
22
|
+
|
|
23
|
+
Report evaluations through the SDK you already use:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createOpenFeatureHook, instrumentLaunchDarkly, instrumentPostHog, reportFlag } from '@testchimp/flags/web';
|
|
27
|
+
|
|
28
|
+
// OpenFeature web SDK
|
|
29
|
+
OpenFeature.addHooks(createOpenFeatureHook());
|
|
30
|
+
|
|
31
|
+
// LaunchDarkly JS SDK: inspectors can only be set at initialize time
|
|
32
|
+
const client = LDClient.initialize(clientSideId, context, instrumentLaunchDarkly({ bootstrap }));
|
|
33
|
+
|
|
34
|
+
// PostHog JS: call once after init
|
|
35
|
+
posthog.init(projectKey, options);
|
|
36
|
+
instrumentPostHog(posthog);
|
|
37
|
+
|
|
38
|
+
// Anything else: report the arm yourself
|
|
39
|
+
reportFlag('checkout-layout', 'compact', 'my-provider');
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Each provider's evaluations reach the fixture with the right provider id: `openfeature`, `launchdarkly` or `posthog`.
|
|
43
|
+
|
|
44
|
+
| Provider | Hook | How it captures |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| OpenFeature (web) | `createOpenFeatureHook()` | The hook's `after` stage. Reports the variant, or the value when there is no variant. |
|
|
47
|
+
| LaunchDarkly JS | `instrumentLaunchDarkly(options)` | A `flag-used` inspector, which the SDK calls on each variation call. `allFlags()` is not counted. |
|
|
48
|
+
| PostHog JS | `instrumentPostHog(posthog)` | Wraps `posthog.capture` and reads the `$feature_flag_called` event that `getFeatureFlag` emits. Lookups made with `send_event: false` emit no event, so they are not captured. |
|
|
49
|
+
|
|
50
|
+
`instrumentLaunchDarkly` returns a new options object, so pass its result into `initialize`. It returns the options unchanged outside a test.
|
|
51
|
+
|
|
52
|
+
## Server
|
|
53
|
+
|
|
54
|
+
Set `TESTCHIMP_FLAG_ECHO=1` in the test environment that runs the backend. Then add the middleware (or wrapper) that matches your framework.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// Express or Connect
|
|
58
|
+
import { flagCollectionMiddleware } from '@testchimp/flags/server';
|
|
59
|
+
app.use(flagCollectionMiddleware());
|
|
60
|
+
|
|
61
|
+
// Fastify
|
|
62
|
+
import { fastifyFlagCollection } from '@testchimp/flags/server';
|
|
63
|
+
await app.register(fastifyFlagCollection);
|
|
64
|
+
|
|
65
|
+
// Next.js App Router route handler, or any (req, res) handler
|
|
66
|
+
import { withFlagCollection } from '@testchimp/flags/server';
|
|
67
|
+
export const GET = withFlagCollection(async (request: Request) => Response.json(await loadOrders()));
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Then wire the provider hook once, at startup:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { createOpenFeatureServerHook, instrumentLaunchDarklyNode, instrumentPostHogNode } from '@testchimp/flags/server';
|
|
74
|
+
|
|
75
|
+
OpenFeature.addHooks(createOpenFeatureServerHook()); // OpenFeature server SDK
|
|
76
|
+
instrumentLaunchDarklyNode(ldClient); // @launchdarkly/node-server-sdk v9.3+, after init
|
|
77
|
+
instrumentPostHogNode(posthogClient); // posthog-node: getFeatureFlag, isFeatureEnabled, evaluateFlags
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`reportFlag(flagKey, variant, providerId)` is also exported, for providers without a hook.
|
|
81
|
+
|
|
82
|
+
Each request gets its own collector, through `AsyncLocalStorage`. Concurrent requests never see each other's flags.
|
|
83
|
+
|
|
84
|
+
### Backend-only flags need the echo
|
|
85
|
+
|
|
86
|
+
A flag evaluated only in the backend shows as untested unless `TESTCHIMP_FLAG_ECHO=1` is set on the backend. Flags evaluated in the browser need no backend setup, because the fixture captures them directly.
|
|
87
|
+
|
|
88
|
+
Only the service that answers the browser's request echoes its flags. Deeper services, queue consumers, cron jobs and background workers are out of scope for v1.
|
|
89
|
+
|
|
90
|
+
## Header contract
|
|
91
|
+
|
|
92
|
+
The header is the interface between your backend and TestChimp. Any language can implement it.
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
x-testchimp-flags: v1.<base64url(JSON array of {k, v, p})>
|
|
96
|
+
x-testchimp-flags-truncated: 1 (only when entries were dropped)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
- `k` is the flag key, `v` is the arm as a string, `p` is the provider id (`openfeature`, `launchdarkly`, `posthog`, `statsig`, or `unknown`).
|
|
100
|
+
- Entries are deduplicated by `(k, v)`.
|
|
101
|
+
- base64url has no padding.
|
|
102
|
+
- The encoded value must stay within 4096 bytes. Keep the first entries that fit, and set `x-testchimp-flags-truncated: 1` if any were dropped.
|
|
103
|
+
- Set the header only when at least one entry was recorded. Set it only when the echo is enabled.
|
|
104
|
+
|
|
105
|
+
A Python implementation, about 25 lines:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
import base64, json
|
|
109
|
+
|
|
110
|
+
MAX_BYTES = 4096
|
|
111
|
+
|
|
112
|
+
def encode(entries):
|
|
113
|
+
return "v1." + base64.urlsafe_b64encode(json.dumps(entries, separators=(",", ":")).encode()).rstrip(b"=").decode()
|
|
114
|
+
|
|
115
|
+
def flag_headers(arms):
|
|
116
|
+
"""arms: (flag_key, variant, provider_id) tuples observed while handling one request."""
|
|
117
|
+
seen, kept, truncated = set(), [], False
|
|
118
|
+
for k, v, p in arms:
|
|
119
|
+
if (k, v) in seen:
|
|
120
|
+
continue
|
|
121
|
+
seen.add((k, v))
|
|
122
|
+
if len(encode(kept + [{"k": k, "v": v, "p": p}]).encode()) > MAX_BYTES:
|
|
123
|
+
truncated = True
|
|
124
|
+
break
|
|
125
|
+
kept.append({"k": k, "v": v, "p": p})
|
|
126
|
+
if not kept:
|
|
127
|
+
return {}
|
|
128
|
+
headers = {"x-testchimp-flags": encode(kept)}
|
|
129
|
+
if truncated:
|
|
130
|
+
headers["x-testchimp-flags-truncated"] = "1"
|
|
131
|
+
return headers
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Call `flag_headers` from your framework's response hook, and only when the echo is enabled. The Playwright fixture reads the header from every response, so no CORS change is needed in the app under test.
|
|
135
|
+
|
|
136
|
+
## Verified against
|
|
137
|
+
|
|
138
|
+
- `@launchdarkly/node-server-sdk` 9.17.1: the `afterEvaluation` hook fires from a real `variation` call.
|
|
139
|
+
- `@openfeature/server-sdk` 1.23.0: the `after` hook fires from a real `getBooleanValue` and `getStringValue` call.
|
|
140
|
+
- The header decodes with the `@testchimp/playwright` fixture decoder.
|
|
141
|
+
- The web entry is checked to contain no Node-only module, and makes no network calls (unit tests).
|
|
142
|
+
- The LaunchDarkly JS inspector, PostHog `$feature_flag_called` and `posthog-node` method shapes are taken from the providers' current documentation. They are covered by unit tests, but not yet by a live browser run.
|
|
143
|
+
|
|
144
|
+
## Not in v1
|
|
145
|
+
|
|
146
|
+
- Statsig adapters. Statsig gates reach TestChimp through the fixture's bootstrap capture only.
|
|
147
|
+
- Java, Python and Go server hooks. Use the header contract above.
|
|
148
|
+
- Flags evaluated outside the service that answers the browser's request.
|
|
149
|
+
|
|
150
|
+
## License
|
|
151
|
+
|
|
152
|
+
MIT
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { H as HookContextLike, E as EvaluationDetailsLike } from '../openfeature-BIO-k-VW.mjs';
|
|
2
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
|
+
|
|
4
|
+
/** True when `TESTCHIMP_FLAG_ECHO` is 1 or true. */
|
|
5
|
+
declare function isEchoActive(): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Low-level: record one evaluation in the current request's collector. Does nothing outside a request or when
|
|
8
|
+
* echo is off. `variant` is normalized (booleans become "true"/"false", objects JSON).
|
|
9
|
+
*/
|
|
10
|
+
declare function reportFlag(flagKey: string, variant: unknown, providerId?: string): void;
|
|
11
|
+
/**
|
|
12
|
+
* Express and Connect middleware:
|
|
13
|
+
* app.use(flagCollectionMiddleware());
|
|
14
|
+
* Register it before the routes whose flags you want echoed.
|
|
15
|
+
*/
|
|
16
|
+
declare function flagCollectionMiddleware(): (_req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;
|
|
17
|
+
interface FastifyInstanceLike {
|
|
18
|
+
addHook: (name: string, hook: (...args: any[]) => void) => unknown;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Fastify plugin: `await app.register(fastifyFlagCollection)`. It is not encapsulated (like fastify-plugin), so
|
|
22
|
+
* its hooks apply to every route.
|
|
23
|
+
*/
|
|
24
|
+
declare function fastifyFlagCollection(fastify: FastifyInstanceLike, _opts: unknown, done: (err?: Error) => void): void;
|
|
25
|
+
/**
|
|
26
|
+
* Generic wrapper for any handler. It covers Next.js App Router route handlers (they return a `Response`) and
|
|
27
|
+
* Pages-style or raw Node handlers that take `(req, res)` and write to `res`.
|
|
28
|
+
*
|
|
29
|
+
* export const GET = withFlagCollection(async (request: Request) => Response.json(...));
|
|
30
|
+
*/
|
|
31
|
+
declare function withFlagCollection<A extends unknown[], R>(handler: (...args: A) => R | Promise<R>): (...args: A) => Promise<R>;
|
|
32
|
+
/**
|
|
33
|
+
* OpenFeature server SDK hook: `OpenFeature.setProvider(...)` then `OpenFeature.addHooks(createOpenFeatureServerHook())`.
|
|
34
|
+
*/
|
|
35
|
+
declare function createOpenFeatureServerHook(): {
|
|
36
|
+
after(hookContext: HookContextLike | undefined, details: EvaluationDetailsLike | undefined): void;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* LaunchDarkly Node SDK (v9.3+). Adds a hook that records every variation result. Call it once, after
|
|
40
|
+
* `init(...)`. Older SDKs without `addHook` are left alone.
|
|
41
|
+
*/
|
|
42
|
+
declare function instrumentLaunchDarklyNode<T extends object>(client: T): T;
|
|
43
|
+
/**
|
|
44
|
+
* PostHog Node SDK. Wraps `getFeatureFlag`, `isFeatureEnabled` and `evaluateFlags` (including the `getFlag` and
|
|
45
|
+
* `isEnabled` methods of the snapshot it returns). Call it once after creating the client.
|
|
46
|
+
*/
|
|
47
|
+
declare function instrumentPostHogNode<T extends object>(client: T): T;
|
|
48
|
+
|
|
49
|
+
export { createOpenFeatureServerHook, fastifyFlagCollection, flagCollectionMiddleware, instrumentLaunchDarklyNode, instrumentPostHogNode, isEchoActive, reportFlag, withFlagCollection };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { H as HookContextLike, E as EvaluationDetailsLike } from '../openfeature-BIO-k-VW.js';
|
|
2
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
|
+
|
|
4
|
+
/** True when `TESTCHIMP_FLAG_ECHO` is 1 or true. */
|
|
5
|
+
declare function isEchoActive(): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Low-level: record one evaluation in the current request's collector. Does nothing outside a request or when
|
|
8
|
+
* echo is off. `variant` is normalized (booleans become "true"/"false", objects JSON).
|
|
9
|
+
*/
|
|
10
|
+
declare function reportFlag(flagKey: string, variant: unknown, providerId?: string): void;
|
|
11
|
+
/**
|
|
12
|
+
* Express and Connect middleware:
|
|
13
|
+
* app.use(flagCollectionMiddleware());
|
|
14
|
+
* Register it before the routes whose flags you want echoed.
|
|
15
|
+
*/
|
|
16
|
+
declare function flagCollectionMiddleware(): (_req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;
|
|
17
|
+
interface FastifyInstanceLike {
|
|
18
|
+
addHook: (name: string, hook: (...args: any[]) => void) => unknown;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Fastify plugin: `await app.register(fastifyFlagCollection)`. It is not encapsulated (like fastify-plugin), so
|
|
22
|
+
* its hooks apply to every route.
|
|
23
|
+
*/
|
|
24
|
+
declare function fastifyFlagCollection(fastify: FastifyInstanceLike, _opts: unknown, done: (err?: Error) => void): void;
|
|
25
|
+
/**
|
|
26
|
+
* Generic wrapper for any handler. It covers Next.js App Router route handlers (they return a `Response`) and
|
|
27
|
+
* Pages-style or raw Node handlers that take `(req, res)` and write to `res`.
|
|
28
|
+
*
|
|
29
|
+
* export const GET = withFlagCollection(async (request: Request) => Response.json(...));
|
|
30
|
+
*/
|
|
31
|
+
declare function withFlagCollection<A extends unknown[], R>(handler: (...args: A) => R | Promise<R>): (...args: A) => Promise<R>;
|
|
32
|
+
/**
|
|
33
|
+
* OpenFeature server SDK hook: `OpenFeature.setProvider(...)` then `OpenFeature.addHooks(createOpenFeatureServerHook())`.
|
|
34
|
+
*/
|
|
35
|
+
declare function createOpenFeatureServerHook(): {
|
|
36
|
+
after(hookContext: HookContextLike | undefined, details: EvaluationDetailsLike | undefined): void;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* LaunchDarkly Node SDK (v9.3+). Adds a hook that records every variation result. Call it once, after
|
|
40
|
+
* `init(...)`. Older SDKs without `addHook` are left alone.
|
|
41
|
+
*/
|
|
42
|
+
declare function instrumentLaunchDarklyNode<T extends object>(client: T): T;
|
|
43
|
+
/**
|
|
44
|
+
* PostHog Node SDK. Wraps `getFeatureFlag`, `isFeatureEnabled` and `evaluateFlags` (including the `getFlag` and
|
|
45
|
+
* `isEnabled` methods of the snapshot it returns). Call it once after creating the client.
|
|
46
|
+
*/
|
|
47
|
+
declare function instrumentPostHogNode<T extends object>(client: T): T;
|
|
48
|
+
|
|
49
|
+
export { createOpenFeatureServerHook, fastifyFlagCollection, flagCollectionMiddleware, instrumentLaunchDarklyNode, instrumentPostHogNode, isEchoActive, reportFlag, withFlagCollection };
|
|
@@ -0,0 +1,306 @@
|
|
|
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/server/index.ts
|
|
21
|
+
var server_exports = {};
|
|
22
|
+
__export(server_exports, {
|
|
23
|
+
createOpenFeatureServerHook: () => createOpenFeatureServerHook,
|
|
24
|
+
fastifyFlagCollection: () => fastifyFlagCollection,
|
|
25
|
+
flagCollectionMiddleware: () => flagCollectionMiddleware,
|
|
26
|
+
instrumentLaunchDarklyNode: () => instrumentLaunchDarklyNode,
|
|
27
|
+
instrumentPostHogNode: () => instrumentPostHogNode,
|
|
28
|
+
isEchoActive: () => isEchoActive,
|
|
29
|
+
reportFlag: () => reportFlag,
|
|
30
|
+
withFlagCollection: () => withFlagCollection
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(server_exports);
|
|
33
|
+
|
|
34
|
+
// src/shared/header.ts
|
|
35
|
+
var FLAG_HEADER = "x-testchimp-flags";
|
|
36
|
+
var FLAG_TRUNCATED_HEADER = "x-testchimp-flags-truncated";
|
|
37
|
+
var MAX_HEADER_BYTES = 4096;
|
|
38
|
+
var UNKNOWN_PROVIDER = "unknown";
|
|
39
|
+
var MAX_COLLECTED_ENTRIES = 1e3;
|
|
40
|
+
var FlagCollector = class {
|
|
41
|
+
constructor() {
|
|
42
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
43
|
+
}
|
|
44
|
+
add(flagKey, variant, providerId = UNKNOWN_PROVIDER) {
|
|
45
|
+
if (!flagKey) return;
|
|
46
|
+
const key = `${flagKey}\0${variant}`;
|
|
47
|
+
if (this.entries.has(key) || this.entries.size >= MAX_COLLECTED_ENTRIES) return;
|
|
48
|
+
this.entries.set(key, { k: flagKey, v: variant, p: providerId || UNKNOWN_PROVIDER });
|
|
49
|
+
}
|
|
50
|
+
get size() {
|
|
51
|
+
return this.entries.size;
|
|
52
|
+
}
|
|
53
|
+
list() {
|
|
54
|
+
return [...this.entries.values()];
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
function utf8ByteLength(text) {
|
|
58
|
+
return new TextEncoder().encode(text).length;
|
|
59
|
+
}
|
|
60
|
+
function base64UrlEncode(text) {
|
|
61
|
+
const bytes = new TextEncoder().encode(text);
|
|
62
|
+
let binary = "";
|
|
63
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
64
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
65
|
+
}
|
|
66
|
+
function encodeFlagHeader(entries) {
|
|
67
|
+
const kept = [];
|
|
68
|
+
let truncated = false;
|
|
69
|
+
for (const entry of entries) {
|
|
70
|
+
const candidate = `v1.${base64UrlEncode(JSON.stringify([...kept, entry]))}`;
|
|
71
|
+
if (utf8ByteLength(candidate) > MAX_HEADER_BYTES) {
|
|
72
|
+
truncated = true;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
kept.push(entry);
|
|
76
|
+
}
|
|
77
|
+
if (kept.length === 0) return { value: "", truncated };
|
|
78
|
+
return { value: `v1.${base64UrlEncode(JSON.stringify(kept))}`, truncated };
|
|
79
|
+
}
|
|
80
|
+
function flagResponseHeaders(collector) {
|
|
81
|
+
if (collector.size === 0) return void 0;
|
|
82
|
+
const { value, truncated } = encodeFlagHeader(collector.list());
|
|
83
|
+
if (value === "") return void 0;
|
|
84
|
+
const headers = { [FLAG_HEADER]: value };
|
|
85
|
+
if (truncated) headers[FLAG_TRUNCATED_HEADER] = "1";
|
|
86
|
+
return headers;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// src/shared/variant.ts
|
|
90
|
+
var MAX_VARIANT_LENGTH = 128;
|
|
91
|
+
function normalizeVariant(value) {
|
|
92
|
+
if (value === void 0) return void 0;
|
|
93
|
+
let text;
|
|
94
|
+
if (value === null) {
|
|
95
|
+
text = "null";
|
|
96
|
+
} else if (typeof value === "string") {
|
|
97
|
+
text = value;
|
|
98
|
+
} else if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
99
|
+
text = String(value);
|
|
100
|
+
} else {
|
|
101
|
+
try {
|
|
102
|
+
text = JSON.stringify(value);
|
|
103
|
+
} catch {
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (text === void 0) return void 0;
|
|
108
|
+
return text.length > MAX_VARIANT_LENGTH ? text.slice(0, MAX_VARIANT_LENGTH) : text;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/shared/openfeature.ts
|
|
112
|
+
function openFeatureHook(report) {
|
|
113
|
+
return {
|
|
114
|
+
after(hookContext, details) {
|
|
115
|
+
const flagKey = details?.flagKey || hookContext?.flagKey;
|
|
116
|
+
if (!flagKey) return;
|
|
117
|
+
const variant = details?.variant !== void 0 && details.variant !== "" ? details.variant : details?.value;
|
|
118
|
+
report(flagKey, variant, "openfeature");
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/server/als.ts
|
|
124
|
+
var import_node_async_hooks = require("async_hooks");
|
|
125
|
+
var STORE_KEY = /* @__PURE__ */ Symbol.for("@testchimp/flags:collector-store");
|
|
126
|
+
function collectorStorage() {
|
|
127
|
+
const g = globalThis;
|
|
128
|
+
let store = g[STORE_KEY];
|
|
129
|
+
if (!store) {
|
|
130
|
+
store = new import_node_async_hooks.AsyncLocalStorage();
|
|
131
|
+
g[STORE_KEY] = store;
|
|
132
|
+
}
|
|
133
|
+
return store;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/server/index.ts
|
|
137
|
+
function isEchoActive() {
|
|
138
|
+
const raw = (typeof process !== "undefined" ? process.env.TESTCHIMP_FLAG_ECHO : void 0) ?? "";
|
|
139
|
+
const value = raw.trim().toLowerCase();
|
|
140
|
+
return value === "1" || value === "true";
|
|
141
|
+
}
|
|
142
|
+
function reportFlag(flagKey, variant, providerId = UNKNOWN_PROVIDER) {
|
|
143
|
+
try {
|
|
144
|
+
if (!flagKey || !isEchoActive()) return;
|
|
145
|
+
const collector = collectorStorage().getStore();
|
|
146
|
+
if (!collector) return;
|
|
147
|
+
const v = normalizeVariant(variant);
|
|
148
|
+
if (v === void 0) return;
|
|
149
|
+
collector.add(flagKey, v, providerId);
|
|
150
|
+
} catch {
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
var wrappedResponses = /* @__PURE__ */ new WeakSet();
|
|
154
|
+
function applyFlagHeaders(res, collector) {
|
|
155
|
+
if (res.headersSent) return;
|
|
156
|
+
const headers = flagResponseHeaders(collector);
|
|
157
|
+
if (!headers) return;
|
|
158
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
159
|
+
res.setHeader(name, value);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function attachHeaderWriter(res, collector) {
|
|
163
|
+
if (wrappedResponses.has(res)) return;
|
|
164
|
+
wrappedResponses.add(res);
|
|
165
|
+
const originalWriteHead = res.writeHead;
|
|
166
|
+
res.writeHead = function(...args) {
|
|
167
|
+
applyFlagHeaders(this, collector);
|
|
168
|
+
return originalWriteHead.apply(this, args);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function flagCollectionMiddleware() {
|
|
172
|
+
return function testchimpFlagCollection(_req, res, next) {
|
|
173
|
+
if (!isEchoActive()) {
|
|
174
|
+
next();
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const collector = new FlagCollector();
|
|
178
|
+
attachHeaderWriter(res, collector);
|
|
179
|
+
collectorStorage().run(collector, () => next());
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
var fastifyCollectors = /* @__PURE__ */ new WeakMap();
|
|
183
|
+
function fastifyFlagCollection(fastify, _opts, done) {
|
|
184
|
+
fastify.addHook("onRequest", (request, _reply, hookDone) => {
|
|
185
|
+
if (!isEchoActive()) {
|
|
186
|
+
hookDone();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const collector = new FlagCollector();
|
|
190
|
+
fastifyCollectors.set(request.raw, collector);
|
|
191
|
+
collectorStorage().run(collector, () => hookDone());
|
|
192
|
+
});
|
|
193
|
+
fastify.addHook(
|
|
194
|
+
"onSend",
|
|
195
|
+
(request, reply, payload, hookDone) => {
|
|
196
|
+
const collector = fastifyCollectors.get(request.raw);
|
|
197
|
+
const headers = collector ? flagResponseHeaders(collector) : void 0;
|
|
198
|
+
if (headers) {
|
|
199
|
+
for (const [name, value] of Object.entries(headers)) reply.header(name, value);
|
|
200
|
+
}
|
|
201
|
+
hookDone(null, payload);
|
|
202
|
+
}
|
|
203
|
+
);
|
|
204
|
+
done();
|
|
205
|
+
}
|
|
206
|
+
fastifyFlagCollection[/* @__PURE__ */ Symbol.for("skip-override")] = true;
|
|
207
|
+
function findServerResponse(args) {
|
|
208
|
+
const candidate = args[1];
|
|
209
|
+
if (candidate && typeof candidate.setHeader === "function" && typeof candidate.writeHead === "function") {
|
|
210
|
+
return candidate;
|
|
211
|
+
}
|
|
212
|
+
return void 0;
|
|
213
|
+
}
|
|
214
|
+
function withResponseHeaders(response, collector) {
|
|
215
|
+
const headers = flagResponseHeaders(collector);
|
|
216
|
+
if (!headers) return response;
|
|
217
|
+
const next = new Response(response.body, {
|
|
218
|
+
status: response.status,
|
|
219
|
+
statusText: response.statusText,
|
|
220
|
+
headers: response.headers
|
|
221
|
+
});
|
|
222
|
+
for (const [name, value] of Object.entries(headers)) next.headers.set(name, value);
|
|
223
|
+
return next;
|
|
224
|
+
}
|
|
225
|
+
function withFlagCollection(handler) {
|
|
226
|
+
return async (...args) => {
|
|
227
|
+
if (!isEchoActive()) return handler(...args);
|
|
228
|
+
const collector = new FlagCollector();
|
|
229
|
+
const res = findServerResponse(args);
|
|
230
|
+
if (res) attachHeaderWriter(res, collector);
|
|
231
|
+
const result = await collectorStorage().run(collector, () => handler(...args));
|
|
232
|
+
if (typeof Response !== "undefined" && result instanceof Response) {
|
|
233
|
+
return withResponseHeaders(result, collector);
|
|
234
|
+
}
|
|
235
|
+
return result;
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function createOpenFeatureServerHook() {
|
|
239
|
+
return openFeatureHook(reportFlag);
|
|
240
|
+
}
|
|
241
|
+
var instrumentedClients = /* @__PURE__ */ new WeakSet();
|
|
242
|
+
function launchDarklyNodeHook() {
|
|
243
|
+
return {
|
|
244
|
+
getMetadata: () => ({ name: "testchimp-flags" }),
|
|
245
|
+
afterEvaluation(hookContext, data, detail) {
|
|
246
|
+
if (hookContext?.flagKey) reportFlag(hookContext.flagKey, detail?.value, "launchdarkly");
|
|
247
|
+
return data;
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function instrumentLaunchDarklyNode(client) {
|
|
252
|
+
if (!isEchoActive() || instrumentedClients.has(client)) return client;
|
|
253
|
+
const addHook = client.addHook;
|
|
254
|
+
if (typeof addHook !== "function") return client;
|
|
255
|
+
instrumentedClients.add(client);
|
|
256
|
+
addHook.call(client, launchDarklyNodeHook());
|
|
257
|
+
return client;
|
|
258
|
+
}
|
|
259
|
+
function wrapMethod(target, name, after) {
|
|
260
|
+
const holder = target;
|
|
261
|
+
const original = holder[name];
|
|
262
|
+
if (typeof original !== "function") return;
|
|
263
|
+
const fn = original;
|
|
264
|
+
try {
|
|
265
|
+
holder[name] = function(...args) {
|
|
266
|
+
const result = fn.apply(this, args);
|
|
267
|
+
if (result && typeof result.then === "function") {
|
|
268
|
+
return result.then((value) => {
|
|
269
|
+
after(args, value);
|
|
270
|
+
return value;
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
after(args, result);
|
|
274
|
+
return result;
|
|
275
|
+
};
|
|
276
|
+
} catch {
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function instrumentPostHogNode(client) {
|
|
280
|
+
if (!isEchoActive() || instrumentedClients.has(client)) return client;
|
|
281
|
+
instrumentedClients.add(client);
|
|
282
|
+
const recordFirstArg = (args, value) => {
|
|
283
|
+
if (typeof args[0] === "string") reportFlag(args[0], value, "posthog");
|
|
284
|
+
};
|
|
285
|
+
wrapMethod(client, "getFeatureFlag", recordFirstArg);
|
|
286
|
+
wrapMethod(client, "isFeatureEnabled", recordFirstArg);
|
|
287
|
+
wrapMethod(client, "evaluateFlags", (_args, snapshot) => {
|
|
288
|
+
if (snapshot && typeof snapshot === "object") {
|
|
289
|
+
wrapMethod(snapshot, "getFlag", recordFirstArg);
|
|
290
|
+
wrapMethod(snapshot, "isEnabled", recordFirstArg);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
return client;
|
|
294
|
+
}
|
|
295
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
296
|
+
0 && (module.exports = {
|
|
297
|
+
createOpenFeatureServerHook,
|
|
298
|
+
fastifyFlagCollection,
|
|
299
|
+
flagCollectionMiddleware,
|
|
300
|
+
instrumentLaunchDarklyNode,
|
|
301
|
+
instrumentPostHogNode,
|
|
302
|
+
isEchoActive,
|
|
303
|
+
reportFlag,
|
|
304
|
+
withFlagCollection
|
|
305
|
+
});
|
|
306
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts","../../src/shared/header.ts","../../src/shared/variant.ts","../../src/shared/openfeature.ts","../../src/server/als.ts"],"sourcesContent":["/**\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","/**\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,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;AAC3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