@decocms/blocks 7.72.0 → 8.0.0-next.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 (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
@@ -1,328 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- type ExperimentConfig,
4
- pickWeightedVariant,
5
- readExperimentConfig,
6
- resolveExperimentVariant,
7
- weightsFingerprint,
8
- } from "./experiments";
9
- import {
10
- parseSegmentCookie,
11
- type StoredFlag,
12
- segmentCacheToken,
13
- serializeSegmentCookie,
14
- } from "./flags";
15
-
16
- type Payload = { collectionId: string };
17
-
18
- /** Contract 1's example document, verbatim. */
19
- const CONFIG: ExperimentConfig<Payload> = {
20
- version: 1,
21
- experiments: [
22
- {
23
- key: "plp-ranking",
24
- variants: [
25
- { id: "control", weight: 95, payload: { collectionId: "139" } },
26
- { id: "model-b", weight: 5, payload: { collectionId: "412" } },
27
- ],
28
- },
29
- ],
30
- };
31
-
32
- /** Same experiment after a ramp stage advances 5% -> 10%. */
33
- const RAMPED: ExperimentConfig<Payload> = {
34
- version: 1,
35
- experiments: [
36
- {
37
- key: "plp-ranking",
38
- variants: [
39
- { id: "control", weight: 90, payload: { collectionId: "139" } },
40
- { id: "model-b", weight: 10, payload: { collectionId: "412" } },
41
- ],
42
- },
43
- ],
44
- };
45
-
46
- /**
47
- * One request: a cookie in, a fresh assignment sink, a fixed RNG sample.
48
- * Mirrors what the framework threads through in production.
49
- */
50
- function request(
51
- config: ExperimentConfig<Payload> | null,
52
- cookie: string | undefined,
53
- rand: number,
54
- ) {
55
- const assignments: StoredFlag[] = [];
56
- const resolve = () =>
57
- resolveExperimentVariant<Payload>("plp-ranking", {
58
- config,
59
- segmentCookie: cookie,
60
- assignments,
61
- random: () => rand,
62
- });
63
- // The cookie the framework would write back (persistFlags merges the same way).
64
- const nextCookie = () =>
65
- serializeSegmentCookie([
66
- ...parseSegmentCookie(cookie).filter((f) => !assignments.some((a) => a.name === f.name)),
67
- ...assignments,
68
- ]);
69
- return { resolve, assignments, nextCookie };
70
- }
71
-
72
- describe("pickWeightedVariant", () => {
73
- const variants = CONFIG.experiments[0].variants;
74
-
75
- it("splits the range in proportion to the weights", () => {
76
- expect(pickWeightedVariant(variants, 0)).toBe("control");
77
- expect(pickWeightedVariant(variants, 0.94)).toBe("control");
78
- expect(pickWeightedVariant(variants, 0.96)).toBe("model-b");
79
- // 0.9999 must not fall off the end into `undefined`.
80
- expect(pickWeightedVariant(variants, 0.9999)).toBe("model-b");
81
- });
82
-
83
- it("holds the distribution over many draws", () => {
84
- let modelB = 0;
85
- for (let i = 0; i < 10_000; i++) {
86
- if (pickWeightedVariant(variants, i / 10_000) === "model-b") modelB++;
87
- }
88
- expect(modelB / 10_000).toBeCloseTo(0.05, 2);
89
- });
90
-
91
- it("handles N > 2 arms", () => {
92
- const three = [
93
- { id: "a", weight: 50, payload: {} },
94
- { id: "b", weight: 30, payload: {} },
95
- { id: "c", weight: 20, payload: {} },
96
- ];
97
- expect(pickWeightedVariant(three, 0.1)).toBe("a");
98
- expect(pickWeightedVariant(three, 0.6)).toBe("b");
99
- expect(pickWeightedVariant(three, 0.9)).toBe("c");
100
- });
101
-
102
- it("still splits proportionally when weights violate the sum-to-100 contract", () => {
103
- const bad = [
104
- { id: "a", weight: 1, payload: {} },
105
- { id: "b", weight: 1, payload: {} },
106
- ];
107
- expect(pickWeightedVariant(bad, 0.25)).toBe("a");
108
- expect(pickWeightedVariant(bad, 0.75)).toBe("b");
109
- });
110
- });
111
-
112
- describe("weightsFingerprint", () => {
113
- it("changes when a weight changes", () => {
114
- expect(weightsFingerprint(CONFIG.experiments[0].variants)).not.toBe(
115
- weightsFingerprint(RAMPED.experiments[0].variants),
116
- );
117
- });
118
-
119
- it("is stable under variant reordering", () => {
120
- const reversed = [...CONFIG.experiments[0].variants].reverse();
121
- expect(weightsFingerprint(reversed)).toBe(weightsFingerprint(CONFIG.experiments[0].variants));
122
- });
123
-
124
- it("never collides with the legacy -1 sentinel", () => {
125
- expect(weightsFingerprint(CONFIG.experiments[0].variants)).toBeGreaterThanOrEqual(0);
126
- });
127
- });
128
-
129
- describe("resolveExperimentVariant — first assignment", () => {
130
- it("assigns a fresh visitor and reports isFresh", async () => {
131
- const { resolve, assignments } = request(CONFIG, undefined, 0.99);
132
- const variant = await resolve();
133
-
134
- expect(variant).toEqual({
135
- experimentKey: "plp-ranking",
136
- variantId: "model-b",
137
- payload: { collectionId: "412" },
138
- isFresh: true,
139
- });
140
- expect(assignments).toEqual([
141
- {
142
- name: "plp-ranking",
143
- value: "model-b",
144
- pct: weightsFingerprint(CONFIG.experiments[0].variants),
145
- },
146
- ]);
147
- });
148
-
149
- it("routes the majority of fresh visitors to the heavy arm", async () => {
150
- const { resolve } = request(CONFIG, undefined, 0.5);
151
- expect((await resolve())?.variantId).toBe("control");
152
- });
153
-
154
- it("returns null when no config is published", async () => {
155
- expect(await request(null, undefined, 0.5).resolve()).toBeNull();
156
- });
157
-
158
- it("returns null when the key is not among the active experiments", async () => {
159
- const other: ExperimentConfig<Payload> = { version: 1, experiments: [] };
160
- expect(await resolveExperimentVariant<Payload>("plp-ranking", { config: other })).toBeNull();
161
- });
162
-
163
- it("resolves once per request even when several loaders ask", async () => {
164
- const { resolve, assignments } = request(CONFIG, undefined, 0.99);
165
- const [a, b] = [await resolve(), await resolve()];
166
-
167
- expect(b?.variantId).toBe(a?.variantId);
168
- expect(b?.isFresh).toBe(false); // only the first call assigned
169
- expect(assignments).toHaveLength(1);
170
- });
171
- });
172
-
173
- describe("resolveExperimentVariant — stickiness across requests", () => {
174
- it("re-serves the stored variant without re-rolling", async () => {
175
- const first = request(CONFIG, undefined, 0.99);
176
- expect((await first.resolve())?.variantId).toBe("model-b");
177
- const cookie = first.nextCookie();
178
-
179
- // Next request: an RNG sample that WOULD have drawn "control".
180
- const second = request(CONFIG, cookie, 0.1);
181
- const variant = await second.resolve();
182
-
183
- expect(variant?.variantId).toBe("model-b");
184
- expect(variant?.payload).toEqual({ collectionId: "412" });
185
- expect(variant?.isFresh).toBe(false);
186
- });
187
-
188
- it("stays sticky over many requests with adversarial RNG", async () => {
189
- let cookie = request(CONFIG, undefined, 0.99).nextCookie();
190
- const first = request(CONFIG, undefined, 0.99);
191
- await first.resolve();
192
- cookie = first.nextCookie();
193
-
194
- for (const rand of [0, 0.2, 0.5, 0.94, 0.999]) {
195
- const req = request(CONFIG, cookie, rand);
196
- expect((await req.resolve())?.variantId).toBe("model-b");
197
- cookie = req.nextCookie();
198
- }
199
- });
200
-
201
- it("honours a classic-deco cookie that carries no fingerprint", async () => {
202
- // pct absent -> parses as -1 -> must stick, not churn every legacy visitor.
203
- const legacy = btoa(encodeURIComponent(JSON.stringify({ exp: { "plp-ranking": "model-b" } })));
204
- const variant = await request(CONFIG, legacy, 0.1).resolve();
205
-
206
- expect(variant?.variantId).toBe("model-b");
207
- expect(variant?.isFresh).toBe(false);
208
- });
209
-
210
- it("re-rolls a visitor holding a variant that no longer exists", async () => {
211
- const stale = serializeSegmentCookie([
212
- {
213
- name: "plp-ranking",
214
- value: "model-z",
215
- pct: weightsFingerprint(CONFIG.experiments[0].variants),
216
- },
217
- ]);
218
- const variant = await request(CONFIG, stale, 0.1).resolve();
219
-
220
- expect(variant?.variantId).toBe("control");
221
- expect(variant?.isFresh).toBe(true);
222
- });
223
- });
224
-
225
- describe("resolveExperimentVariant — re-roll once, then stick, when weights change", () => {
226
- it("re-rolls on the ramp and re-sticks on the new weights", async () => {
227
- // Assigned under 95/5.
228
- const first = request(CONFIG, undefined, 0.99);
229
- expect((await first.resolve())?.variantId).toBe("model-b");
230
- const beforeRamp = first.nextCookie();
231
-
232
- // Ramp to 90/10: the stored fingerprint goes stale -> exactly one re-roll.
233
- const rerolled = request(RAMPED, beforeRamp, 0.5);
234
- const afterRamp = await rerolled.resolve();
235
- expect(afterRamp?.isFresh).toBe(true);
236
- expect(afterRamp?.variantId).toBe("control"); // 0.5 lands in the 90% arm
237
- const afterRampCookie = rerolled.nextCookie();
238
-
239
- // Every subsequent request sticks — no second re-roll.
240
- for (const rand of [0.99, 0.01, 0.5]) {
241
- const req = request(RAMPED, afterRampCookie, rand);
242
- const variant = await req.resolve();
243
- expect(variant?.variantId).toBe("control");
244
- expect(variant?.isFresh).toBe(false);
245
- }
246
- });
247
-
248
- it("writes the new fingerprint so the re-roll cannot repeat", async () => {
249
- const first = request(CONFIG, undefined, 0.99);
250
- await first.resolve();
251
-
252
- const rerolled = request(RAMPED, first.nextCookie(), 0.5);
253
- await rerolled.resolve();
254
-
255
- expect(rerolled.assignments[0].pct).toBe(weightsFingerprint(RAMPED.experiments[0].variants));
256
- });
257
- });
258
-
259
- describe("deco_segment carries the assignment (contract 4)", () => {
260
- it("stores the variant id under the experiment key", async () => {
261
- const req = request(CONFIG, undefined, 0.99);
262
- await req.resolve();
263
-
264
- const payload = JSON.parse(decodeURIComponent(atob(req.nextCookie())));
265
- expect(payload.exp).toEqual({ "plp-ranking": "model-b" });
266
- // Boolean buckets stay untouched, so analytics reading `active` is unaffected.
267
- expect(payload.active).toEqual([]);
268
- });
269
-
270
- it("coexists with a CMS boolean flag in the same cookie", async () => {
271
- const withFlag = serializeSegmentCookie([{ name: "TestHero", value: true, pct: 50 }]);
272
- const req = request(CONFIG, withFlag, 0.99);
273
- await req.resolve();
274
-
275
- const payload = JSON.parse(decodeURIComponent(atob(req.nextCookie())));
276
- expect(payload.active).toEqual(["TestHero"]);
277
- expect(payload.exp).toEqual({ "plp-ranking": "model-b" });
278
- expect(parseSegmentCookie(req.nextCookie())).toEqual(
279
- expect.arrayContaining([
280
- { name: "TestHero", value: true, pct: 50 },
281
- { name: "plp-ranking", value: "model-b", pct: expect.any(Number) },
282
- ]),
283
- );
284
- });
285
-
286
- it("folds into the CDN cache key so two variants never share cached HTML", async () => {
287
- const a = request(CONFIG, undefined, 0.99);
288
- const b = request(CONFIG, undefined, 0.1);
289
- await a.resolve();
290
- await b.resolve();
291
-
292
- const tokenA = segmentCacheToken(parseSegmentCookie(a.nextCookie()));
293
- const tokenB = segmentCacheToken(parseSegmentCookie(b.nextCookie()));
294
- expect(tokenA).not.toBe(tokenB);
295
- });
296
-
297
- it("keeps the cookie byte-identical to today when no experiment is assigned", () => {
298
- const flags: StoredFlag[] = [{ name: "TestHero", value: true, pct: 50 }];
299
- const payload = JSON.parse(decodeURIComponent(atob(serializeSegmentCookie(flags))));
300
- expect("exp" in payload).toBe(false);
301
- });
302
- });
303
-
304
- describe("readExperimentConfig", () => {
305
- const kv = (value: unknown) => ({ get: async () => value as never });
306
-
307
- it("reads contract 1's document", async () => {
308
- expect(await readExperimentConfig(kv(CONFIG), "www.acme.com")).toEqual(CONFIG);
309
- });
310
-
311
- it("returns null instead of throwing when the binding is missing", async () => {
312
- expect(await readExperimentConfig(undefined, "www.acme.com")).toBeNull();
313
- });
314
-
315
- it("returns null on an unset key or a malformed document", async () => {
316
- expect(await readExperimentConfig(kv(null), "www.acme.com")).toBeNull();
317
- expect(await readExperimentConfig(kv({ version: 1 }), "www.acme.com")).toBeNull();
318
- });
319
-
320
- it("returns null when KV itself fails — never a thrown request", async () => {
321
- const broken = {
322
- get: async () => {
323
- throw new Error("KV unavailable");
324
- },
325
- };
326
- expect(await readExperimentConfig(broken, "www.acme.com")).toBeNull();
327
- });
328
- });
@@ -1,164 +0,0 @@
1
- /**
2
- * Coverage for the shared SWR fetch cache — both the caching semantics
3
- * (fresh HIT / dedup / SWR stale-serve / cold MISS) AND the telemetry it now
4
- * emits (`deco.cache.requests` with `layer: "swr"` + `profile: <provider>`).
5
- * The whole point of this module is that instrumentation is automatic, so the
6
- * metric assertions are as load-bearing as the behavioral ones.
7
- */
8
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9
- import { configureMeter, type MeterAdapter } from "../middleware/observability";
10
- import { createFetchCache } from "./fetchCache";
11
-
12
- interface Counter {
13
- name: string;
14
- value: number;
15
- labels?: Record<string, unknown>;
16
- }
17
-
18
- function captureMeter(): { adapter: MeterAdapter; counters: Counter[] } {
19
- const counters: Counter[] = [];
20
- const adapter: MeterAdapter = {
21
- counterInc(name, value, labels) {
22
- counters.push({ name, value: value ?? 1, labels });
23
- },
24
- histogramRecord() {},
25
- };
26
- return { adapter, counters };
27
- }
28
-
29
- const KNOBS = {
30
- maxEntries: 100,
31
- freshTtlMs: { success: 1000, notFound: 500, serverError: 0 },
32
- staleIfErrorMs: 10_000,
33
- inflightBackstopMs: 15_000,
34
- };
35
-
36
- function jsonResponse(body: unknown, status = 200): Response {
37
- return new Response(JSON.stringify(body), {
38
- status,
39
- headers: { "content-type": "application/json" },
40
- });
41
- }
42
-
43
- let counters: Counter[];
44
-
45
- beforeEach(() => {
46
- const cap = captureMeter();
47
- counters = cap.counters;
48
- configureMeter(cap.adapter);
49
- });
50
-
51
- afterEach(() => {
52
- configureMeter({ counterInc: () => {} });
53
- vi.useRealTimers();
54
- });
55
-
56
- const statuses = () =>
57
- counters
58
- .filter((c) => c.name === "deco.cache.requests")
59
- .map((c) => c.labels?.["status"]);
60
-
61
- describe("createFetchCache — behavior", () => {
62
- it("cold call is a MISS, second call is a HIT with the cached body", async () => {
63
- const cache = createFetchCache({ provider: "vtex", ...KNOBS });
64
- let calls = 0;
65
- const doFetch = () => {
66
- calls++;
67
- return Promise.resolve(jsonResponse({ ok: true }));
68
- };
69
-
70
- const a = await cache.fetchWithCache("k", doFetch);
71
- const b = await cache.fetchWithCache("k", doFetch);
72
-
73
- expect(a).toEqual({ ok: true });
74
- expect(b).toEqual({ ok: true });
75
- expect(calls).toBe(1); // second served from cache
76
- expect(statuses()).toEqual(["MISS", "HIT"]);
77
- });
78
-
79
- it("dedups concurrent calls for the same key (one upstream, join = HIT)", async () => {
80
- const cache = createFetchCache({ provider: "vtex", ...KNOBS });
81
- let resolve!: (r: Response) => void;
82
- let calls = 0;
83
- const doFetch = () => {
84
- calls++;
85
- return new Promise<Response>((r) => {
86
- resolve = r;
87
- });
88
- };
89
-
90
- const p1 = cache.fetchWithCache("k", doFetch);
91
- const p2 = cache.fetchWithCache("k", doFetch);
92
- resolve(jsonResponse({ n: 1 }));
93
- const [a, b] = await Promise.all([p1, p2]);
94
-
95
- expect(a).toEqual({ n: 1 });
96
- expect(b).toEqual({ n: 1 });
97
- expect(calls).toBe(1); // only one upstream call
98
- expect(statuses()).toEqual(["MISS", "HIT"]);
99
- });
100
-
101
- it("serves stale within the SIE window (STALE-HIT) and revalidates in background", async () => {
102
- vi.useFakeTimers();
103
- const cache = createFetchCache({ provider: "vtex", ...KNOBS });
104
- let calls = 0;
105
- const doFetch = () => {
106
- calls++;
107
- return Promise.resolve(jsonResponse({ v: calls }));
108
- };
109
-
110
- await cache.fetchWithCache("k", doFetch); // MISS, caches { v: 1 }
111
- vi.setSystemTime(Date.now() + 1500); // past 1000ms fresh TTL, within SIE
112
-
113
- const stale = await cache.fetchWithCache("k", doFetch); // serves last-good
114
- expect(stale).toEqual({ v: 1 }); // stale body returned synchronously
115
- await vi.runAllTimersAsync(); // let background refresh settle
116
-
117
- expect(statuses()).toEqual(["MISS", "STALE-HIT"]);
118
- expect(calls).toBe(2); // background refresh ran
119
- });
120
-
121
- it("past the SIE window the entry is dropped and refetched (MISS again)", async () => {
122
- vi.useFakeTimers();
123
- const cache = createFetchCache({ provider: "vtex", ...KNOBS });
124
- const doFetch = () => Promise.resolve(jsonResponse({ ok: 1 }));
125
-
126
- await cache.fetchWithCache("k", doFetch); // MISS
127
- vi.setSystemTime(Date.now() + 1000 + 10_000 + 1); // past fresh + SIE
128
- await cache.fetchWithCache("k", doFetch); // too stale -> cold MISS
129
-
130
- expect(statuses()).toEqual(["MISS", "MISS"]);
131
- });
132
-
133
- it("isolates providers — distinct instances never share entries", async () => {
134
- const vtex = createFetchCache({ provider: "vtex", ...KNOBS });
135
- const magento = createFetchCache({ provider: "magento", ...KNOBS });
136
- await vtex.fetchWithCache("k", () => Promise.resolve(jsonResponse({ p: "vtex" })));
137
- const fromMagento = await magento.fetchWithCache("k", () =>
138
- Promise.resolve(jsonResponse({ p: "magento" })),
139
- );
140
- expect(fromMagento).toEqual({ p: "magento" }); // magento MISS, not vtex's entry
141
- });
142
- });
143
-
144
- describe("createFetchCache — telemetry labels", () => {
145
- it("stamps layer=swr and provider=<provider> on every emit (profile stays unset)", async () => {
146
- const cache = createFetchCache({ provider: "magento", ...KNOBS });
147
- await cache.fetchWithCache("k", () => Promise.resolve(jsonResponse({})));
148
- const emitted = counters.filter((c) => c.name === "deco.cache.requests");
149
- expect(emitted.length).toBe(1);
150
- expect(emitted[0]?.labels?.["layer"]).toBe("swr");
151
- expect(emitted[0]?.labels?.["provider"]).toBe("magento");
152
- // profile is reserved for the edge layer's page-type — must NOT be set here.
153
- expect(emitted[0]?.labels?.["profile"]).toBeUndefined();
154
- expect(emitted[0]?.labels?.["status"]).toBe("MISS");
155
- });
156
-
157
- it("is a no-op with no meter configured (never throws)", async () => {
158
- configureMeter({ counterInc: () => {} });
159
- const cache = createFetchCache({ provider: "vtex", ...KNOBS });
160
- await expect(
161
- cache.fetchWithCache("k", () => Promise.resolve(jsonResponse({}))),
162
- ).resolves.toEqual({});
163
- });
164
- });
@@ -1,91 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- parseSegmentCookie,
4
- type StoredFlag,
5
- segmentCacheToken,
6
- serializeSegmentCookie,
7
- trafficToPct,
8
- } from "./flags";
9
-
10
- describe("trafficToPct", () => {
11
- it("maps a ratio to a 0-100 integer", () => {
12
- expect(trafficToPct(0.5)).toBe(50);
13
- expect(trafficToPct(0.234)).toBe(23);
14
- });
15
-
16
- it("clamps out-of-range and non-finite values", () => {
17
- expect(trafficToPct(0)).toBe(0);
18
- expect(trafficToPct(-1)).toBe(0);
19
- expect(trafficToPct(1)).toBe(100);
20
- expect(trafficToPct(2)).toBe(100);
21
- expect(trafficToPct(NaN)).toBe(0);
22
- });
23
- });
24
-
25
- describe("deco_segment round-trip", () => {
26
- it("round-trips a single active flag", () => {
27
- const flags: StoredFlag[] = [{ name: "TestHero", value: true, pct: 50 }];
28
- expect(parseSegmentCookie(serializeSegmentCookie(flags))).toEqual(flags);
29
- });
30
-
31
- it("round-trips active + inactive flags (sorted by name)", () => {
32
- const flags: StoredFlag[] = [
33
- { name: "Zeta", value: false, pct: 20 },
34
- { name: "Alpha", value: true, pct: 70 },
35
- ];
36
- expect(parseSegmentCookie(serializeSegmentCookie(flags))).toEqual([
37
- { name: "Alpha", value: true, pct: 70 },
38
- { name: "Zeta", value: false, pct: 20 },
39
- ]);
40
- });
41
-
42
- it("produces the classic deco_segment shape that OneDollarStats reads", () => {
43
- const raw = serializeSegmentCookie([
44
- { name: "TestHero", value: true, pct: 50 },
45
- { name: "Promo", value: false, pct: 30 },
46
- ]);
47
- // Mirrors @decocms/apps OneDollarStats readFlagsFromCookie decode.
48
- const seg = JSON.parse(decodeURIComponent(atob(raw)));
49
- expect(seg.active).toContain("TestHero");
50
- expect(seg.inactiveDrawn).toContain("Promo");
51
- expect(seg.pct).toEqual({ TestHero: 50, Promo: 30 });
52
- });
53
-
54
- it("is raw base64 (no percent-escapes) so atob() works directly", () => {
55
- const raw = serializeSegmentCookie([{ name: "TestHero", value: true, pct: 50 }]);
56
- expect(raw).not.toMatch(/%/);
57
- expect(() => atob(raw)).not.toThrow();
58
- });
59
- });
60
-
61
- describe("parseSegmentCookie robustness", () => {
62
- it("returns [] for empty / nullish / malformed input", () => {
63
- expect(parseSegmentCookie(undefined)).toEqual([]);
64
- expect(parseSegmentCookie(null)).toEqual([]);
65
- expect(parseSegmentCookie("")).toEqual([]);
66
- expect(parseSegmentCookie("not-base64-!!!")).toEqual([]);
67
- });
68
-
69
- it("marks classic segments without a pct fingerprint as pct: -1", () => {
70
- const raw = btoa(encodeURIComponent(JSON.stringify({ active: ["Legacy"], inactiveDrawn: [] })));
71
- expect(parseSegmentCookie(raw)).toEqual([{ name: "Legacy", value: true, pct: -1 }]);
72
- });
73
- });
74
-
75
- describe("segmentCacheToken", () => {
76
- it("is empty for no flags so non-A/B pages share a cache entry", () => {
77
- expect(segmentCacheToken([])).toBe("");
78
- });
79
-
80
- it("includes the pct fingerprint so a traffic change re-buckets", () => {
81
- const at50 = segmentCacheToken([{ name: "TestHero", value: true, pct: 50 }]);
82
- const at70 = segmentCacheToken([{ name: "TestHero", value: true, pct: 70 }]);
83
- expect(at50).not.toBe(at70);
84
- });
85
-
86
- it("differs by decision so cohorts split", () => {
87
- const on = segmentCacheToken([{ name: "TestHero", value: true, pct: 50 }]);
88
- const off = segmentCacheToken([{ name: "TestHero", value: false, pct: 50 }]);
89
- expect(on).not.toBe(off);
90
- });
91
- });
@@ -1,71 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { HttpError, STATUS_CODE, UserAgent } from "./http";
3
-
4
- describe("STATUS_CODE", () => {
5
- it("exposes common codes with the IANA-canonical names", () => {
6
- expect(STATUS_CODE.OK).toBe(200);
7
- expect(STATUS_CODE.MovedPermanently).toBe(301);
8
- expect(STATUS_CODE.NotFound).toBe(404);
9
- expect(STATUS_CODE.TooManyRequests).toBe(429);
10
- expect(STATUS_CODE.InternalServerError).toBe(500);
11
- });
12
-
13
- it("is readonly at the type level", () => {
14
- // @ts-expect-error — assigning into the const map should not type-check.
15
- STATUS_CODE.OK = 999;
16
- // Even though the assignment is allowed at runtime (frozen-by-convention),
17
- // we just want the type to flag it. The value is whatever JS allows.
18
- expect(typeof STATUS_CODE.OK).toBe("number");
19
- });
20
- });
21
-
22
- describe("UserAgent", () => {
23
- it("accepts a string and exposes it via toString", () => {
24
- const ua = new UserAgent("Mozilla/5.0 (test)");
25
- expect(ua.toString()).toBe("Mozilla/5.0 (test)");
26
- });
27
-
28
- it("treats null as an empty UA string", () => {
29
- const ua = new UserAgent(null);
30
- expect(ua.toString()).toBe("");
31
- });
32
-
33
- it("exposes empty browser/os/cpu/device/engine accessors", () => {
34
- const ua = new UserAgent("anything");
35
- expect(ua.browser).toEqual({});
36
- expect(ua.os).toEqual({});
37
- expect(ua.cpu).toEqual({});
38
- expect(ua.device).toEqual({});
39
- expect(ua.engine).toEqual({});
40
- });
41
- });
42
-
43
- describe("HttpError", () => {
44
- it("captures status and message", () => {
45
- const err = new HttpError(404, "Missing");
46
- expect(err).toBeInstanceOf(Error);
47
- expect(err.name).toBe("HttpError");
48
- expect(err.status).toBe(404);
49
- expect(err.message).toBe("Missing");
50
- });
51
-
52
- it("defaults the message from the status when not provided", () => {
53
- const err = new HttpError(503);
54
- expect(err.message).toBe("HTTP 503");
55
- });
56
-
57
- it("preserves an optional body payload for downstream handling", () => {
58
- const body = { code: "rate_limited" };
59
- const err = new HttpError(429, "Too Many Requests", body);
60
- expect(err.body).toEqual(body);
61
- });
62
-
63
- it("supports `instanceof` discrimination", () => {
64
- const err = new HttpError(304);
65
- function isNotModified(e: unknown): e is HttpError {
66
- return e instanceof HttpError && e.status === 304;
67
- }
68
- expect(isNotModified(err)).toBe(true);
69
- expect(isNotModified(new Error("nope"))).toBe(false);
70
- });
71
- });
@@ -1,35 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { DEFAULT_INFLIGHT_TIMEOUT_MS, withInflightTimeout } from "./inflightTimeout";
3
-
4
- describe("withInflightTimeout", () => {
5
- it("returns the underlying value when work settles in time", async () => {
6
- const result = await withInflightTimeout(Promise.resolve(42), "ok-case");
7
- expect(result).toBe(42);
8
- });
9
-
10
- it("propagates rejection when underlying work rejects in time", async () => {
11
- await expect(
12
- withInflightTimeout(Promise.reject(new Error("boom")), "reject-case"),
13
- ).rejects.toThrow("boom");
14
- });
15
-
16
- it("rejects with a timeout error when underlying work never settles", async () => {
17
- vi.useFakeTimers();
18
- try {
19
- const hung = new Promise<number>(() => {});
20
- const raced = withInflightTimeout(hung, "hung-case", 1_000);
21
- // Swallow the eventual rejection so the runner doesn't see it as unhandled
22
- raced.catch(() => {});
23
-
24
- await vi.advanceTimersByTimeAsync(1_500);
25
- await expect(raced).rejects.toThrow(/timed out/);
26
- } finally {
27
- vi.useRealTimers();
28
- }
29
- });
30
-
31
- it("exports a sane default timeout", () => {
32
- expect(DEFAULT_INFLIGHT_TIMEOUT_MS).toBeGreaterThanOrEqual(1_000);
33
- expect(DEFAULT_INFLIGHT_TIMEOUT_MS).toBeLessThanOrEqual(60_000);
34
- });
35
- });