@wellth-app/experiments 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/README.md +223 -2
- package/dist/cjs/index.js +10 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/react.js +317 -0
- package/dist/cjs/react.js.map +1 -0
- package/dist/cjs/registry-pg5aaOm-.js +537 -0
- package/dist/cjs/registry-pg5aaOm-.js.map +1 -0
- package/dist/cjs/web.js +87 -0
- package/dist/cjs/web.js.map +1 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/react.js +290 -0
- package/dist/esm/react.js.map +1 -0
- package/dist/esm/registry-B73fwn9J.js +534 -0
- package/dist/esm/registry-B73fwn9J.js.map +1 -0
- package/dist/esm/web.js +85 -0
- package/dist/esm/web.js.map +1 -0
- package/dist/events.d.ts +65 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/react/context.d.ts +37 -0
- package/dist/react/context.d.ts.map +1 -0
- package/dist/react/guard.d.ts +11 -0
- package/dist/react/guard.d.ts.map +1 -0
- package/dist/react/index.d.ts +12 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/provider.d.ts +38 -0
- package/dist/react/provider.d.ts.map +1 -0
- package/dist/react/use-analytics.d.ts +12 -0
- package/dist/react/use-analytics.d.ts.map +1 -0
- package/dist/react/use-experiment-qa.d.ts +14 -0
- package/dist/react/use-experiment-qa.d.ts.map +1 -0
- package/dist/react/use-experiment.d.ts +30 -0
- package/dist/react/use-experiment.d.ts.map +1 -0
- package/dist/react/use-feature-flag.d.ts +16 -0
- package/dist/react/use-feature-flag.d.ts.map +1 -0
- package/dist/react/use-feature-value.d.ts +16 -0
- package/dist/react/use-feature-value.d.ts.map +1 -0
- package/dist/registry.d.ts +143 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/types.d.ts +111 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/uuid.d.ts +6 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/web/batched-event-sender.d.ts +35 -0
- package/dist/web/batched-event-sender.d.ts.map +1 -0
- package/dist/web/index.d.ts +7 -0
- package/dist/web/index.d.ts.map +1 -0
- package/package.json +127 -4
- package/src/events.ts +90 -0
- package/src/index.ts +37 -0
- package/src/react/context.ts +62 -0
- package/src/react/guard.ts +25 -0
- package/src/react/index.ts +17 -0
- package/src/react/provider.tsx +109 -0
- package/src/react/use-analytics.ts +17 -0
- package/src/react/use-experiment-qa.ts +26 -0
- package/src/react/use-experiment.ts +72 -0
- package/src/react/use-feature-flag.ts +35 -0
- package/src/react/use-feature-value.ts +42 -0
- package/src/registry.ts +715 -0
- package/src/types.ts +120 -0
- package/src/uuid.ts +14 -0
- package/src/web/batched-event-sender.ts +111 -0
- package/src/web/index.ts +9 -0
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var growthbook = require('@growthbook/growthbook');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The analytics stream the SDK emits into. One stream carries every product
|
|
7
|
+
* event; `experiment_exposed` is one event type on it. The stream is the seam
|
|
8
|
+
* where the platform's analytics pipeline plugs in.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The warehouse contract for an experiment exposure. Field names are contractual —
|
|
13
|
+
* the warehouse recomputes assignment from `experiment_id` + `subject` and joins
|
|
14
|
+
* exposures on them. Exactly one emission per render-visible assignment.
|
|
15
|
+
*
|
|
16
|
+
* `config_version` + `subject` let the warehouse recompute the cohort *as
|
|
17
|
+
* configured at exposure time*; `exposure_id` is the idempotency key the
|
|
18
|
+
* ingestion and warehouse dedupe layers key on; `override` marks QA-forced
|
|
19
|
+
* assignments that analysis drops by default.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* The surfaces that emit exposure. Each app declares itself at registry
|
|
23
|
+
* construction — the app is "app", Atlas is "web", notifications dispatch is
|
|
24
|
+
* "notifications". Extend as new surfaces ship.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Any event on the product-analytics stream. ExperimentExposureEvent is one of these. */
|
|
28
|
+
|
|
29
|
+
/** Where events go. Batching and transport live behind this seam. */
|
|
30
|
+
|
|
31
|
+
function buildExperimentExposure({
|
|
32
|
+
experimentKey,
|
|
33
|
+
subjectId,
|
|
34
|
+
variant,
|
|
35
|
+
surface,
|
|
36
|
+
timestamp,
|
|
37
|
+
configVersion,
|
|
38
|
+
exposureId,
|
|
39
|
+
override
|
|
40
|
+
}) {
|
|
41
|
+
return {
|
|
42
|
+
event: "experiment_exposed",
|
|
43
|
+
experiment_id: experimentKey,
|
|
44
|
+
variation_id: variant,
|
|
45
|
+
subject: subjectId,
|
|
46
|
+
surface,
|
|
47
|
+
timestamp,
|
|
48
|
+
config_version: configVersion,
|
|
49
|
+
exposure_id: exposureId,
|
|
50
|
+
...(override === true ? {
|
|
51
|
+
override: true
|
|
52
|
+
} : {})
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A v4 UUID for idempotency keys — uniqueness, not security. Uses the platform
|
|
58
|
+
* crypto when it has one (web, modern Hermes), a Math.random fallback otherwise.
|
|
59
|
+
*/
|
|
60
|
+
function newId() {
|
|
61
|
+
const cryptoApi = globalThis.crypto;
|
|
62
|
+
if (cryptoApi?.randomUUID) {
|
|
63
|
+
return cryptoApi.randomUUID();
|
|
64
|
+
}
|
|
65
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
|
|
66
|
+
const r = Math.floor(Math.random() * 16);
|
|
67
|
+
return (c === "x" ? r : r & 0x3 | 0x8).toString(16);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The features-endpoint payload the registry consumes. This is the wire format of
|
|
73
|
+
* `<sdk-host>/api/features/<clientKey>` — the config the evaluation engine
|
|
74
|
+
* downloads once and then evaluates entirely locally.
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
/** An experiment's remote start/stop. Anything not running is stopped. */
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A config key's shape, for the hooks' misuse guard. "experiment" keys carry
|
|
81
|
+
* an experiment-shaped rule (live or not); "flag" keys carry flag-shaped
|
|
82
|
+
* rules. A bare-default key reports "unknown": a stopped experiment and a
|
|
83
|
+
* static default are indistinguishable, and both read fail-closed from either
|
|
84
|
+
* path, so no guard fires.
|
|
85
|
+
*/
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* How a flag resolved. The evaluation engine's source vocabulary, re-exported
|
|
89
|
+
* under our name: "force" (a targeting/rollout rule matched), "defaultValue"
|
|
90
|
+
* (no rule matched), "unknownFeature" (absent from the config), and the rarer
|
|
91
|
+
* engine outcomes.
|
|
92
|
+
*/
|
|
93
|
+
|
|
94
|
+
/** A feature flag's resolution for one subject. Flags never log exposure. */
|
|
95
|
+
|
|
96
|
+
/** The arm key returned when the experiment config doesn't name one. */
|
|
97
|
+
const CONTROL_VARIANT_KEY = "control";
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The default warning channel. Apps route config-guard warnings through the
|
|
101
|
+
* `warn` option (their own logger or telemetry); unset, they land here.
|
|
102
|
+
*/
|
|
103
|
+
const defaultWarn = message => {
|
|
104
|
+
// eslint-disable-next-line no-console -- the one sanctioned console call
|
|
105
|
+
console.warn(message);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Ids normalize inside the evaluator — trim + lowercase — so casing/whitespace
|
|
110
|
+
* drift at a call site can never scramble a cohort. The warehouse applies the
|
|
111
|
+
* same normalization before hashing.
|
|
112
|
+
*/
|
|
113
|
+
function normalizeSubject(subjectId) {
|
|
114
|
+
return subjectId.trim().toLowerCase();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The plain string form is a migration entry; entries may carry expiry + kind. */
|
|
118
|
+
function toOverrideEntry(value) {
|
|
119
|
+
if (value === undefined) return undefined;
|
|
120
|
+
return typeof value === "string" ? {
|
|
121
|
+
variant: value
|
|
122
|
+
} : value;
|
|
123
|
+
}
|
|
124
|
+
function isLive(entry) {
|
|
125
|
+
return entry.expiresAt === undefined || Date.parse(entry.expiresAt) > Date.now();
|
|
126
|
+
}
|
|
127
|
+
function createFeatureRegistry(options) {
|
|
128
|
+
const surface = options.surface;
|
|
129
|
+
const events = options.events;
|
|
130
|
+
// Override map keys are subject ids; normalize them once at construction so
|
|
131
|
+
// a cutover export's casing/whitespace can never miss the lookup (ids
|
|
132
|
+
// normalize inside the evaluator, never at call sites).
|
|
133
|
+
const overrides = {};
|
|
134
|
+
for (const [experimentKey, bySubject] of Object.entries(options.overrides ?? {})) {
|
|
135
|
+
const normalized = {};
|
|
136
|
+
for (const [subjectKey, value] of Object.entries(bySubject)) {
|
|
137
|
+
normalized[normalizeSubject(subjectKey)] = value;
|
|
138
|
+
}
|
|
139
|
+
overrides[experimentKey] = normalized;
|
|
140
|
+
}
|
|
141
|
+
const cacheStorage = options.cacheStorage;
|
|
142
|
+
const warn = options.warn ?? defaultWarn;
|
|
143
|
+
let client = null;
|
|
144
|
+
let activeClientKey;
|
|
145
|
+
let configVersion = null;
|
|
146
|
+
let entries = new Map();
|
|
147
|
+
let version = 0;
|
|
148
|
+
let enabled = false;
|
|
149
|
+
const pins = new Map();
|
|
150
|
+
const exposed = new Set();
|
|
151
|
+
const listeners = new Set();
|
|
152
|
+
const bump = () => {
|
|
153
|
+
version += 1;
|
|
154
|
+
for (const listener of listeners) listener();
|
|
155
|
+
};
|
|
156
|
+
const rebuildEntries = () => {
|
|
157
|
+
entries = client ? parseEntries(client.getFeatures(), warn) : new Map();
|
|
158
|
+
};
|
|
159
|
+
const captureConfigVersion = () => {
|
|
160
|
+
configVersion = client?.getPayload().dateUpdated ?? null;
|
|
161
|
+
};
|
|
162
|
+
const makeClient = clientOptions => {
|
|
163
|
+
// The cache's persistent tier sits behind the app's storage when given
|
|
164
|
+
// (AsyncStorage on RN) — cold starts then evaluate offline from the last fetch.
|
|
165
|
+
if (cacheStorage) {
|
|
166
|
+
growthbook.setPolyfills({
|
|
167
|
+
localStorage: cacheStorage
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return new growthbook.GrowthBookClient(clientOptions ?? {});
|
|
171
|
+
};
|
|
172
|
+
const evaluateExperiment = ({
|
|
173
|
+
experimentKey,
|
|
174
|
+
subjectId,
|
|
175
|
+
attributes
|
|
176
|
+
}) => {
|
|
177
|
+
const subject = normalizeSubject(subjectId);
|
|
178
|
+
const entry = entries.get(experimentKey);
|
|
179
|
+
|
|
180
|
+
// Unknown, disabled, or stopped: control with no exposure. A stopped
|
|
181
|
+
// experiment always lands here — overrides never resurrect it.
|
|
182
|
+
if (client === null || !entry || entry.status === "stopped") {
|
|
183
|
+
return {
|
|
184
|
+
variant: entry?.controlKey ?? CONTROL_VARIANT_KEY,
|
|
185
|
+
params: entry?.defaultParams ?? {},
|
|
186
|
+
exposure: null
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// QA pins force a variant for the pinned subject and are never exposure.
|
|
191
|
+
const pin = pins.get(experimentKey);
|
|
192
|
+
if (pin && pin.subjectId === subject) {
|
|
193
|
+
const variation = findVariation(entry, pin.variant);
|
|
194
|
+
if (variation) {
|
|
195
|
+
return {
|
|
196
|
+
variant: variation.key,
|
|
197
|
+
params: variation.params,
|
|
198
|
+
exposure: null
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Registry overrides keep a member on the assigned arm. Migration entries
|
|
204
|
+
// are real assignments and log exposure normally; QA entries log flagged
|
|
205
|
+
// as overrides so analysis drops them. Expired entries fall through to
|
|
206
|
+
// the hash as if they never existed.
|
|
207
|
+
const overrideEntry = toOverrideEntry(overrides[experimentKey]?.[subject]);
|
|
208
|
+
if (overrideEntry && isLive(overrideEntry)) {
|
|
209
|
+
const variation = findVariation(entry, overrideEntry.variant);
|
|
210
|
+
if (variation) {
|
|
211
|
+
return {
|
|
212
|
+
variant: variation.key,
|
|
213
|
+
params: variation.params,
|
|
214
|
+
exposure: {
|
|
215
|
+
experimentKey: entry.experimentKey,
|
|
216
|
+
subjectId: subject,
|
|
217
|
+
variant: variation.key,
|
|
218
|
+
configVersion,
|
|
219
|
+
override: overrideEntry.kind === "qa" ? true : undefined
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Delegate to the engine's local evaluation: targeting conditions gate
|
|
226
|
+
// eligibility (including date windows — the registry always supplies the
|
|
227
|
+
// current ISO date as `date`), then the deterministic hash buckets the
|
|
228
|
+
// subject id. `id` is always the subject — attributes never override it.
|
|
229
|
+
const result = client.evalFeature(experimentKey, {
|
|
230
|
+
attributes: {
|
|
231
|
+
date: new Date().toISOString(),
|
|
232
|
+
...attributes,
|
|
233
|
+
id: subject
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
const experimentResult = result.experimentResult;
|
|
237
|
+
if (result.source === "experiment" && experimentResult?.inExperiment === true) {
|
|
238
|
+
return {
|
|
239
|
+
variant: experimentResult.key,
|
|
240
|
+
params: isParams(result.value) ? result.value : entry.defaultParams,
|
|
241
|
+
exposure: {
|
|
242
|
+
experimentKey: entry.experimentKey,
|
|
243
|
+
subjectId: subject,
|
|
244
|
+
variant: experimentResult.key,
|
|
245
|
+
configVersion
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Ineligible (targeting failed, outside the window, or outside coverage):
|
|
251
|
+
// the default arm, no exposure.
|
|
252
|
+
return {
|
|
253
|
+
variant: entry.controlKey,
|
|
254
|
+
params: entry.defaultParams,
|
|
255
|
+
exposure: null
|
|
256
|
+
};
|
|
257
|
+
};
|
|
258
|
+
const evaluateFlag = ({
|
|
259
|
+
featureKey,
|
|
260
|
+
subjectId,
|
|
261
|
+
attributes
|
|
262
|
+
}) => {
|
|
263
|
+
const entry = entries.get(featureKey);
|
|
264
|
+
|
|
265
|
+
// Disabled or unknown: the null read.
|
|
266
|
+
if (client === null || !entry) {
|
|
267
|
+
return {
|
|
268
|
+
value: null,
|
|
269
|
+
on: false,
|
|
270
|
+
off: true,
|
|
271
|
+
source: "unknownFeature"
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// An experiment-shaped key read through the flag path gets the config's
|
|
276
|
+
// default, never the assigned value — that read would render a variant
|
|
277
|
+
// without an exposure event and corrupt the experiment's counts. Keyed on
|
|
278
|
+
// rule PRESENCE, not parse status: the engine would still evaluate a rule
|
|
279
|
+
// the parse guards failed closed, so a guarded key must never reach it.
|
|
280
|
+
if (entry.hasExperimentRule) {
|
|
281
|
+
return {
|
|
282
|
+
value: entry.defaultValue,
|
|
283
|
+
on: Boolean(entry.defaultValue),
|
|
284
|
+
off: !entry.defaultValue,
|
|
285
|
+
source: "defaultValue"
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Delegate to the engine's local evaluation: targeting conditions and
|
|
290
|
+
// percentage rollouts included.
|
|
291
|
+
const result = client.evalFeature(featureKey, {
|
|
292
|
+
attributes: {
|
|
293
|
+
date: new Date().toISOString(),
|
|
294
|
+
...attributes,
|
|
295
|
+
id: normalizeSubject(subjectId)
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
return {
|
|
299
|
+
value: result.value,
|
|
300
|
+
on: result.on,
|
|
301
|
+
off: result.off,
|
|
302
|
+
source: result.source
|
|
303
|
+
};
|
|
304
|
+
};
|
|
305
|
+
return {
|
|
306
|
+
async init({
|
|
307
|
+
clientKey,
|
|
308
|
+
apiHost
|
|
309
|
+
}) {
|
|
310
|
+
if (clientKey === undefined) return;
|
|
311
|
+
enabled = true;
|
|
312
|
+
activeClientKey = clientKey;
|
|
313
|
+
client = makeClient({
|
|
314
|
+
apiHost,
|
|
315
|
+
clientKey
|
|
316
|
+
});
|
|
317
|
+
await client.init();
|
|
318
|
+
rebuildEntries();
|
|
319
|
+
captureConfigVersion();
|
|
320
|
+
bump();
|
|
321
|
+
},
|
|
322
|
+
initSync({
|
|
323
|
+
payload
|
|
324
|
+
}) {
|
|
325
|
+
enabled = true;
|
|
326
|
+
client = makeClient({});
|
|
327
|
+
client.initSync({
|
|
328
|
+
payload
|
|
329
|
+
});
|
|
330
|
+
rebuildEntries();
|
|
331
|
+
captureConfigVersion();
|
|
332
|
+
bump();
|
|
333
|
+
},
|
|
334
|
+
async refresh() {
|
|
335
|
+
if (client === null || activeClientKey === undefined) return;
|
|
336
|
+
await client.refreshFeatures();
|
|
337
|
+
rebuildEntries();
|
|
338
|
+
captureConfigVersion();
|
|
339
|
+
bump();
|
|
340
|
+
},
|
|
341
|
+
evaluateExperiment,
|
|
342
|
+
evaluateFlag,
|
|
343
|
+
getKeyKind(key) {
|
|
344
|
+
const entry = entries.get(key);
|
|
345
|
+
if (!entry) return "unknown";
|
|
346
|
+
if (entry.hasExperimentRule) return "experiment";
|
|
347
|
+
return entry.hasFlagRule ? "flag" : "unknown";
|
|
348
|
+
},
|
|
349
|
+
trackExposure({
|
|
350
|
+
experimentKey,
|
|
351
|
+
subjectId,
|
|
352
|
+
variant,
|
|
353
|
+
configVersion: evaluatedConfigVersion,
|
|
354
|
+
override
|
|
355
|
+
}) {
|
|
356
|
+
const subject = normalizeSubject(subjectId);
|
|
357
|
+
const dedupeKey = JSON.stringify([experimentKey, subject, variant]);
|
|
358
|
+
if (exposed.has(dedupeKey)) return;
|
|
359
|
+
exposed.add(dedupeKey);
|
|
360
|
+
events?.send(buildExperimentExposure({
|
|
361
|
+
experimentKey,
|
|
362
|
+
subjectId: subject,
|
|
363
|
+
variant,
|
|
364
|
+
surface,
|
|
365
|
+
timestamp: Date.now(),
|
|
366
|
+
// The evaluation-time version — a config refresh between compute and
|
|
367
|
+
// render must not re-stamp the event.
|
|
368
|
+
configVersion: evaluatedConfigVersion,
|
|
369
|
+
exposureId: newId(),
|
|
370
|
+
override
|
|
371
|
+
}));
|
|
372
|
+
},
|
|
373
|
+
sendEvent(event) {
|
|
374
|
+
events?.send(event);
|
|
375
|
+
},
|
|
376
|
+
pin(pin) {
|
|
377
|
+
pins.set(pin.experimentKey, {
|
|
378
|
+
...pin,
|
|
379
|
+
subjectId: normalizeSubject(pin.subjectId)
|
|
380
|
+
});
|
|
381
|
+
bump();
|
|
382
|
+
},
|
|
383
|
+
unpin({
|
|
384
|
+
experimentKey
|
|
385
|
+
}) {
|
|
386
|
+
if (pins.delete(experimentKey)) bump();
|
|
387
|
+
},
|
|
388
|
+
getPins() {
|
|
389
|
+
return [...pins.values()];
|
|
390
|
+
},
|
|
391
|
+
subscribe(listener) {
|
|
392
|
+
listeners.add(listener);
|
|
393
|
+
return () => listeners.delete(listener);
|
|
394
|
+
},
|
|
395
|
+
getVersion() {
|
|
396
|
+
return version;
|
|
397
|
+
},
|
|
398
|
+
isReady() {
|
|
399
|
+
return client?.ready ?? false;
|
|
400
|
+
},
|
|
401
|
+
isEnabled() {
|
|
402
|
+
return enabled;
|
|
403
|
+
},
|
|
404
|
+
getConfigVersion() {
|
|
405
|
+
return configVersion;
|
|
406
|
+
},
|
|
407
|
+
destroy() {
|
|
408
|
+
client?.destroy();
|
|
409
|
+
client = null;
|
|
410
|
+
listeners.clear();
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function findVariation(entry, variantKey) {
|
|
415
|
+
return entry.variations.find(variation => variation.key === variantKey);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Experiment arms carry object payloads; anything else in the config reads as no payload. */
|
|
419
|
+
function isParams(value) {
|
|
420
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
421
|
+
}
|
|
422
|
+
function parseEntries(features, warn) {
|
|
423
|
+
const entries = new Map();
|
|
424
|
+
for (const [featureKey, definition] of Object.entries(features)) {
|
|
425
|
+
entries.set(featureKey, parseEntry(featureKey, definition, warn));
|
|
426
|
+
}
|
|
427
|
+
return entries;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** A rule carrying a runnable experiment: two or more arms to assign between. */
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* The wire's rule lifecycle fields. The engine's published rule type omits
|
|
434
|
+
* them (`status` is deprecated upstream but still emitted), so they are read
|
|
435
|
+
* defensively here — a remotely stopped experiment's rule can still ride the
|
|
436
|
+
* payload.
|
|
437
|
+
*/
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* A rule is live only while the config says so: two-plus arms, not deactivated
|
|
441
|
+
* (`active: false`), and not carrying a terminal lifecycle status. A remotely
|
|
442
|
+
* stopped rule that still rides the payload parses as stopped here — the entry
|
|
443
|
+
* never reaches the engine, so no override can resurrect it.
|
|
444
|
+
*/
|
|
445
|
+
function hasLiveExperiment(rule) {
|
|
446
|
+
return Array.isArray(rule.variations) && rule.variations.length >= 2 && rule.active !== false && rule.status !== "draft" && rule.status !== "stopped";
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* The bucketing contract the warehouse reproduces: the hash input is the bare
|
|
451
|
+
* subject id, hashed with hashVersion 2, with no sticky-bucket fallback. A rule
|
|
452
|
+
* that breaks it would bucket on inputs the warehouse can't reproduce — so the
|
|
453
|
+
* entry fails closed instead of ever producing a wrong assignment. Returns why
|
|
454
|
+
* the rule violates the contract, or null when it conforms.
|
|
455
|
+
*/
|
|
456
|
+
function hashContractViolation(rule) {
|
|
457
|
+
if (rule.hashAttribute !== undefined && rule.hashAttribute !== "id") {
|
|
458
|
+
return `buckets on hashAttribute "${rule.hashAttribute}" — the hash input must be the bare subject id`;
|
|
459
|
+
}
|
|
460
|
+
if (rule.fallbackAttribute !== undefined) {
|
|
461
|
+
return `buckets with fallbackAttribute "${rule.fallbackAttribute}" — sticky bucketing is out of contract`;
|
|
462
|
+
}
|
|
463
|
+
if (rule.hashVersion !== 2) {
|
|
464
|
+
return rule.hashVersion === undefined ? "omits hashVersion — the contract is the explicit hashVersion 2" : `buckets with hashVersion ${rule.hashVersion} — the contract is hashVersion 2`;
|
|
465
|
+
}
|
|
466
|
+
return null;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** The entry shape for anything not running: the control experience only. */
|
|
470
|
+
function stoppedEntry(featureKey, hasExperimentRule, hasFlagRule, defaultParams, defaultValue) {
|
|
471
|
+
return {
|
|
472
|
+
key: featureKey,
|
|
473
|
+
experimentKey: featureKey,
|
|
474
|
+
status: "stopped",
|
|
475
|
+
hasExperimentRule,
|
|
476
|
+
hasFlagRule,
|
|
477
|
+
controlKey: CONTROL_VARIANT_KEY,
|
|
478
|
+
variations: [],
|
|
479
|
+
defaultParams,
|
|
480
|
+
defaultValue
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
function parseEntry(featureKey, definition, warn) {
|
|
484
|
+
const defaultParams = isParams(definition.defaultValue) ? definition.defaultValue : {};
|
|
485
|
+
const defaultValue = definition.defaultValue ?? null;
|
|
486
|
+
const rules = definition.rules ?? [];
|
|
487
|
+
// Presence, not parse status: any experiment-shaped rule, live or not,
|
|
488
|
+
// trusted or not — the flag path keys on this so it never evaluates one.
|
|
489
|
+
const hasExperimentRule = rules.some(rule => Array.isArray(rule.variations) && rule.variations.length >= 2);
|
|
490
|
+
const hasFlagRule = rules.some(rule => !(Array.isArray(rule.variations) && rule.variations.length >= 2));
|
|
491
|
+
|
|
492
|
+
// A feature carries at most one experiment-shaped rule: the engine evaluates
|
|
493
|
+
// every rule in order, so a second one would bucket subjects on inputs the
|
|
494
|
+
// contract never validated (and a stopped rule riding alongside a live one
|
|
495
|
+
// would still assign through it). Fail closed on the shape.
|
|
496
|
+
if (rules.filter(rule => Array.isArray(rule.variations) && rule.variations.length >= 2).length > 1) {
|
|
497
|
+
warn(`[experiments] "${featureKey}" carries more than one experiment rule; the experiment reads as stopped (control, no exposure)`);
|
|
498
|
+
return stoppedEntry(featureKey, hasExperimentRule, hasFlagRule, defaultParams, defaultValue);
|
|
499
|
+
}
|
|
500
|
+
const experimentRule = rules.find(hasLiveExperiment);
|
|
501
|
+
|
|
502
|
+
// The config marks an experiment stopped by no longer carrying a live
|
|
503
|
+
// experiment rule: the feature keeps only its default payload, which is the
|
|
504
|
+
// control experience a stopped experiment serves. The same shape is a plain
|
|
505
|
+
// feature flag.
|
|
506
|
+
if (!experimentRule) {
|
|
507
|
+
return stoppedEntry(featureKey, hasExperimentRule, hasFlagRule, defaultParams, defaultValue);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// A live rule that breaks the bucketing contract can only assign wrong: fail
|
|
511
|
+
// closed, and name the key on the warning channel so the config gets fixed
|
|
512
|
+
// rather than silently serving control forever.
|
|
513
|
+
const violation = hashContractViolation(experimentRule);
|
|
514
|
+
if (violation !== null) {
|
|
515
|
+
warn(`[experiments] "${featureKey}" ${violation}; the experiment reads as stopped (control, no exposure)`);
|
|
516
|
+
return stoppedEntry(featureKey, hasExperimentRule, hasFlagRule, defaultParams, defaultValue);
|
|
517
|
+
}
|
|
518
|
+
const variations = experimentRule.variations.map((value, index) => ({
|
|
519
|
+
key: experimentRule.meta?.[index]?.key ?? String(index),
|
|
520
|
+
params: isParams(value) ? value : {}
|
|
521
|
+
}));
|
|
522
|
+
return {
|
|
523
|
+
key: featureKey,
|
|
524
|
+
experimentKey: experimentRule.key ?? featureKey,
|
|
525
|
+
status: "running",
|
|
526
|
+
hasExperimentRule,
|
|
527
|
+
hasFlagRule,
|
|
528
|
+
controlKey: variations[0]?.key ?? CONTROL_VARIANT_KEY,
|
|
529
|
+
variations,
|
|
530
|
+
defaultParams,
|
|
531
|
+
defaultValue
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
exports.buildExperimentExposure = buildExperimentExposure;
|
|
536
|
+
exports.createFeatureRegistry = createFeatureRegistry;
|
|
537
|
+
//# sourceMappingURL=registry-pg5aaOm-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-pg5aaOm-.js","sources":["../../src/events.ts","../../src/uuid.ts","../../src/registry.ts"],"sourcesContent":["/**\n * The analytics stream the SDK emits into. One stream carries every product\n * event; `experiment_exposed` is one event type on it. The stream is the seam\n * where the platform's analytics pipeline plugs in.\n */\n\n/**\n * The warehouse contract for an experiment exposure. Field names are contractual —\n * the warehouse recomputes assignment from `experiment_id` + `subject` and joins\n * exposures on them. Exactly one emission per render-visible assignment.\n *\n * `config_version` + `subject` let the warehouse recompute the cohort *as\n * configured at exposure time*; `exposure_id` is the idempotency key the\n * ingestion and warehouse dedupe layers key on; `override` marks QA-forced\n * assignments that analysis drops by default.\n */\n/**\n * The surfaces that emit exposure. Each app declares itself at registry\n * construction — the app is \"app\", Atlas is \"web\", notifications dispatch is\n * \"notifications\". Extend as new surfaces ship.\n */\nexport type ExposureSurface = \"app\" | \"web\" | \"notifications\";\n\nexport interface ExperimentExposureEvent {\n event: \"experiment_exposed\";\n /** The experiment's key. */\n experiment_id: string;\n /** The assigned arm's key. */\n variation_id: string;\n /** The member id the assignment hashed on (normalized: trimmed, lowercased). */\n subject: string;\n /** The emitting surface, declared by the app. */\n surface: ExposureSurface;\n /** Epoch milliseconds, at render time. */\n timestamp: number;\n /**\n * The registry config version the assignment was evaluated against — captured\n * at evaluation time and carried on the exposure, never re-read at send time.\n * Null when unknown.\n */\n config_version: string | null;\n /** Idempotency key: one per unique assignment per session. */\n exposure_id: string;\n /** Present and true only when a QA-kind override produced the assignment. */\n override?: true;\n}\n\n/** Any event on the product-analytics stream. ExperimentExposureEvent is one of these. */\nexport interface StreamEvent {\n event: string;\n /** Epoch milliseconds. */\n timestamp: number;\n}\n\n/** Where events go. Batching and transport live behind this seam. */\nexport interface EventStream {\n send: (event: StreamEvent) => void;\n}\n\nexport function buildExperimentExposure({\n experimentKey,\n subjectId,\n variant,\n surface,\n timestamp,\n configVersion,\n exposureId,\n override,\n}: {\n experimentKey: string;\n subjectId: string;\n variant: string;\n surface: ExposureSurface;\n timestamp: number;\n configVersion: string | null;\n exposureId: string;\n override?: boolean;\n}): ExperimentExposureEvent {\n return {\n event: \"experiment_exposed\",\n experiment_id: experimentKey,\n variation_id: variant,\n subject: subjectId,\n surface,\n timestamp,\n config_version: configVersion,\n exposure_id: exposureId,\n ...(override === true ? { override: true } : {}),\n };\n}\n","/**\n * A v4 UUID for idempotency keys — uniqueness, not security. Uses the platform\n * crypto when it has one (web, modern Hermes), a Math.random fallback otherwise.\n */\nexport function newId(): string {\n const cryptoApi = globalThis.crypto;\n if (cryptoApi?.randomUUID) {\n return cryptoApi.randomUUID();\n }\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n return (c === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n","import {\n GrowthBookClient,\n setPolyfills,\n type FeatureApiResponse,\n type FeatureDefinition,\n type FeatureDefinitions,\n type FeatureResultSource,\n type FeatureRule,\n} from \"@growthbook/growthbook\";\nimport {\n buildExperimentExposure,\n type EventStream,\n type ExposureSurface,\n type StreamEvent,\n} from \"./events\";\nimport type {\n ExperimentParams,\n ExposureInput,\n KeyValueStorage,\n OverrideEntry,\n Overrides,\n QaPin,\n ResolvedAssignment,\n TargetingAttributes,\n} from \"./types\";\nimport { newId } from \"./uuid\";\n\n/**\n * The features-endpoint payload the registry consumes. This is the wire format of\n * `<sdk-host>/api/features/<clientKey>` — the config the evaluation engine\n * downloads once and then evaluates entirely locally.\n */\nexport type RegistryPayload = FeatureApiResponse;\n\nexport interface RegistryInitOptions {\n /** The SDK key identifying the environment's config on the features endpoint. */\n clientKey?: string;\n /** The SDK host. When absent, the evaluation client's built-in default host applies. */\n apiHost?: string;\n}\n\nexport interface EvaluateExperimentInput {\n experimentKey: string;\n subjectId: string;\n attributes?: TargetingAttributes;\n}\n\nexport interface EvaluateFlagInput {\n featureKey: string;\n subjectId: string;\n attributes?: TargetingAttributes;\n}\n\n/** An experiment's remote start/stop. Anything not running is stopped. */\nexport type ExperimentStatus = \"running\" | \"stopped\";\n\n/**\n * A config key's shape, for the hooks' misuse guard. \"experiment\" keys carry\n * an experiment-shaped rule (live or not); \"flag\" keys carry flag-shaped\n * rules. A bare-default key reports \"unknown\": a stopped experiment and a\n * static default are indistinguishable, and both read fail-closed from either\n * path, so no guard fires.\n */\nexport type KeyKind = \"experiment\" | \"flag\" | \"unknown\";\n\n/**\n * How a flag resolved. The evaluation engine's source vocabulary, re-exported\n * under our name: \"force\" (a targeting/rollout rule matched), \"defaultValue\"\n * (no rule matched), \"unknownFeature\" (absent from the config), and the rarer\n * engine outcomes.\n */\nexport type FlagSource = FeatureResultSource;\n\n/** A feature flag's resolution for one subject. Flags never log exposure. */\nexport interface FlagEvaluation {\n /** The flag's resolved value — rule value, or the config's default. */\n value: unknown;\n /** Boolean convenience over the value. */\n on: boolean;\n off: boolean;\n source: FlagSource;\n}\n\ninterface ExperimentVariation {\n key: string;\n params: ExperimentParams;\n}\n\ninterface FeatureEntry {\n /** The feature key call sites pass — the experiment's key by platform convention. */\n key: string;\n /** The key written to exposure events (the config rule's tracking key when it differs). */\n experimentKey: string;\n status: ExperimentStatus;\n /**\n * True when the config carries ANY experiment-shaped rule (two or more arms)\n * for this key — regardless of lifecycle status or hash-contract trust. The\n * flag path keys on presence, not parse status: the engine would still\n * evaluate a failed-closed rule, so an experiment-shaped key must never\n * reach it.\n */\n hasExperimentRule: boolean;\n /**\n * True when the config carries any rule for this key that is NOT\n * experiment-shaped (a targeting/rollout/force rule) — an actively\n * configured flag. Drives the misuse guard's flag classification.\n */\n hasFlagRule: boolean;\n controlKey: string;\n variations: readonly ExperimentVariation[];\n /** The config's default payload, shaped for the experiment path. */\n defaultParams: ExperimentParams;\n /** The config's default value, raw — the flag path's default read. */\n defaultValue: unknown;\n}\n\nexport interface FeatureRegistry {\n /**\n * Fetch the experiment config from the features endpoint and start keeping it\n * fresh. The evaluation client caches locally and revalidates stale reads in\n * the background; init resolves with the cached config when one exists. Without\n * a client key the registry stays disabled: every experiment reads control,\n * every flag reads its fallback, and nothing is fetched. A failed fetch leaves\n * the registry serving defaults, never throwing into the app.\n */\n init: (options: RegistryInitOptions) => Promise<void>;\n /** Seed the registry synchronously from an already-available payload (tests, SSR). */\n initSync: (options: { payload: RegistryPayload }) => void;\n /**\n * Re-fetch the config now (e.g. on app foreground). No-op on a disabled or\n * payload-seeded registry — a seeded registry is fresh by construction and\n * has no endpoint to refresh from.\n */\n refresh: () => Promise<void>;\n /**\n * Resolve the assignment for one subject. The evaluation order: a stopped or\n * unknown experiment reads control with no exposure (overrides never\n * resurrect it); then, checked before delegating to the engine's local\n * evaluation — QA pin, then registry overrides (migration / QA, unexpired\n * only); then the engine (targeting conditions, then the deterministic hash\n * bucket). Subject ids are normalized (trim + lowercase) inside the\n * evaluator.\n */\n evaluateExperiment: (input: EvaluateExperimentInput) => ResolvedAssignment;\n /**\n * Resolve a feature flag for one subject: targeting conditions and percentage\n * rollouts evaluate locally against the same deterministic hash. Flags never\n * log exposure. An experiment-shaped key read here returns the config's\n * default by design — experiments go through evaluateExperiment, which is the\n * exposure-aware path.\n */\n evaluateFlag: (input: EvaluateFlagInput) => FlagEvaluation;\n /**\n * Record that an assignment became visible. Emits exactly one event per unique\n * (experiment, subject, variant) assignment per session — repeat calls for the\n * same assignment are deduplicated.\n */\n trackExposure: (input: ExposureInput) => void;\n /** Send an event on the configured stream. No-op when no stream is configured. */\n sendEvent: (event: StreamEvent) => void;\n /** Force a variant for one subject on this session. Pins never emit exposure. */\n pin: (pin: QaPin) => void;\n unpin: (input: { experimentKey: string }) => void;\n getPins: () => readonly QaPin[];\n /**\n * The key's config shape, for the hooks' misuse guard: \"experiment\" when it\n * carries an experiment-shaped rule (live or not), \"flag\" when it carries\n * flag-shaped rules only, \"unknown\" otherwise (no config, or a bare default\n * — indistinguishable from a stopped experiment, so no guard fires).\n */\n getKeyKind: (key: string) => KeyKind;\n /** React subscription: re-render when the config or pins change. */\n subscribe: (listener: () => void) => () => void;\n getVersion: () => number;\n /** True once a config payload is loaded and evaluations reflect it. */\n isReady: () => boolean;\n /** True when the registry was given a client key (evaluations are live config). */\n isEnabled: () => boolean;\n /** The loaded config's version (the payload's dateUpdated), null when unknown. */\n getConfigVersion: () => string | null;\n destroy: () => void;\n}\n\ninterface FeatureRegistryOptions {\n /**\n * The surface exposures are stamped with. Required — each app declares\n * itself; there is no default.\n */\n surface: ExposureSurface;\n events?: EventStream;\n overrides?: Overrides;\n /**\n * Where the config cache persists (AsyncStorage on React Native). Unset, the\n * engine uses the platform's localStorage when present and memory otherwise.\n */\n cacheStorage?: KeyValueStorage;\n /**\n * Where config-guard warnings go: an experiment rule that breaks the platform\n * contract fails closed and names its feature key here. Default: console.warn.\n */\n warn?: (message: string) => void;\n}\n\n/** The arm key returned when the experiment config doesn't name one. */\nconst CONTROL_VARIANT_KEY = \"control\";\n\n/**\n * The default warning channel. Apps route config-guard warnings through the\n * `warn` option (their own logger or telemetry); unset, they land here.\n */\nconst defaultWarn: (message: string) => void = (message) => {\n // eslint-disable-next-line no-console -- the one sanctioned console call\n console.warn(message);\n};\n\n/**\n * Ids normalize inside the evaluator — trim + lowercase — so casing/whitespace\n * drift at a call site can never scramble a cohort. The warehouse applies the\n * same normalization before hashing.\n */\nfunction normalizeSubject(subjectId: string): string {\n return subjectId.trim().toLowerCase();\n}\n\n/** The plain string form is a migration entry; entries may carry expiry + kind. */\nfunction toOverrideEntry(\n value: string | OverrideEntry | undefined,\n): OverrideEntry | undefined {\n if (value === undefined) return undefined;\n return typeof value === \"string\" ? { variant: value } : value;\n}\n\nfunction isLive(entry: OverrideEntry): boolean {\n return (\n entry.expiresAt === undefined || Date.parse(entry.expiresAt) > Date.now()\n );\n}\n\nexport function createFeatureRegistry(\n options: FeatureRegistryOptions,\n): FeatureRegistry {\n const surface = options.surface;\n const events = options.events;\n // Override map keys are subject ids; normalize them once at construction so\n // a cutover export's casing/whitespace can never miss the lookup (ids\n // normalize inside the evaluator, never at call sites).\n const overrides: Overrides = {};\n for (const [experimentKey, bySubject] of Object.entries(\n options.overrides ?? {},\n )) {\n const normalized: Overrides[string] = {};\n for (const [subjectKey, value] of Object.entries(bySubject)) {\n normalized[normalizeSubject(subjectKey)] = value;\n }\n overrides[experimentKey] = normalized;\n }\n const cacheStorage = options.cacheStorage;\n const warn = options.warn ?? defaultWarn;\n\n let client: GrowthBookClient | null = null;\n let activeClientKey: string | undefined;\n let configVersion: string | null = null;\n let entries: ReadonlyMap<string, FeatureEntry> = new Map();\n let version = 0;\n let enabled = false;\n const pins = new Map<string, QaPin>();\n const exposed = new Set<string>();\n const listeners = new Set<() => void>();\n\n const bump = (): void => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const rebuildEntries = (): void => {\n entries = client ? parseEntries(client.getFeatures(), warn) : new Map();\n };\n\n const captureConfigVersion = (): void => {\n configVersion = client?.getPayload().dateUpdated ?? null;\n };\n\n const makeClient = (clientOptions?: {\n apiHost?: string;\n clientKey?: string;\n }): GrowthBookClient => {\n // The cache's persistent tier sits behind the app's storage when given\n // (AsyncStorage on RN) — cold starts then evaluate offline from the last fetch.\n if (cacheStorage) {\n setPolyfills({ localStorage: cacheStorage });\n }\n return new GrowthBookClient(clientOptions ?? {});\n };\n\n const evaluateExperiment = ({\n experimentKey,\n subjectId,\n attributes,\n }: EvaluateExperimentInput): ResolvedAssignment => {\n const subject = normalizeSubject(subjectId);\n const entry = entries.get(experimentKey);\n\n // Unknown, disabled, or stopped: control with no exposure. A stopped\n // experiment always lands here — overrides never resurrect it.\n if (client === null || !entry || entry.status === \"stopped\") {\n return {\n variant: entry?.controlKey ?? CONTROL_VARIANT_KEY,\n params: entry?.defaultParams ?? {},\n exposure: null,\n };\n }\n\n // QA pins force a variant for the pinned subject and are never exposure.\n const pin = pins.get(experimentKey);\n if (pin && pin.subjectId === subject) {\n const variation = findVariation(entry, pin.variant);\n if (variation) {\n return {\n variant: variation.key,\n params: variation.params,\n exposure: null,\n };\n }\n }\n\n // Registry overrides keep a member on the assigned arm. Migration entries\n // are real assignments and log exposure normally; QA entries log flagged\n // as overrides so analysis drops them. Expired entries fall through to\n // the hash as if they never existed.\n const overrideEntry = toOverrideEntry(overrides[experimentKey]?.[subject]);\n if (overrideEntry && isLive(overrideEntry)) {\n const variation = findVariation(entry, overrideEntry.variant);\n if (variation) {\n return {\n variant: variation.key,\n params: variation.params,\n exposure: {\n experimentKey: entry.experimentKey,\n subjectId: subject,\n variant: variation.key,\n configVersion,\n override: overrideEntry.kind === \"qa\" ? true : undefined,\n },\n };\n }\n }\n\n // Delegate to the engine's local evaluation: targeting conditions gate\n // eligibility (including date windows — the registry always supplies the\n // current ISO date as `date`), then the deterministic hash buckets the\n // subject id. `id` is always the subject — attributes never override it.\n const result = client.evalFeature(experimentKey, {\n attributes: {\n date: new Date().toISOString(),\n ...attributes,\n id: subject,\n },\n });\n const experimentResult = result.experimentResult;\n if (\n result.source === \"experiment\" &&\n experimentResult?.inExperiment === true\n ) {\n return {\n variant: experimentResult.key,\n params: isParams(result.value) ? result.value : entry.defaultParams,\n exposure: {\n experimentKey: entry.experimentKey,\n subjectId: subject,\n variant: experimentResult.key,\n configVersion,\n },\n };\n }\n\n // Ineligible (targeting failed, outside the window, or outside coverage):\n // the default arm, no exposure.\n return {\n variant: entry.controlKey,\n params: entry.defaultParams,\n exposure: null,\n };\n };\n\n const evaluateFlag = ({\n featureKey,\n subjectId,\n attributes,\n }: EvaluateFlagInput): FlagEvaluation => {\n const entry = entries.get(featureKey);\n\n // Disabled or unknown: the null read.\n if (client === null || !entry) {\n return { value: null, on: false, off: true, source: \"unknownFeature\" };\n }\n\n // An experiment-shaped key read through the flag path gets the config's\n // default, never the assigned value — that read would render a variant\n // without an exposure event and corrupt the experiment's counts. Keyed on\n // rule PRESENCE, not parse status: the engine would still evaluate a rule\n // the parse guards failed closed, so a guarded key must never reach it.\n if (entry.hasExperimentRule) {\n return {\n value: entry.defaultValue,\n on: Boolean(entry.defaultValue),\n off: !entry.defaultValue,\n source: \"defaultValue\",\n };\n }\n\n // Delegate to the engine's local evaluation: targeting conditions and\n // percentage rollouts included.\n const result = client.evalFeature(featureKey, {\n attributes: {\n date: new Date().toISOString(),\n ...attributes,\n id: normalizeSubject(subjectId),\n },\n });\n return {\n value: result.value,\n on: result.on,\n off: result.off,\n source: result.source,\n };\n };\n\n return {\n async init({ clientKey, apiHost }: RegistryInitOptions): Promise<void> {\n if (clientKey === undefined) return;\n enabled = true;\n activeClientKey = clientKey;\n client = makeClient({ apiHost, clientKey });\n await client.init();\n rebuildEntries();\n captureConfigVersion();\n bump();\n },\n initSync({ payload }: { payload: RegistryPayload }): void {\n enabled = true;\n client = makeClient({});\n client.initSync({ payload });\n rebuildEntries();\n captureConfigVersion();\n bump();\n },\n async refresh(): Promise<void> {\n if (client === null || activeClientKey === undefined) return;\n await client.refreshFeatures();\n rebuildEntries();\n captureConfigVersion();\n bump();\n },\n evaluateExperiment,\n evaluateFlag,\n getKeyKind(key: string): KeyKind {\n const entry = entries.get(key);\n if (!entry) return \"unknown\";\n if (entry.hasExperimentRule) return \"experiment\";\n return entry.hasFlagRule ? \"flag\" : \"unknown\";\n },\n trackExposure({\n experimentKey,\n subjectId,\n variant,\n configVersion: evaluatedConfigVersion,\n override,\n }: ExposureInput): void {\n const subject = normalizeSubject(subjectId);\n const dedupeKey = JSON.stringify([experimentKey, subject, variant]);\n if (exposed.has(dedupeKey)) return;\n exposed.add(dedupeKey);\n events?.send(\n buildExperimentExposure({\n experimentKey,\n subjectId: subject,\n variant,\n surface,\n timestamp: Date.now(),\n // The evaluation-time version — a config refresh between compute and\n // render must not re-stamp the event.\n configVersion: evaluatedConfigVersion,\n exposureId: newId(),\n override,\n }),\n );\n },\n sendEvent(event: StreamEvent): void {\n events?.send(event);\n },\n pin(pin: QaPin): void {\n pins.set(pin.experimentKey, {\n ...pin,\n subjectId: normalizeSubject(pin.subjectId),\n });\n bump();\n },\n unpin({ experimentKey }: { experimentKey: string }): void {\n if (pins.delete(experimentKey)) bump();\n },\n getPins(): readonly QaPin[] {\n return [...pins.values()];\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n getVersion(): number {\n return version;\n },\n isReady(): boolean {\n return client?.ready ?? false;\n },\n isEnabled(): boolean {\n return enabled;\n },\n getConfigVersion(): string | null {\n return configVersion;\n },\n destroy(): void {\n client?.destroy();\n client = null;\n listeners.clear();\n },\n };\n}\n\nfunction findVariation(\n entry: FeatureEntry,\n variantKey: string,\n): ExperimentVariation | undefined {\n return entry.variations.find((variation) => variation.key === variantKey);\n}\n\n/** Experiment arms carry object payloads; anything else in the config reads as no payload. */\nfunction isParams(value: unknown): value is ExperimentParams {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseEntries(\n features: FeatureDefinitions,\n warn: (message: string) => void,\n): ReadonlyMap<string, FeatureEntry> {\n const entries = new Map<string, FeatureEntry>();\n for (const [featureKey, definition] of Object.entries(features)) {\n entries.set(featureKey, parseEntry(featureKey, definition, warn));\n }\n return entries;\n}\n\n/** A rule carrying a runnable experiment: two or more arms to assign between. */\ntype ExperimentRule = FeatureRule & { variations: unknown[] };\n\n/**\n * The wire's rule lifecycle fields. The engine's published rule type omits\n * them (`status` is deprecated upstream but still emitted), so they are read\n * defensively here — a remotely stopped experiment's rule can still ride the\n * payload.\n */\ntype WireExperimentRule = FeatureRule & {\n active?: boolean;\n status?: string;\n};\n\n/**\n * A rule is live only while the config says so: two-plus arms, not deactivated\n * (`active: false`), and not carrying a terminal lifecycle status. A remotely\n * stopped rule that still rides the payload parses as stopped here — the entry\n * never reaches the engine, so no override can resurrect it.\n */\nfunction hasLiveExperiment(rule: WireExperimentRule): rule is ExperimentRule {\n return (\n Array.isArray(rule.variations) &&\n rule.variations.length >= 2 &&\n rule.active !== false &&\n rule.status !== \"draft\" &&\n rule.status !== \"stopped\"\n );\n}\n\n/**\n * The bucketing contract the warehouse reproduces: the hash input is the bare\n * subject id, hashed with hashVersion 2, with no sticky-bucket fallback. A rule\n * that breaks it would bucket on inputs the warehouse can't reproduce — so the\n * entry fails closed instead of ever producing a wrong assignment. Returns why\n * the rule violates the contract, or null when it conforms.\n */\nfunction hashContractViolation(rule: ExperimentRule): string | null {\n if (rule.hashAttribute !== undefined && rule.hashAttribute !== \"id\") {\n return `buckets on hashAttribute \"${rule.hashAttribute}\" — the hash input must be the bare subject id`;\n }\n if (rule.fallbackAttribute !== undefined) {\n return `buckets with fallbackAttribute \"${rule.fallbackAttribute}\" — sticky bucketing is out of contract`;\n }\n if (rule.hashVersion !== 2) {\n return rule.hashVersion === undefined\n ? \"omits hashVersion — the contract is the explicit hashVersion 2\"\n : `buckets with hashVersion ${rule.hashVersion} — the contract is hashVersion 2`;\n }\n return null;\n}\n\n/** The entry shape for anything not running: the control experience only. */\nfunction stoppedEntry(\n featureKey: string,\n hasExperimentRule: boolean,\n hasFlagRule: boolean,\n defaultParams: ExperimentParams,\n defaultValue: unknown,\n): FeatureEntry {\n return {\n key: featureKey,\n experimentKey: featureKey,\n status: \"stopped\",\n hasExperimentRule,\n hasFlagRule,\n controlKey: CONTROL_VARIANT_KEY,\n variations: [],\n defaultParams,\n defaultValue,\n };\n}\n\nfunction parseEntry(\n featureKey: string,\n definition: FeatureDefinition,\n warn: (message: string) => void,\n): FeatureEntry {\n const defaultParams = isParams(definition.defaultValue)\n ? definition.defaultValue\n : {};\n const defaultValue: unknown = definition.defaultValue ?? null;\n const rules = definition.rules ?? [];\n // Presence, not parse status: any experiment-shaped rule, live or not,\n // trusted or not — the flag path keys on this so it never evaluates one.\n const hasExperimentRule = rules.some(\n (rule) => Array.isArray(rule.variations) && rule.variations.length >= 2,\n );\n const hasFlagRule = rules.some(\n (rule) => !(Array.isArray(rule.variations) && rule.variations.length >= 2),\n );\n\n // A feature carries at most one experiment-shaped rule: the engine evaluates\n // every rule in order, so a second one would bucket subjects on inputs the\n // contract never validated (and a stopped rule riding alongside a live one\n // would still assign through it). Fail closed on the shape.\n if (\n rules.filter(\n (rule) => Array.isArray(rule.variations) && rule.variations.length >= 2,\n ).length > 1\n ) {\n warn(\n `[experiments] \"${featureKey}\" carries more than one experiment rule; the experiment reads as stopped (control, no exposure)`,\n );\n return stoppedEntry(\n featureKey,\n hasExperimentRule,\n hasFlagRule,\n defaultParams,\n defaultValue,\n );\n }\n\n const experimentRule = rules.find(hasLiveExperiment);\n\n // The config marks an experiment stopped by no longer carrying a live\n // experiment rule: the feature keeps only its default payload, which is the\n // control experience a stopped experiment serves. The same shape is a plain\n // feature flag.\n if (!experimentRule) {\n return stoppedEntry(\n featureKey,\n hasExperimentRule,\n hasFlagRule,\n defaultParams,\n defaultValue,\n );\n }\n\n // A live rule that breaks the bucketing contract can only assign wrong: fail\n // closed, and name the key on the warning channel so the config gets fixed\n // rather than silently serving control forever.\n const violation = hashContractViolation(experimentRule);\n if (violation !== null) {\n warn(\n `[experiments] \"${featureKey}\" ${violation}; the experiment reads as stopped (control, no exposure)`,\n );\n return stoppedEntry(\n featureKey,\n hasExperimentRule,\n hasFlagRule,\n defaultParams,\n defaultValue,\n );\n }\n\n const variations: ExperimentVariation[] = experimentRule.variations.map(\n (value: unknown, index: number) => ({\n key: experimentRule.meta?.[index]?.key ?? String(index),\n params: isParams(value) ? value : {},\n }),\n );\n\n return {\n key: featureKey,\n experimentKey: experimentRule.key ?? featureKey,\n status: \"running\",\n hasExperimentRule,\n hasFlagRule,\n controlKey: variations[0]?.key ?? CONTROL_VARIANT_KEY,\n variations,\n defaultParams,\n defaultValue,\n };\n}\n"],"names":["buildExperimentExposure","experimentKey","subjectId","variant","surface","timestamp","configVersion","exposureId","override","event","experiment_id","variation_id","subject","config_version","exposure_id","newId","cryptoApi","globalThis","crypto","randomUUID","replace","c","r","Math","floor","random","toString","CONTROL_VARIANT_KEY","defaultWarn","message","console","warn","normalizeSubject","trim","toLowerCase","toOverrideEntry","value","undefined","isLive","entry","expiresAt","Date","parse","now","createFeatureRegistry","options","events","overrides","bySubject","Object","entries","normalized","subjectKey","cacheStorage","client","activeClientKey","Map","version","enabled","pins","exposed","Set","listeners","bump","listener","rebuildEntries","parseEntries","getFeatures","captureConfigVersion","getPayload","dateUpdated","makeClient","clientOptions","setPolyfills","localStorage","GrowthBookClient","evaluateExperiment","attributes","get","status","controlKey","params","defaultParams","exposure","pin","variation","findVariation","key","overrideEntry","kind","result","evalFeature","date","toISOString","id","experimentResult","source","inExperiment","isParams","evaluateFlag","featureKey","on","off","hasExperimentRule","defaultValue","Boolean","init","clientKey","apiHost","initSync","payload","refresh","refreshFeatures","getKeyKind","hasFlagRule","trackExposure","evaluatedConfigVersion","dedupeKey","JSON","stringify","has","add","send","sendEvent","set","unpin","delete","getPins","values","subscribe","getVersion","isReady","ready","isEnabled","getConfigVersion","destroy","clear","variantKey","variations","find","Array","isArray","features","definition","parseEntry","hasLiveExperiment","rule","length","active","hashContractViolation","hashAttribute","fallbackAttribute","hashVersion","stoppedEntry","rules","some","filter","experimentRule","violation","map","index","meta","String"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA2BA;;AAOA;;AAKO,SAASA,uBAAuBA,CAAC;EACtCC,aAAa;EACbC,SAAS;EACTC,OAAO;EACPC,OAAO;EACPC,SAAS;EACTC,aAAa;EACbC,UAAU;AACVC,EAAAA;AAUF,CAAC,EAA2B;EAC1B,OAAO;AACLC,IAAAA,KAAK,EAAE,oBAAoB;AAC3BC,IAAAA,aAAa,EAAET,aAAa;AAC5BU,IAAAA,YAAY,EAAER,OAAO;AACrBS,IAAAA,OAAO,EAAEV,SAAS;IAClBE,OAAO;IACPC,SAAS;AACTQ,IAAAA,cAAc,EAAEP,aAAa;AA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