@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,519 +0,0 @@
1
- import { beforeEach, describe, expect, it } from "vitest";
2
-
3
- import {
4
- clearDraftCache,
5
- DEFAULT_PREVIEW_API_DOMAINS,
6
- draftPointerFromRequest,
7
- isDraftHostAllowed,
8
- isDraftPreviewEnabled,
9
- parseDraftPointer,
10
- previewApiOriginForHost,
11
- resolveDraftDecofile,
12
- resolveDraftForRequest,
13
- setDecoSiteHost,
14
- setDraftPreviewHosts,
15
- } from "./draftSource";
16
-
17
- const ENV_ON = { DECO_ALLOWED_PREVIEW_HOSTS: "preview.example" };
18
-
19
- function jsonResponse(body: unknown, init?: ResponseInit): Response {
20
- return new Response(JSON.stringify(body), {
21
- status: 200,
22
- headers: { "content-type": "application/json" },
23
- ...init,
24
- });
25
- }
26
-
27
- beforeEach(() => {
28
- clearDraftCache();
29
- });
30
-
31
- describe("parseDraftPointer", () => {
32
- it("parses <authority><path>@<version>, lowercasing the authority", () => {
33
- expect(
34
- parseDraftPointer(
35
- "Studio.decocms.com/api/acme/decofile/vm-1/main?token=Tok.abc@8c1d44e",
36
- ),
37
- ).toEqual({
38
- host: "studio.decocms.com",
39
- path: "/api/acme/decofile/vm-1/main?token=Tok.abc",
40
- version: "8c1d44e",
41
- });
42
- });
43
-
44
- it("keeps an explicit port on the authority, incl. bare localhost", () => {
45
- expect(parseDraftPointer("localhost:4000/api/o/decofile/m/b@v1")).toEqual({
46
- host: "localhost:4000",
47
- path: "/api/o/decofile/m/b",
48
- version: "v1",
49
- });
50
- });
51
-
52
- it("splits on the LAST @ — an earlier @ fails validation, never half-reads", () => {
53
- // The path charset excludes `@`, so a smuggled one lands in `path` and
54
- // fails PATH_RE rather than shifting the version boundary.
55
- expect(parseDraftPointer("a.example/x@y/z@v1")).toBeNull();
56
- expect(parseDraftPointer("a@b@c")).toBeNull();
57
- });
58
-
59
- it("requires a rooted path — authority-only tokens are gone", () => {
60
- // Non-backcompat: the daemon-era `<authority>@<version>` form is invalid.
61
- expect(parseDraftPointer("abc.preview-studio.decocms.com@v1")).toBeNull();
62
- expect(parseDraftPointer("a.example@v1")).toBeNull();
63
- });
64
-
65
- it("rejects anything that could escape the authority or path", () => {
66
- // No scheme, no userinfo, no fragment/space in the path — a full URL
67
- // fails structurally at parse time.
68
- expect(parseDraftPointer("https://evil.example/x@v1")).toBeNull();
69
- expect(parseDraftPointer("a.example:80:80/x@v1")).toBeNull();
70
- expect(parseDraftPointer("a.example:abc/x@v1")).toBeNull();
71
- expect(parseDraftPointer(".leading.dot/x@v1")).toBeNull();
72
- expect(parseDraftPointer("a.example/x#frag@v1")).toBeNull();
73
- expect(parseDraftPointer("a.example/x y@v1")).toBeNull();
74
- });
75
-
76
- it("validates the version charset — it becomes a cache key", () => {
77
- expect(parseDraftPointer("a.example/x@")).toBeNull();
78
- expect(parseDraftPointer(`a.example/x@${"x".repeat(65)}`)).toBeNull();
79
- expect(parseDraftPointer("a.example/x@v 1")).toBeNull();
80
- expect(parseDraftPointer(null)).toBeNull();
81
- });
82
- });
83
-
84
- describe("previewApiOriginForHost", () => {
85
- it("admits authorities under the default deco domains", () => {
86
- // Hosted Studio (the decofile API origin) via the .decocms.com suffix.
87
- expect(previewApiOriginForHost("studio.decocms.com", {})).toBe(
88
- "https://studio.decocms.com",
89
- );
90
- // Preview daemons keep working under the same suffix.
91
- expect(previewApiOriginForHost("abc.preview-studio.decocms.com", {})).toBe(
92
- "https://abc.preview-studio.decocms.com",
93
- );
94
- // Local dev: exact-host entries, http, explicit port allowed.
95
- expect(previewApiOriginForHost("localhost:4000", {})).toBe(
96
- "http://localhost:4000",
97
- );
98
- // The native app's dev origin serves TLS (locally-trusted cert): https,
99
- // but the explicit port is still allowed.
100
- expect(previewApiOriginForHost("local.studio.decocms.com:4420", {})).toBe(
101
- "https://local.studio.decocms.com:4420",
102
- );
103
- expect(previewApiOriginForHost("abc.localhost:60534", {})).toBe(
104
- "http://abc.localhost:60534",
105
- );
106
- });
107
-
108
- it("rejects hosts outside the domains — the token proposes, config disposes", () => {
109
- expect(previewApiOriginForHost("evil.example", {})).toBeNull();
110
- // Dot-prefixed suffixes guarantee a label boundary: a lookalike domain
111
- // that merely ends with the same characters cannot pass.
112
- expect(previewApiOriginForHost("evil-decocms.com", {})).toBeNull();
113
- // The suffix domain itself (no label in front) is not admitted.
114
- expect(previewApiOriginForHost("decocms.com", {})).toBeNull();
115
- });
116
-
117
- it("allows an explicit port only for local entries", () => {
118
- // A public-domain token must not steer the fetch at odd ports.
119
- expect(previewApiOriginForHost("studio.decocms.com:8500", {})).toBeNull();
120
- expect(
121
- previewApiOriginForHost("abc.preview-studio.decocms.com:8500", {}),
122
- ).toBeNull();
123
- });
124
-
125
- it("honours a configured override instead of the defaults", () => {
126
- const env = { DECO_PREVIEW_API_DOMAINS: ".staging.example" };
127
- expect(previewApiOriginForHost("abc.staging.example", env)).toBe(
128
- "https://abc.staging.example",
129
- );
130
- expect(previewApiOriginForHost("studio.decocms.com", env)).toBeNull();
131
- });
132
- });
133
-
134
- describe("gating", () => {
135
- it("is on iff an allowed host is configured — API domains have defaults", () => {
136
- expect(isDraftPreviewEnabled(ENV_ON)).toBe(true);
137
- expect(isDraftPreviewEnabled({})).toBe(false);
138
- });
139
-
140
- it("matches request hosts verbatim, port included, case-insensitively", () => {
141
- const env = { DECO_ALLOWED_PREVIEW_HOSTS: "acme.vtex.app, localhost:3100" };
142
- expect(isDraftHostAllowed("ACME.VTEX.APP", env)).toBe(true);
143
- expect(isDraftHostAllowed("localhost:3100", env)).toBe(true);
144
- expect(isDraftHostAllowed("acme.com.br", env)).toBe(false);
145
- expect(isDraftHostAllowed("localhost", env)).toBe(false);
146
- expect(isDraftHostAllowed(null, env)).toBe(false);
147
- expect(isDraftHostAllowed("acme.vtex.app", {})).toBe(false);
148
- });
149
- });
150
-
151
- // Canonical Studio decofile-API pointer prefix (authority + path, no version).
152
- const P = "studio.decocms.com/api/acme/decofile/vm-1/main?token=tok.abc";
153
-
154
- describe("resolveDraftDecofile", () => {
155
- it("fetches the token's path on its validated origin", async () => {
156
- const calls: string[] = [];
157
- const blocks = await resolveDraftDecofile({
158
- pointer: `${P}@v1`,
159
- env: ENV_ON,
160
- fetchImpl: (async (url: string) => {
161
- calls.push(String(url));
162
- return jsonResponse({ "pages-home": { title: "draft" } });
163
- }) as unknown as typeof fetch,
164
- });
165
-
166
- expect(blocks).toEqual({ "pages-home": { title: "draft" } });
167
- // The pointer's version rides along as `v=`, making the URL fully
168
- // content-addressed so Studio can answer with CDN-cacheable immutable
169
- // headers when it matches the served sha.
170
- expect(calls).toEqual([
171
- "https://studio.decocms.com/api/acme/decofile/vm-1/main?token=tok.abc&v=v1",
172
- ]);
173
- });
174
-
175
- it("is inert without a host allowlist — no fetch at all", async () => {
176
- let called = false;
177
- const blocks = await resolveDraftDecofile({
178
- pointer: `${P}@v1`,
179
- env: {},
180
- fetchImpl: (async () => {
181
- called = true;
182
- return jsonResponse({});
183
- }) as unknown as typeof fetch,
184
- });
185
- expect(blocks).toBeNull();
186
- expect(called).toBe(false);
187
- });
188
-
189
- it("refuses a parseable token whose origin no domain admits — no fetch, no cache", async () => {
190
- let called = false;
191
- const fetchImpl = (async () => {
192
- called = true;
193
- return jsonResponse({});
194
- }) as unknown as typeof fetch;
195
- expect(
196
- await resolveDraftDecofile({
197
- pointer: "abc.evil.example/x@v1",
198
- env: ENV_ON,
199
- fetchImpl,
200
- }),
201
- ).toBeNull();
202
- expect(called).toBe(false);
203
-
204
- // Origin validation runs BEFORE the cache: a version already cached from
205
- // an allowed origin must not be served for a disallowed authority.
206
- await resolveDraftDecofile({ pointer: `${P}@vX`, env: ENV_ON, fetchImpl });
207
- expect(called).toBe(true);
208
- expect(
209
- await resolveDraftDecofile({
210
- pointer: "abc.evil.example/x@vX",
211
- env: ENV_ON,
212
- fetchImpl,
213
- }),
214
- ).toBeNull();
215
- });
216
-
217
- it("caches by version — one fetch per version, not per request", async () => {
218
- let fetches = 0;
219
- const fetchImpl = (async () => {
220
- fetches++;
221
- return jsonResponse({ n: fetches });
222
- }) as unknown as typeof fetch;
223
-
224
- const a = await resolveDraftDecofile({
225
- pointer: `${P}@v1`,
226
- env: ENV_ON,
227
- fetchImpl,
228
- });
229
- const b = await resolveDraftDecofile({
230
- pointer: `${P}@v1`,
231
- env: ENV_ON,
232
- fetchImpl,
233
- });
234
- expect(fetches).toBe(1);
235
- expect(b).toBe(a);
236
-
237
- await resolveDraftDecofile({ pointer: `${P}@v2`, env: ENV_ON, fetchImpl });
238
- expect(fetches).toBe(2);
239
- });
240
-
241
- it("bounds the cache so multi-MB decofiles can't accumulate", async () => {
242
- let fetches = 0;
243
- const fetchImpl = (async () => {
244
- fetches++;
245
- return jsonResponse({ n: fetches });
246
- }) as unknown as typeof fetch;
247
-
248
- for (const v of ["v1", "v2", "v3", "v4"]) {
249
- await resolveDraftDecofile({
250
- pointer: `${P}@${v}`,
251
- env: ENV_ON,
252
- fetchImpl,
253
- });
254
- }
255
- expect(fetches).toBe(4);
256
- await resolveDraftDecofile({ pointer: `${P}@v1`, env: ENV_ON, fetchImpl });
257
- expect(fetches).toBe(5); // v1 evicted (cap 3) — re-fetch, never stale
258
- await resolveDraftDecofile({ pointer: `${P}@v4`, env: ENV_ON, fetchImpl });
259
- expect(fetches).toBe(5); // v4 resident
260
- });
261
-
262
- it("degrades to published on unreachable / non-2xx / unparseable", async () => {
263
- for (const fetchImpl of [
264
- async () => {
265
- throw new Error("ECONNREFUSED");
266
- },
267
- async () => new Response("nope", { status: 404 }),
268
- async () =>
269
- new Response("<html>not json</html>", {
270
- status: 200,
271
- headers: { "content-type": "text/html" },
272
- }),
273
- ]) {
274
- clearDraftCache();
275
- expect(
276
- await resolveDraftDecofile({
277
- pointer: `${P}@v1`,
278
- env: ENV_ON,
279
- fetchImpl: fetchImpl as unknown as typeof fetch,
280
- }),
281
- ).toBeNull();
282
- }
283
- });
284
- });
285
-
286
- // DEFAULT_PREVIEW_API_DOMAINS is part of the public contract — pin it.
287
- describe("DEFAULT_PREVIEW_API_DOMAINS", () => {
288
- it("ships the deco-operated origins plus local-dev exact hosts", () => {
289
- expect(DEFAULT_PREVIEW_API_DOMAINS).toEqual([
290
- "local.studio.decocms.com",
291
- "localhost",
292
- "127.0.0.1",
293
- ".localhost",
294
- ".decocms.com",
295
- ]);
296
- });
297
- });
298
-
299
- describe("site-block preview hosts", () => {
300
- it("enables the feature from the site block alone — no env needed", () => {
301
- setDraftPreviewHosts(["acme.vtex.app", "LOCALHOST:3100", 42, " "]);
302
- try {
303
- expect(isDraftPreviewEnabled({})).toBe(true);
304
- expect(isDraftHostAllowed("acme.vtex.app", {})).toBe(true);
305
- // Sanitized: lowercased, non-strings and blanks dropped.
306
- expect(isDraftHostAllowed("localhost:3100", {})).toBe(true);
307
- expect(isDraftHostAllowed("evil.example", {})).toBe(false);
308
- } finally {
309
- setDraftPreviewHosts([]);
310
- }
311
- });
312
-
313
- it("env REPLACES the block hosts when set — the operational escape hatch", () => {
314
- setDraftPreviewHosts(["acme.vtex.app"]);
315
- try {
316
- const env = { DECO_ALLOWED_PREVIEW_HOSTS: "other.example" };
317
- expect(isDraftHostAllowed("other.example", env)).toBe(true);
318
- // Not merged: env is a kill switch / override, so the block value must
319
- // not survive alongside it.
320
- expect(isDraftHostAllowed("acme.vtex.app", env)).toBe(false);
321
- } finally {
322
- setDraftPreviewHosts([]);
323
- }
324
- });
325
- });
326
-
327
- describe("deco-hosted preview domains (setDecoSiteHost)", () => {
328
- it("infers <site>.deco.site and enables the feature", () => {
329
- setDecoSiteHost("acme");
330
- try {
331
- expect(isDraftPreviewEnabled({})).toBe(true);
332
- expect(isDraftHostAllowed("acme.deco.site", {})).toBe(true);
333
- expect(isDraftHostAllowed("other.deco.site", {})).toBe(false);
334
- // A custom production domain is never inferred.
335
- expect(isDraftHostAllowed("www.acme.com", {})).toBe(false);
336
- } finally {
337
- setDecoSiteHost(null);
338
- }
339
- });
340
-
341
- it("infers the <site>.deco-cx.workers.dev deploy host", () => {
342
- setDecoSiteHost("acme-tanstack");
343
- try {
344
- expect(isDraftHostAllowed("acme-tanstack.deco-cx.workers.dev", {})).toBe(true);
345
- // Exact match only — another worker on the same account is not admitted.
346
- expect(isDraftHostAllowed("other-site.deco-cx.workers.dev", {})).toBe(false);
347
- // No nested subdomain widens the match.
348
- expect(
349
- isDraftHostAllowed("acme-tanstack.evil.deco-cx.workers.dev", {}),
350
- ).toBe(false);
351
- // Wrong apex.
352
- expect(isDraftHostAllowed("acme-tanstack.deco-cx.workers.example", {})).toBe(false);
353
- } finally {
354
- setDecoSiteHost(null);
355
- }
356
- });
357
-
358
- it("is merged ON TOP of the site block, not replacing it", () => {
359
- setDraftPreviewHosts(["acme.vtex.app"]);
360
- setDecoSiteHost("acme");
361
- try {
362
- expect(isDraftHostAllowed("acme.vtex.app", {})).toBe(true);
363
- expect(isDraftHostAllowed("acme.deco.site", {})).toBe(true);
364
- } finally {
365
- setDraftPreviewHosts([]);
366
- setDecoSiteHost(null);
367
- }
368
- });
369
-
370
- it("is merged ON TOP of the env escape hatch too", () => {
371
- setDecoSiteHost("acme");
372
- try {
373
- const env = { DECO_ALLOWED_PREVIEW_HOSTS: "other.example" };
374
- expect(isDraftHostAllowed("other.example", env)).toBe(true);
375
- expect(isDraftHostAllowed("acme.deco.site", env)).toBe(true);
376
- } finally {
377
- setDecoSiteHost(null);
378
- }
379
- });
380
-
381
- it("a blank/null/undefined site name registers no host", () => {
382
- // The binding passes DECO_SITE_NAME straight through — an unnamed site
383
- // (unset binding, blank value) is not armed.
384
- for (const site of [" ", null, undefined]) {
385
- setDecoSiteHost(site);
386
- try {
387
- expect(isDraftPreviewEnabled({})).toBe(false);
388
- } finally {
389
- setDecoSiteHost(null);
390
- }
391
- }
392
- });
393
-
394
- it("DECO_ALLOWED_PREVIEW_HOSTS=none kills the inferred hosts too", () => {
395
- setDraftPreviewHosts(["acme.vtex.app"]);
396
- setDecoSiteHost("acme");
397
- try {
398
- // The kill switch wins over the inferred hosts AND the site block, so a
399
- // bad rollout can be stopped without a deploy.
400
- const env = { DECO_ALLOWED_PREVIEW_HOSTS: "none" };
401
- expect(isDraftPreviewEnabled(env)).toBe(false);
402
- expect(isDraftHostAllowed("acme.deco.site", env)).toBe(false);
403
- expect(isDraftHostAllowed("acme.deco-cx.workers.dev", env)).toBe(false);
404
- expect(isDraftHostAllowed("acme.vtex.app", env)).toBe(false);
405
- } finally {
406
- setDraftPreviewHosts([]);
407
- setDecoSiteHost(null);
408
- }
409
- });
410
- });
411
-
412
- describe("draftPointerFromRequest", () => {
413
- it("reads the pointer from the __deco_draft cookie (in-preview navigation)", () => {
414
- const req = new Request(
415
- "https://preview.example/deco/invoke/site/loaders/x.ts",
416
- {
417
- headers: {
418
- cookie: "a=1; __deco_draft=abc.preview-studio.decocms.com@v1; b=2",
419
- },
420
- },
421
- );
422
- expect(draftPointerFromRequest(req)).toBe(
423
- "abc.preview-studio.decocms.com@v1",
424
- );
425
- });
426
-
427
- it("lets ?__draft= win over the cookie", () => {
428
- const req = new Request("https://preview.example/p?__draft=h@v2", {
429
- headers: { cookie: "__deco_draft=h@v1" },
430
- });
431
- expect(draftPointerFromRequest(req)).toBe("h@v2");
432
- });
433
-
434
- it("returns null on ?__draft=off even with a cookie set", () => {
435
- const req = new Request("https://preview.example/p?__draft=off", {
436
- headers: { cookie: "__deco_draft=h@v1" },
437
- });
438
- expect(draftPointerFromRequest(req)).toBeNull();
439
- });
440
-
441
- it("returns null with neither param nor cookie", () => {
442
- expect(
443
- draftPointerFromRequest(new Request("https://preview.example/p")),
444
- ).toBeNull();
445
- });
446
- });
447
-
448
- describe("resolveDraftForRequest", () => {
449
- const ENV = { DECO_ALLOWED_PREVIEW_HOSTS: "preview.example" };
450
- function invokeReq(host = "preview.example"): Request {
451
- return new Request(
452
- "https://preview.example/deco/invoke/site/loaders/x.ts",
453
- {
454
- method: "POST",
455
- headers: {
456
- "x-forwarded-host": host,
457
- cookie: `__deco_draft=${encodeURIComponent(`${P}@v1`)}`,
458
- },
459
- },
460
- );
461
- }
462
-
463
- it("binds the draft when host is allowed and the pointer resolves", async () => {
464
- const fetchImpl = (async () =>
465
- jsonResponse({
466
- "site/x": { value: "draft" },
467
- })) as unknown as typeof fetch;
468
- expect(
469
- await resolveDraftForRequest(invokeReq(), { env: ENV, fetchImpl }),
470
- ).toEqual({
471
- "site/x": { value: "draft" },
472
- });
473
- });
474
-
475
- it("is inert with no allowlist — never touches the network", async () => {
476
- let called = false;
477
- const fetchImpl = (async () => {
478
- called = true;
479
- return jsonResponse({});
480
- }) as unknown as typeof fetch;
481
- expect(
482
- await resolveDraftForRequest(invokeReq(), { env: {}, fetchImpl }),
483
- ).toBeNull();
484
- expect(called).toBe(false);
485
- });
486
-
487
- it("returns null when the request host is not on the allowlist (prod stays published)", async () => {
488
- let called = false;
489
- const fetchImpl = (async () => {
490
- called = true;
491
- return jsonResponse({});
492
- }) as unknown as typeof fetch;
493
- expect(
494
- await resolveDraftForRequest(invokeReq("prod.example"), {
495
- env: ENV,
496
- fetchImpl,
497
- }),
498
- ).toBeNull();
499
- expect(called).toBe(false);
500
- });
501
-
502
- it("returns null when the request carries no draft pointer", async () => {
503
- const req = new Request(
504
- "https://preview.example/deco/invoke/site/loaders/x.ts",
505
- {
506
- headers: { "x-forwarded-host": "preview.example" },
507
- },
508
- );
509
- let called = false;
510
- const fetchImpl = (async () => {
511
- called = true;
512
- return jsonResponse({});
513
- }) as unknown as typeof fetch;
514
- expect(
515
- await resolveDraftForRequest(req, { env: ENV, fetchImpl }),
516
- ).toBeNull();
517
- expect(called).toBe(false);
518
- });
519
- });
@@ -1,181 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- registerLayoutSections,
4
- registerSectionLoader,
5
- registerSections,
6
- resolveDecoPage,
7
- runSectionLoaders,
8
- setBlocks,
9
- unregisterLayoutSections,
10
- } from "./index";
11
-
12
- /**
13
- * Regression test for the layout-cache index-corruption bug that shipped in
14
- * @decocms/start@6.12.1 and was fixed in 6.12.2 (blocks commit 73d4f19,
15
- * "fix(cms): don't mutate shared cached section objects when stamping
16
- * index"). Two live production sites
17
- * hit this in the wild as an intermittent "footer renders above other
18
- * sections" bug under concurrent traffic.
19
- *
20
- * Mechanism: resolveDecoPage caches a layout section's (Header/Footer)
21
- * resolved output in a module-level Map, shared across every request that
22
- * references the same layout block — and dedupes concurrent in-flight
23
- * resolutions to the same shared Promise. Each request then stamps its own
24
- * page's flat position onto `.index` so mergeSections can sort eager +
25
- * deferred sections back into CMS order. If two concurrent requests need the
26
- * SAME cached layout section at DIFFERENT flat positions (e.g. page A has
27
- * Footer at index 0, page B has Footer at index 2), and stamping mutates the
28
- * shared cached object in place, whichever request's stamp lands last wins —
29
- * and both requests then see that same (possibly wrong-for-them) index.
30
- *
31
- * The fix clones the wrapper object before stamping, so each caller gets its
32
- * own `{ ...section, index }` and the shared cache/in-flight objects are
33
- * never touched.
34
- */
35
- describe("resolveDecoPage — layout section cache does not leak `.index` across concurrent requests", () => {
36
- it("gives each page its own correct Footer index when resolved concurrently", async () => {
37
- const FOOTER_TYPE = "site/sections/RaceFooter.tsx";
38
- const FILLER_TYPE = "site/sections/RaceFiller.tsx";
39
-
40
- // A controllable delay on Footer's resolver forces both concurrent
41
- // resolveDecoPage() calls to land on the SAME in-flight promise
42
- // (resolvedLayoutInflight), reproducing the exact shared-object window
43
- // the original bug required — without this, the two calls might resolve
44
- // sequentially and never actually share state.
45
- let releaseFooter: () => void = () => {};
46
- const footerGate = new Promise<void>((resolve) => {
47
- releaseFooter = resolve;
48
- });
49
-
50
- registerSections({
51
- [FOOTER_TYPE]: async () => {
52
- await footerGate;
53
- return { default: () => null };
54
- },
55
- [FILLER_TYPE]: async () => ({ default: () => null }),
56
- });
57
- registerLayoutSections([FOOTER_TYPE]);
58
-
59
- setBlocks({
60
- "pages-race-a": {
61
- path: "/race-a",
62
- // Footer at flat index 0 for this page.
63
- sections: [{ __resolveType: FOOTER_TYPE }, { __resolveType: FILLER_TYPE }],
64
- },
65
- "pages-race-b": {
66
- path: "/race-b",
67
- // Same Footer, but at flat index 2 for this page.
68
- sections: [
69
- { __resolveType: FILLER_TYPE },
70
- { __resolveType: FILLER_TYPE },
71
- { __resolveType: FOOTER_TYPE },
72
- ],
73
- },
74
- });
75
-
76
- try {
77
- const pending = Promise.all([resolveDecoPage("/race-a"), resolveDecoPage("/race-b")]);
78
-
79
- // Let both resolveDecoPage() calls start and reach the shared
80
- // in-flight Footer promise before releasing it — this is what forces
81
- // them onto the SAME cached/in-flight object rather than resolving
82
- // one after the other.
83
- await new Promise((r) => setTimeout(r, 10));
84
- releaseFooter();
85
-
86
- const [pageA, pageB] = await pending;
87
-
88
- const footerA = pageA?.resolvedSections.find((s) => s.component === FOOTER_TYPE);
89
- const footerB = pageB?.resolvedSections.find((s) => s.component === FOOTER_TYPE);
90
-
91
- expect(footerA).toBeDefined();
92
- expect(footerB).toBeDefined();
93
-
94
- // The bug: mutating a shared cached object in place means both pages
95
- // would observe whichever index was stamped last (either both 0 or
96
- // both 2), not their own correct position.
97
- expect(footerA?.index).toBe(0);
98
- expect(footerB?.index).toBe(2);
99
-
100
- // The fix clones the wrapper before stamping — each page's Footer
101
- // section must be its own object, not the same shared reference.
102
- expect(footerA).not.toBe(footerB);
103
- } finally {
104
- unregisterLayoutSections([FOOTER_TYPE]);
105
- }
106
- });
107
-
108
- it("does not leak index across sequential requests when the result is already in the TTL cache", async () => {
109
- // This covers the scenario missing from the concurrent test above:
110
- // Page A is fully served first (result lands in layoutCache), then Page B
111
- // arrives and hits the cache — it must get its own index, not Page A's.
112
- const FOOTER_KEY = "site/sections/SeqCacheFooter.tsx";
113
-
114
- registerLayoutSections([FOOTER_KEY]);
115
- registerSectionLoader(FOOTER_KEY, async (props) => props);
116
-
117
- const req = new Request("https://example.com/");
118
- const makeSection = (index: number) => ({
119
- component: FOOTER_KEY,
120
- props: {},
121
- key: `${FOOTER_KEY}-${index}`,
122
- index,
123
- });
124
-
125
- try {
126
- // First request: populate the TTL cache with index 2.
127
- const [sectionA] = await runSectionLoaders([makeSection(2)], req);
128
-
129
- // Second request: hits the TTL cache — must get index 7, not 2.
130
- const [sectionB] = await runSectionLoaders([makeSection(7)], req);
131
-
132
- expect(sectionA?.index).toBe(2);
133
- expect(sectionB?.index).toBe(7);
134
- // Must be separate objects — the cached entry must never carry an index.
135
- expect(sectionA).not.toBe(sectionB);
136
- } finally {
137
- unregisterLayoutSections([FOOTER_KEY]);
138
- }
139
- });
140
-
141
- it("mechanism check: mutating a shared object in place under concurrent stamping loses one side's index (isolated, framework-independent)", async () => {
142
- // This isolates the exact bug mechanism from the diff that shipped in
143
- // 6.12.1 and was reverted after the rollback, independent of the CMS
144
- // registry/cache machinery — proof that the failure mode is a plain JS
145
- // shared-mutable-object race, not something specific to this framework's
146
- // plumbing.
147
- type Wrapper = { component: string; index?: number };
148
-
149
- const sharedCached: Wrapper[] = [{ component: "Footer" }];
150
-
151
- // Old (buggy) behavior: mutate the shared array's objects in place.
152
- function stampBuggy(indexForThisCaller: number): Promise<Wrapper[]> {
153
- return Promise.resolve(sharedCached).then((sections) => {
154
- for (const s of sections) s.index = indexForThisCaller;
155
- return sections;
156
- });
157
- }
158
-
159
- // New (fixed) behavior: clone before stamping.
160
- function stampFixed(indexForThisCaller: number): Promise<Wrapper[]> {
161
- return Promise.resolve(sharedCached).then((sections) =>
162
- sections.map((s) => ({ ...s, index: indexForThisCaller })),
163
- );
164
- }
165
-
166
- // Two "requests" concurrently want different indices for the same
167
- // shared cached object. With the buggy stamper, whichever `.then()`
168
- // callback runs last (caller B, since microtasks run in scheduling
169
- // order) overwrites the object caller A already received a *reference*
170
- // to — so caller A's array ends up reporting caller B's index too.
171
- const [buggyA, buggyB] = await Promise.all([stampBuggy(0), stampBuggy(2)]);
172
- expect(buggyA[0].index).toBe(2); // <- corrupted: A wanted 0, sees 2
173
- expect(buggyB[0].index).toBe(2);
174
- expect(buggyA[0]).toBe(buggyB[0]); // same object reference — the bug
175
-
176
- const [fixedA, fixedB] = await Promise.all([stampFixed(0), stampFixed(2)]);
177
- expect(fixedA[0].index).toBe(0); // <- correct
178
- expect(fixedB[0].index).toBe(2); // <- correct
179
- expect(fixedA[0]).not.toBe(fixedB[0]); // independent objects — the fix
180
- });
181
- });