@productcraft/flags 0.0.0 → 0.2.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +395 -1
  3. package/api.md +1532 -0
  4. package/dist/browser/chunk-DIPMYL6H.cjs +598 -0
  5. package/dist/browser/chunk-DIPMYL6H.cjs.map +1 -0
  6. package/dist/browser/chunk-OI4KARX6.js +593 -0
  7. package/dist/browser/chunk-OI4KARX6.js.map +1 -0
  8. package/dist/browser/chunk-UFZYZXX5.js +1584 -0
  9. package/dist/browser/chunk-UFZYZXX5.js.map +1 -0
  10. package/dist/browser/chunk-YAW7UFU3.cjs +1584 -0
  11. package/dist/browser/chunk-YAW7UFU3.cjs.map +1 -0
  12. package/dist/browser/index.cjs +105 -0
  13. package/dist/browser/index.cjs.map +1 -0
  14. package/dist/browser/index.js +9 -0
  15. package/dist/browser/index.js.map +1 -0
  16. package/dist/browser/management.cjs +12 -0
  17. package/dist/browser/management.cjs.map +1 -0
  18. package/dist/browser/management.js +3 -0
  19. package/dist/browser/management.js.map +1 -0
  20. package/dist/browser/testing.cjs +1315 -0
  21. package/dist/browser/testing.cjs.map +1 -0
  22. package/dist/browser/testing.js +1307 -0
  23. package/dist/browser/testing.js.map +1 -0
  24. package/dist/chunk-ERCRURB5.js +1584 -0
  25. package/dist/chunk-ERCRURB5.js.map +1 -0
  26. package/dist/chunk-ERZAYN5A.js +626 -0
  27. package/dist/chunk-ERZAYN5A.js.map +1 -0
  28. package/dist/chunk-HOIKWDWQ.cjs +1584 -0
  29. package/dist/chunk-HOIKWDWQ.cjs.map +1 -0
  30. package/dist/chunk-J62ZCSIV.cjs +631 -0
  31. package/dist/chunk-J62ZCSIV.cjs.map +1 -0
  32. package/dist/client-DQaz2Leb.d.cts +175 -0
  33. package/dist/client-DQaz2Leb.d.ts +175 -0
  34. package/dist/client-bVEJfS6_.d.cts +11007 -0
  35. package/dist/client-bVEJfS6_.d.ts +11007 -0
  36. package/dist/index.cjs +105 -0
  37. package/dist/index.cjs.map +1 -0
  38. package/dist/index.d.cts +5 -0
  39. package/dist/index.d.ts +5 -0
  40. package/dist/index.js +9 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/management.cjs +12 -0
  43. package/dist/management.cjs.map +1 -0
  44. package/dist/management.d.cts +3 -0
  45. package/dist/management.d.ts +3 -0
  46. package/dist/management.js +3 -0
  47. package/dist/management.js.map +1 -0
  48. package/dist/testing.cjs +1315 -0
  49. package/dist/testing.cjs.map +1 -0
  50. package/dist/testing.d.cts +71 -0
  51. package/dist/testing.d.ts +71 -0
  52. package/dist/testing.js +1307 -0
  53. package/dist/testing.js.map +1 -0
  54. package/manifest.json +875 -0
  55. package/package.json +121 -5
@@ -0,0 +1,593 @@
1
+ import { ProductCraftError, ConfigurationError, backoffMs, parseRetryAfterMs, isBrowser } from '@productcraft/core';
2
+ import { parseConfig, ConfigParseError, isNewerConfig, hashConfidential, evaluate } from '@productcraft/flags-engine';
3
+
4
+ // src/client/client.ts
5
+
6
+ // src/client/key.ts
7
+ var BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
8
+ function crc32(text) {
9
+ let crc = 4294967295;
10
+ for (let i = 0; i < text.length; i++) {
11
+ crc ^= text.charCodeAt(i);
12
+ for (let k = 0; k < 8; k++) crc = crc & 1 ? 3988292384 ^ crc >>> 1 : crc >>> 1;
13
+ }
14
+ return (crc ^ 4294967295) >>> 0;
15
+ }
16
+ function base62(value, width) {
17
+ let out = "";
18
+ do {
19
+ out = BASE62[value % 62] + out;
20
+ value = Math.floor(value / 62);
21
+ } while (value > 0);
22
+ return out.padStart(width, "0");
23
+ }
24
+ function isWellFormedSdkKey(key) {
25
+ if (typeof key !== "string" || !/^pcf_sdk_[0-9A-Za-z]{38}$/.test(key)) return false;
26
+ return base62(crc32(key.slice(8, 40)), 6) === key.slice(40);
27
+ }
28
+
29
+ // src/client/overrides.ts
30
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
31
+ var put = (o, k, v) => Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
32
+ function toSetting(value, remote) {
33
+ if (typeof value === "boolean") return { type: "boolean", value };
34
+ if (typeof value === "string") return remote === "json" ? { type: "json", value } : { type: "string", value };
35
+ if (typeof value === "number") {
36
+ if (!Number.isFinite(value)) return null;
37
+ return { type: remote !== "number" && Number.isSafeInteger(value) ? "integer" : "number", value };
38
+ }
39
+ if (value === null || typeof value === "object") {
40
+ try {
41
+ return { type: "json", value: JSON.stringify(value) };
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+ function overrideSettings(values, remoteType) {
49
+ const settings = {};
50
+ const skipped = [];
51
+ for (const key of Object.keys(values)) {
52
+ const s = toSetting(values[key], remoteType(key));
53
+ if (s) put(settings, key, s);
54
+ else skipped.push(key);
55
+ }
56
+ return { settings, skipped };
57
+ }
58
+ function combine(remote, overrides, behaviour) {
59
+ if (!overrides) return remote;
60
+ const local = { schema: 1, revision: 0, generation: 1, salt: "", segments: {}, settings: overrides };
61
+ if (behaviour === "local_only" || !remote) return local;
62
+ const settings = {};
63
+ const remoteSettings = isObj(remote.settings) ? remote.settings : {};
64
+ const [first, second] = behaviour === "local_over_remote" ? [remoteSettings, overrides] : [overrides, remoteSettings];
65
+ for (const k of Object.keys(first)) put(settings, k, first[k]);
66
+ for (const k of Object.keys(second)) put(settings, k, second[k]);
67
+ return { ...remote, settings };
68
+ }
69
+ var NODE_ONLY = "overrides.file and overrides.env are Node-only; use overrides.values in a browser";
70
+ function deliveryHeaders(etag) {
71
+ return etag && !isBrowser() ? { Accept: "application/json", "If-None-Match": etag } : { Accept: "application/json" };
72
+ }
73
+ function envOverrides(_name) {
74
+ throw new Error(NODE_ONLY);
75
+ }
76
+ async function fileOverrides(_path, _watch, _apply, report) {
77
+ report(NODE_ONLY);
78
+ return void 0;
79
+ }
80
+ function watchVisibility(onChange) {
81
+ const d = globalThis.document;
82
+ if (!d?.addEventListener) return void 0;
83
+ const listener = () => onChange(d.visibilityState === "hidden");
84
+ listener();
85
+ d.addEventListener("visibilitychange", listener);
86
+ return () => d.removeEventListener("visibilitychange", listener);
87
+ }
88
+ var fail = (base, def, code, message) => ({
89
+ ...base,
90
+ value: def,
91
+ variant: null,
92
+ reason: "ERROR",
93
+ errorCode: code,
94
+ errorMessage: message,
95
+ ruleIndex: null,
96
+ percentageIndex: null,
97
+ isDefaultValue: true
98
+ });
99
+ function resolve(config, key, def, user, json, layer) {
100
+ const empty = {
101
+ key,
102
+ value: def,
103
+ variant: null,
104
+ reason: "ERROR",
105
+ errorCode: null,
106
+ errorMessage: null,
107
+ ruleIndex: null,
108
+ percentageIndex: null,
109
+ isDefaultValue: true,
110
+ revision: config?.revision ?? 0,
111
+ warnings: []
112
+ };
113
+ if (!config) return fail(empty, def, "PROVIDER_NOT_READY", "no config yet");
114
+ try {
115
+ const parse = json || def === null || def === void 0 || typeof def === "object";
116
+ const d = evaluate(config, key, parse ? null : def, user ?? null);
117
+ if (d.reason === "ERROR") return { ...d, value: def, isDefaultValue: true };
118
+ const type = config.settingType(key);
119
+ let value = d.value;
120
+ if (parse) {
121
+ const parsable = type === "json" || json && type === "string";
122
+ if (!parsable && (json || def !== null && def !== void 0)) {
123
+ return fail(d, def, "TYPE_MISMATCH", `${key} is ${type}`);
124
+ }
125
+ if (parsable) {
126
+ try {
127
+ value = JSON.parse(d.value);
128
+ } catch (e) {
129
+ return fail(d, def, "PARSE_ERROR", e.message);
130
+ }
131
+ }
132
+ }
133
+ return { ...d, value, reason: layer ?? d.reason };
134
+ } catch (e) {
135
+ return fail(empty, def, "GENERAL", e?.message ?? String(e));
136
+ }
137
+ }
138
+ function resolveAll(config, user, layer) {
139
+ return config ? config.keys().map((k) => resolve(config, k, null, user, false, layer)) : [];
140
+ }
141
+ function toValues(details) {
142
+ const out = /* @__PURE__ */ Object.create(null);
143
+ for (const d of details) out[d.key] = d.value;
144
+ return out;
145
+ }
146
+
147
+ // src/client/client.ts
148
+ var DEFAULT_BASE = "https://api.flags.productcraft.co";
149
+ var MAX_CONFIG_BYTES = 2 * 1024 * 1024;
150
+ var FlagsClientError = class extends ProductCraftError {
151
+ static brandName = "FlagsClientError";
152
+ code;
153
+ constructor(code, message, options) {
154
+ super(message, options);
155
+ this.code = code;
156
+ }
157
+ };
158
+ function deliveryOrigins(urls, warn) {
159
+ const out = [];
160
+ for (const raw of urls) {
161
+ if (/^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*\.productcraft\.co\/?$/.test(raw)) out.push(raw.replace(/\/$/, ""));
162
+ else warn(`base_urls entry dropped: ${JSON.stringify(String(raw).slice(0, 99))}`);
163
+ }
164
+ return out;
165
+ }
166
+ var FlagsSnapshot = class {
167
+ #c;
168
+ #raw;
169
+ #user;
170
+ #layer;
171
+ /** @internal */
172
+ constructor(config, raw, user, layer) {
173
+ this.#c = config;
174
+ this.#raw = raw;
175
+ this.#user = user;
176
+ this.#layer = layer;
177
+ }
178
+ /** Revision of the config, 0 when there is none. */
179
+ get revision() {
180
+ return this.#c?.revision ?? 0;
181
+ }
182
+ /** Generation of the config (bumped after a database restore), 0 when there is none. */
183
+ get generation() {
184
+ return this.#c?.generation ?? 0;
185
+ }
186
+ /** Setting keys in config order. */
187
+ keys() {
188
+ return this.#c?.keys() ?? [];
189
+ }
190
+ getValue(key, defaultValue, user) {
191
+ return this.getValueDetails(key, defaultValue, user).value;
192
+ }
193
+ getValueDetails(key, defaultValue, user) {
194
+ return resolve(this.#c, key, defaultValue, user ?? this.#user, false, this.#layer);
195
+ }
196
+ getJson(key, defaultValue, user) {
197
+ return resolve(this.#c, key, defaultValue, user ?? this.#user, true, this.#layer).value;
198
+ }
199
+ getAllValues(user) {
200
+ return toValues(resolveAll(this.#c, user ?? this.#user, this.#layer));
201
+ }
202
+ /** The config JSON this snapshot evaluates (overrides included), or null: pass it as another client's `bootstrap`. */
203
+ toJSON() {
204
+ return this.#raw;
205
+ }
206
+ };
207
+ var setOverride;
208
+ var unref = (t) => (t.unref?.(), t);
209
+ var cancel = (res) => void res.body?.cancel().catch(() => void 0);
210
+ var FlagsClient = class {
211
+ #key;
212
+ #mode;
213
+ #interval;
214
+ #initWait;
215
+ #timeout;
216
+ #fetch;
217
+ #fixedBase;
218
+ #log;
219
+ #o;
220
+ #behaviour;
221
+ #on = { ready: /* @__PURE__ */ new Set(), configChanged: /* @__PURE__ */ new Set(), evaluated: /* @__PURE__ */ new Set(), error: /* @__PURE__ */ new Set() };
222
+ #warned = /* @__PURE__ */ new Set();
223
+ #state = "initializing";
224
+ #source = "none";
225
+ /** The downloaded (or cached / bootstrap) config, parsed and as JSON for combining with overrides. */
226
+ #remote = null;
227
+ #remoteRaw = null;
228
+ #etag = null;
229
+ #fetchedAt = 0;
230
+ /** Override values as given, and as config settings. */
231
+ #overrideValues = {};
232
+ #overrides = null;
233
+ /** What evaluations use: the remote config combined with the overrides. */
234
+ #config = null;
235
+ #configRaw = null;
236
+ #bases;
237
+ #user;
238
+ #failures = 0;
239
+ #retryAfter = 0;
240
+ #timer;
241
+ #inflight = null;
242
+ #abort = null;
243
+ #offline;
244
+ #closed = false;
245
+ /** Browser build: the page is hidden, so auto polling waits for it to come back (6.3, task 019). */
246
+ #hidden = false;
247
+ #unwatch;
248
+ #unwatchVisibility;
249
+ #init;
250
+ constructor(options = {}) {
251
+ const o = this.#o = options;
252
+ const ov = o.overrides;
253
+ const p = o.polling ?? { mode: "auto" };
254
+ this.#behaviour = ov?.behaviour ?? "local_over_remote";
255
+ if (!/^(auto|lazy|manual)$/.test(p.mode) || !/^(local_only|local_over_remote|remote_over_local)$/.test(this.#behaviour)) {
256
+ throw new ConfigurationError("bad polling.mode or overrides.behaviour");
257
+ }
258
+ const localOnly = !!ov && this.#behaviour === "local_only";
259
+ if (o.sdkKey === void 0 ? !localOnly && !(o.offline && o.bootstrap !== void 0) : !isWellFormedSdkKey(o.sdkKey)) {
260
+ throw new ConfigurationError("sdkKey is not a valid pcf_sdk_ key (check for a typo)");
261
+ }
262
+ this.#key = localOnly ? null : o.sdkKey ?? null;
263
+ this.#log = o.logger === null ? null : o.logger ?? console;
264
+ this.#fetch = o.fetch ?? ((...a) => fetch(...a));
265
+ this.#fixedBase = o.baseUrl?.replace(/\/+$/, "") || null;
266
+ this.#bases = [this.#fixedBase ?? DEFAULT_BASE];
267
+ this.#timeout = o.timeout ?? 1e4;
268
+ this.#user = o.defaultUser;
269
+ this.#offline = o.offline === true;
270
+ this.#mode = p.mode;
271
+ const s = p.mode === "auto" ? p.intervalSeconds : p.mode === "lazy" ? p.ttlSeconds : void 0;
272
+ if (s !== void 0 && !(s >= 30)) this.#warn("i", `polling interval raised to the 30 s minimum`);
273
+ this.#interval = Math.max(30, s ?? 60) * 1e3 || 3e4;
274
+ this.#initWait = Math.max(0, (p.mode === "auto" ? p.maxInitWaitSeconds : void 0) ?? 5) * 1e3;
275
+ if (o.bootstrap !== void 0) this.#adopt(o.bootstrap, "bootstrap", null, 0);
276
+ if (ov && "values" in ov) this.#setOverrides(ov.values);
277
+ else if (ov && "env" in ov) {
278
+ try {
279
+ this.#setOverrides(envOverrides(ov.env));
280
+ } catch (e) {
281
+ this.#error("overrides", e.message, e);
282
+ }
283
+ }
284
+ this.#recompute(false);
285
+ if (this.#mode === "auto" && this.#key) this.#unwatchVisibility = watchVisibility((hidden) => this.#visibility(hidden));
286
+ this.#init = this.#start();
287
+ }
288
+ /** `initializing`, `ready`, `stale`, `key_invalid`, `offline` or `closed`. */
289
+ get state() {
290
+ return this.#state;
291
+ }
292
+ /** Subscribe to `ready`, `configChanged`, `evaluated` or `error`. Returns a function that unsubscribes. */
293
+ on(event, listener) {
294
+ this.#on[event].add(listener);
295
+ return () => this.off(event, listener);
296
+ }
297
+ off(event, listener) {
298
+ this.#on[event].delete(listener);
299
+ }
300
+ /** The user evaluations use when a call passes none. */
301
+ setDefaultUser(user) {
302
+ this.#user = user;
303
+ }
304
+ /** The value of a flag or setting for a user; the default on any failure. Never throws. */
305
+ async getValue(key, defaultValue, user) {
306
+ return (await this.getValueDetails(key, defaultValue, user)).value;
307
+ }
308
+ /** The value plus why: reason, matched rule or split, error code, warnings and revision. Never throws. */
309
+ async getValueDetails(key, defaultValue, user) {
310
+ return this.#eval(key, defaultValue, user, false);
311
+ }
312
+ /** A json (or string) setting, parsed. A parse failure, a missing key or another type returns the default. Never throws. */
313
+ async getJson(key, defaultValue, user) {
314
+ return (await this.#eval(key, defaultValue, user, true)).value;
315
+ }
316
+ /** Every setting's value for a user (json settings parsed), as a null-prototype object. Never throws. */
317
+ async getAllValues(user) {
318
+ await this.#ensure();
319
+ return toValues(resolveAll(this.#config, user ?? this.#user, this.#layer()).map((d) => this.#evaluated(d)));
320
+ }
321
+ /** The config as it is now, for synchronous evaluation. Does not wait for the first download. */
322
+ snapshot() {
323
+ return new FlagsSnapshot(this.#config, this.#configRaw, this.#user, this.#layer());
324
+ }
325
+ /** Resolves when start-up has settled: the first download finished or `maxInitWaitSeconds` passed. Never rejects. */
326
+ async waitForReady() {
327
+ await this.#init;
328
+ return this.#state;
329
+ }
330
+ /** Downloads the config now (any polling mode). Resolves when the attempt settles; never rejects. */
331
+ async forceRefresh() {
332
+ if (this.#closed || this.#offline || !this.#key) return;
333
+ await this.#fetchNow();
334
+ this.#schedule();
335
+ }
336
+ /** Stops all network access; evaluations keep using what is held. */
337
+ setOffline() {
338
+ if (this.#closed) return;
339
+ this.#offline = true;
340
+ this.#state = "offline";
341
+ this.#stop();
342
+ }
343
+ /** Resumes network access after `setOffline()` (or the `offline` option). Auto polling fetches at once. */
344
+ setOnline() {
345
+ if (this.#closed || !this.#offline) return;
346
+ this.#offline = false;
347
+ this.#state = this.#remote ? "stale" : "initializing";
348
+ if (this.#mode === "auto") void this.forceRefresh();
349
+ }
350
+ /** Stops timers, aborts a download in flight and stops watching an override file. Evaluations keep working on what is held. */
351
+ close() {
352
+ this.#closed = true;
353
+ this.#state = "closed";
354
+ this.#stop();
355
+ this.#unwatch?.();
356
+ this.#unwatchVisibility?.();
357
+ }
358
+ /** Hidden: no further polls (a download in flight finishes). Visible again: download now, then poll as usual. */
359
+ #visibility(hidden) {
360
+ const was = this.#hidden;
361
+ this.#hidden = hidden;
362
+ if (hidden) clearTimeout(this.#timer);
363
+ else if (was && this.#state !== "initializing") void this.forceRefresh();
364
+ }
365
+ async #eval(key, def, user, json) {
366
+ await this.#ensure();
367
+ return this.#evaluated(resolve(this.#config, key, def, user ?? this.#user, json, this.#layer()));
368
+ }
369
+ #stop() {
370
+ clearTimeout(this.#timer);
371
+ this.#abort?.abort();
372
+ }
373
+ async #start() {
374
+ await 0;
375
+ const ov = this.#o.overrides;
376
+ if (ov && "file" in ov) {
377
+ const apply = (values) => {
378
+ if (values) this.#setOverrides(values);
379
+ this.#recompute(true);
380
+ };
381
+ this.#unwatch = await fileOverrides(ov.file, ov.watch, apply, (m, e) => this.#error("overrides", m, e));
382
+ }
383
+ await this.#readCache();
384
+ if (this.#closed) ; else if (!this.#key) this.#state = "ready";
385
+ else if (this.#offline) this.#state = "offline";
386
+ else if (this.#mode === "auto" || this.#mode === "lazy" && this.#expired()) {
387
+ await this.#deadline(this.forceRefresh(), this.#initWait);
388
+ this.#schedule();
389
+ }
390
+ this.#emit("ready", this.#state);
391
+ }
392
+ async #deadline(p, ms) {
393
+ let t;
394
+ await Promise.race([p, new Promise((ok) => t = unref(setTimeout(ok, ms)))]);
395
+ clearTimeout(t);
396
+ }
397
+ async #ensure() {
398
+ if (this.#state === "initializing") await this.#init;
399
+ if (this.#mode === "lazy" && this.#key && !this.#offline && !this.#closed && this.#expired()) {
400
+ const p = this.#fetchNow();
401
+ if (!this.#remote) await this.#deadline(p, this.#timeout);
402
+ }
403
+ }
404
+ #expired() {
405
+ return Date.now() - this.#fetchedAt >= this.#interval;
406
+ }
407
+ #fetchNow() {
408
+ return this.#inflight ??= this.#download().finally(() => this.#inflight = null);
409
+ }
410
+ /** Auto polling: the next download after the jittered interval, later after errors (at most 4x) or when the server asks (Retry-After). */
411
+ #schedule() {
412
+ clearTimeout(this.#timer);
413
+ if (this.#closed || this.#offline || this.#hidden || this.#mode !== "auto" || !this.#key) return;
414
+ const i = this.#interval;
415
+ let delay = i * (0.9 + 0.2 * Math.random());
416
+ if (this.#failures) delay = Math.min(4 * i, delay + backoffMs(this.#failures));
417
+ delay = Math.max(delay, this.#retryAfter);
418
+ this.#timer = unref(setTimeout(() => void this.forceRefresh(), delay));
419
+ }
420
+ async #download() {
421
+ if (this.#closed || this.#offline || !this.#key) return;
422
+ this.#retryAfter = 0;
423
+ let failure = ["network", "download failed"];
424
+ for (const base of this.#bases) {
425
+ const abort = this.#abort = new AbortController();
426
+ const timer = setTimeout(() => abort.abort(), this.#timeout);
427
+ try {
428
+ const headers = deliveryHeaders(this.#etag);
429
+ const res = await this.#fetch(`${base}/v1/configs/${encodeURIComponent(this.#key)}/config.json`, { headers, signal: abort.signal });
430
+ if (res.status < 500) return await this.#handle(res);
431
+ cancel(res);
432
+ failure = ["http_status", `download failed: HTTP ${res.status}`];
433
+ } catch (e) {
434
+ if (this.#closed || this.#offline) return;
435
+ failure = ["network", `download failed: ${abort.signal.aborted ? "timeout" : e?.name}`, e];
436
+ } finally {
437
+ clearTimeout(timer);
438
+ }
439
+ }
440
+ this.#failed(...failure);
441
+ }
442
+ async #handle(res) {
443
+ const status = res.status;
444
+ if (status === 304) return this.#succeeded();
445
+ if (status !== 200) {
446
+ cancel(res);
447
+ this.#retryAfter = parseRetryAfterMs(res.headers, Date.now()) ?? 0;
448
+ if (status !== 404) return this.#failed(status === 429 ? "rate_limited" : "http_status", `download failed: HTTP ${status}`);
449
+ this.#failed("key_invalid", "SDK key unknown, revoked or expired (404)");
450
+ if (!this.#closed && !this.#offline) this.#state = "key_invalid";
451
+ return;
452
+ }
453
+ const tooBig = () => this.#failed("too_large", "config over 2 MiB refused");
454
+ if (Number(res.headers.get("content-length")) > MAX_CONFIG_BYTES) return cancel(res), tooBig();
455
+ const reader = res.body?.getReader();
456
+ const decoder = new TextDecoder();
457
+ let text = "";
458
+ let size = 0;
459
+ for (let r; reader && !(r = await reader.read()).done; ) {
460
+ if ((size += r.value.byteLength) > MAX_CONFIG_BYTES) return void reader.cancel().catch(() => void 0), tooBig();
461
+ text += decoder.decode(r.value, { stream: true });
462
+ }
463
+ if (this.#adopt(text + decoder.decode(), "fetch", res.headers.get("etag"), Date.now()) !== false) this.#succeeded();
464
+ }
465
+ #succeeded() {
466
+ this.#failures = 0;
467
+ this.#fetchedAt = Date.now();
468
+ if (!this.#closed && !this.#offline) this.#state = "ready";
469
+ }
470
+ #failed(code, message, cause) {
471
+ this.#failures++;
472
+ if (!this.#closed && !this.#offline) this.#state = "stale";
473
+ this.#error(code, message, cause);
474
+ }
475
+ /**
476
+ * Takes a config from any source when it is newer than the one held (never an older revision within a
477
+ * generation). Returns false when the body was rejected, true when taken, undefined when older.
478
+ */
479
+ #adopt(input, source, etag, fetchedAt) {
480
+ const fetched = source === "fetch";
481
+ let raw;
482
+ let parsed;
483
+ try {
484
+ raw = typeof input === "string" ? JSON.parse(input) : input;
485
+ parsed = parseConfig(raw);
486
+ } catch (e) {
487
+ const args = [e instanceof ConfigParseError ? e.code : "PARSE_ERROR", `${source} config rejected: ${e.message}`, e];
488
+ if (fetched) this.#failed(...args);
489
+ else this.#error(...args);
490
+ return false;
491
+ }
492
+ if (!isNewerConfig(this.#remote, parsed)) return void 0;
493
+ this.#remote = parsed;
494
+ this.#remoteRaw = raw;
495
+ this.#source = source;
496
+ this.#etag = etag;
497
+ this.#fetchedAt = fetchedAt;
498
+ if (!this.#fixedBase) {
499
+ const hinted = deliveryOrigins(parsed.delivery?.baseUrls ?? [], (m) => this.#warn(m, m));
500
+ this.#bases = hinted.length ? hinted : [DEFAULT_BASE];
501
+ }
502
+ this.#recompute(true);
503
+ if (fetched) void this.#writeCache(input);
504
+ return true;
505
+ }
506
+ #setOverrides(values) {
507
+ this.#overrideValues = values;
508
+ const { settings, skipped } = overrideSettings(values, (k) => this.#remote?.settingType(k));
509
+ if (skipped.length) this.#error("overrides", `overrides skipped: ${skipped}`);
510
+ this.#overrides = settings;
511
+ }
512
+ /** Rebuilds the evaluated config from the remote one and the overrides. */
513
+ #recompute(emit) {
514
+ const raw = combine(this.#remoteRaw, this.#overrides, this.#behaviour);
515
+ let parsed = this.#remote;
516
+ try {
517
+ if (raw && raw !== this.#remoteRaw) parsed = parseConfig(raw);
518
+ } catch (e) {
519
+ this.#error("overrides", `overrides rejected: ${e.message}`, e);
520
+ }
521
+ this.#config = raw ? parsed : null;
522
+ this.#configRaw = parsed === this.#remote ? this.#remoteRaw : raw;
523
+ this.#warned.clear();
524
+ if (emit && parsed) {
525
+ const source = this.#overrides && (this.#behaviour === "local_only" || !this.#remote) ? "overrides" : this.#source;
526
+ this.#emit("configChanged", { revision: parsed.revision, generation: parsed.generation, source });
527
+ }
528
+ }
529
+ #cacheKey() {
530
+ return `productcraft-flags:v1:${hashConfidential(this.#key, "", "cache-key").slice(0, 32)}`;
531
+ }
532
+ async #readCache() {
533
+ const cache = this.#o.cache;
534
+ if (!cache || !this.#key) return;
535
+ try {
536
+ const entry = await cache.get(this.#cacheKey());
537
+ if (!entry) return;
538
+ const { config, etag, fetched_at } = JSON.parse(entry);
539
+ this.#adopt(config, "cache", etag ?? null, Number(fetched_at) || 0);
540
+ } catch (e) {
541
+ this.#error("cache", "cache read failed", e);
542
+ }
543
+ }
544
+ async #writeCache(text) {
545
+ try {
546
+ await this.#o.cache?.set(this.#cacheKey(), JSON.stringify({ config: text, etag: this.#etag, fetched_at: this.#fetchedAt }));
547
+ } catch (e) {
548
+ this.#error("cache", "cache write failed", e);
549
+ }
550
+ }
551
+ #layer() {
552
+ if (this.#source === "cache" || this.#source === "bootstrap") return this.#state === "ready" ? null : "CACHED";
553
+ return this.#state === "stale" || this.#state === "key_invalid" ? "STALE" : null;
554
+ }
555
+ #evaluated(d) {
556
+ for (const w of d.warnings) this.#warn(`${d.revision}|${w.key}|${w.code}`, `flag ${JSON.stringify(w.key)} (${w.code}): ${w.message}`);
557
+ this.#emit("evaluated", d);
558
+ return d;
559
+ }
560
+ /** Logs once per id (evaluation warnings: once per key, code and revision); id null logs always. A broken logger never breaks evaluation. */
561
+ #warn(id, message) {
562
+ if (id !== null && this.#warned.has(id)) return;
563
+ if (id !== null) this.#warned.add(id);
564
+ try {
565
+ this.#log?.warn(`[productcraft/flags] ${message}`);
566
+ } catch {
567
+ }
568
+ }
569
+ /** Emits `error`; logs it when nobody listens. */
570
+ #error(code, message, cause) {
571
+ if (!this.#on.error.size) this.#warn(null, message);
572
+ this.#emit("error", new FlagsClientError(code, message, cause === void 0 ? void 0 : { cause }));
573
+ }
574
+ #emit(event, arg) {
575
+ for (const listener of this.#on[event]) {
576
+ try {
577
+ listener(arg);
578
+ } catch (e) {
579
+ if (event !== "error") this.#error("listener", `a ${event} listener threw`, e);
580
+ }
581
+ }
582
+ }
583
+ static {
584
+ setOverride = (client, key, value) => {
585
+ client.#setOverrides(put({ ...client.#overrideValues }, key, value));
586
+ client.#recompute(true);
587
+ };
588
+ }
589
+ };
590
+
591
+ export { FlagsClient, FlagsClientError, FlagsSnapshot, MAX_CONFIG_BYTES, setOverride };
592
+ //# sourceMappingURL=chunk-OI4KARX6.js.map
593
+ //# sourceMappingURL=chunk-OI4KARX6.js.map