@decocms/blocks 8.0.0 → 8.1.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 (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. package/tsconfig.json +0 -7
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Draft preview — pull-based decofile override.
2
+ * Draft preview — pull-based decofile snapshot.
3
3
  *
4
- * A Studio preview serves the working-tree draft at
5
- * `GET <origin>/_sandbox/decofile`; a production site pulls it and renders its
6
- * own real pages against it. This replaces pushing the decofile into a POST
7
- * body, which only deco's own runtime honours — Next.js and most frameworks
8
- * render on GET only.
4
+ * Studio serves the draft decofile (the merged `.deco/blocks/*.json` at the
5
+ * branch head) from its decofile API
6
+ * (`GET <origin>/api/<org>/decofile/<virtualMcpId>/<branch>?token=…`); a
7
+ * production site pulls it and renders its own real pages against it. This
8
+ * replaces pushing the decofile into a POST body, which only deco's own
9
+ * runtime honours — Next.js and most frameworks render on GET only.
9
10
  *
10
11
  * This module is the framework-agnostic half: token parsing, origin
11
12
  * validation, fetching, and version caching. Binding a resolved draft to a
@@ -23,56 +24,83 @@
23
24
  */
24
25
 
25
26
  /**
26
- * A parsed `?__draft=` token: `<host[:port]>@<version>`.
27
+ * A parsed `?__draft=` token: `<host[:port]><path[?query]>@<version>`.
27
28
  *
28
- * The token carries the AUTHORITY of the draft content API, never a scheme or
29
- * path — a full URL would be an SSRF vector, and the scheme is derived from
30
- * the matched domain instead. Reserved evolution: a future signed token uses a
31
- * distinguishable prefix (e.g. `s1.`), so this strict two-part parse rejects
32
- * it cleanly rather than half-reading it.
29
+ * The token carries the AUTHORITY + PATH of the draft content API, never a
30
+ * scheme — a full URL would be an SSRF vector, and the scheme is derived from
31
+ * the matched domain instead. The path is REQUIRED and typically addresses
32
+ * Studio's decofile API (`/api/<org>/decofile/<virtualMcpId>/<branch>?token=…`);
33
+ * its query carries the signed draft grant.
33
34
  */
34
35
  export interface DraftPointer {
35
- /** Content-API authority, e.g. `abc.preview-studio.decocms.com` or `abc.localhost:60534`. */
36
+ /** Content-API authority, e.g. `studio.decocms.com` or `localhost:4000`. */
36
37
  host: string;
37
- /** Opaque content version (the server's ETag). Immutable → safe cache key. */
38
+ /** Path (+ query) on that authority serving the decofile JSON. */
39
+ path: string;
40
+ /** Opaque content version (the branch head sha / server ETag). Immutable → safe cache key. */
38
41
  version: string;
39
42
  }
40
43
 
41
- /** Lowercase DNS hostname, at least two labels (a bare label can't match any domain). */
42
- const HOST_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/;
44
+ /** Lowercase DNS hostname. A single label is allowed — exact-host domain
45
+ * entries (`localhost`, `local.studio.decocms.com`) can admit it. */
46
+ const HOST_RE =
47
+ /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
43
48
  const PORT_RE = /^[0-9]{1,5}$/;
44
49
  const VERSION_RE = /^[A-Za-z0-9._-]{1,64}$/;
50
+ /** Rooted path with an optional query; conservative charset, no `@`/`#`/space. */
51
+ const PATH_RE = /^\/[A-Za-z0-9/_.%~=&?-]*$/;
45
52
 
46
53
  /**
47
- * Parse `<host[:port]>@<version>`. Null on anything unexpected — callers fall
48
- * back to published content. Requires EXACTLY one `@`: a naive split accepts
49
- * `a@b@c` and silently uses the first two segments.
54
+ * Parse `<host[:port]><path>@<version>`. Null on anything unexpected — callers
55
+ * fall back to published content. Splits on the LAST `@` (neither the path
56
+ * charset nor a signed token may contain one, so a stray `@` fails validation
57
+ * rather than being half-read).
50
58
  */
51
- export function parseDraftPointer(raw: string | null | undefined): DraftPointer | null {
59
+ export function parseDraftPointer(
60
+ raw: string | null | undefined,
61
+ ): DraftPointer | null {
52
62
  if (!raw) return null;
53
- const parts = raw.split("@");
54
- if (parts.length !== 2) return null;
55
- const [authority, version] = parts;
56
- if (!authority || !version || !VERSION_RE.test(version)) return null;
57
-
58
- const [host, port, extra] = authority.toLowerCase().split(":");
63
+ const at = raw.lastIndexOf("@");
64
+ if (at <= 0 || at === raw.length - 1) return null;
65
+ const authorityAndPath = raw.slice(0, at);
66
+ const version = raw.slice(at + 1);
67
+ if (!VERSION_RE.test(version)) return null;
68
+
69
+ const slash = authorityAndPath.indexOf("/");
70
+ if (slash === -1) return null;
71
+ const authority = authorityAndPath.slice(0, slash).toLowerCase();
72
+ const path = authorityAndPath.slice(slash);
73
+ if (!PATH_RE.test(path)) return null;
74
+
75
+ const [host, port, extra] = authority.split(":");
59
76
  if (extra !== undefined) return null;
60
77
  if (!host || !HOST_RE.test(host)) return null;
61
78
  if (port !== undefined && !PORT_RE.test(port)) return null;
62
79
 
63
- return { host: port === undefined ? host : `${host}:${port}`, version };
80
+ return {
81
+ host: port === undefined ? host : `${host}:${port}`,
82
+ path,
83
+ version,
84
+ };
64
85
  }
65
86
 
66
87
  /**
67
88
  * Domains the draft content API may live under — deco-operated, so shipping
68
89
  * them as defaults adds no SSRF surface. `DECO_PREVIEW_API_DOMAINS` overrides
69
- * the whole list when set. Entries are dot-prefixed suffixes, which guarantees
70
- * a label boundary on match (`evil-preview-studio.decocms.com` cannot pass).
90
+ * the whole list when set.
91
+ *
92
+ * Two entry shapes: a dot-prefixed entry is a suffix match with a guaranteed
93
+ * label boundary (`evil-decocms.com` cannot pass `.decocms.com`); a bare entry
94
+ * is an exact-host match (needed for `localhost` and dev origins, which no
95
+ * suffix can admit). Order matters only for the local/port rule: the first
96
+ * matching entry decides whether a port and `http` are allowed.
71
97
  */
72
98
  export const DEFAULT_PREVIEW_API_DOMAINS = [
73
- ".preview-studio.decocms.com",
74
- ".local.studio.decocms.com",
99
+ "local.studio.decocms.com", // native/web dev origin (http, explicit port)
100
+ "localhost",
101
+ "127.0.0.1", // loopback dev — `localhost` can resolve to a different (IPv6) server
75
102
  ".localhost",
103
+ ".decocms.com", // hosted Studio (decofile API) + preview daemons
76
104
  ];
77
105
 
78
106
  function readApiDomains(env: Record<string, string | undefined>): string[] {
@@ -99,13 +127,26 @@ export function previewApiOriginForHost(
99
127
  ): string | null {
100
128
  const [host, port] = authority.toLowerCase().split(":");
101
129
  if (!host) return null;
102
- const domain = readApiDomains(envOrProcess(env)).find(
103
- (d) => host.length > d.length && host.endsWith(d),
130
+ const domain = readApiDomains(envOrProcess(env)).find((d) =>
131
+ d.startsWith(".") ? host.length > d.length && host.endsWith(d) : host === d,
104
132
  );
105
133
  if (!domain) return null;
106
- const local = domain.includes("localhost");
134
+ // Local entries may carry an explicit port; public domains may not (a
135
+ // public-domain token must not steer the fetch at odd ports).
136
+ const local =
137
+ domain === "localhost" ||
138
+ domain === "127.0.0.1" ||
139
+ domain.endsWith(".localhost") ||
140
+ domain === "local.studio.decocms.com";
107
141
  if (port !== undefined && !local) return null;
108
- return `${local ? "http" : "https"}://${host}${port === undefined ? "" : `:${port}`}`;
142
+ // Scheme is derived, never taken from the token. Plain-loopback dev hosts
143
+ // are http; local.studio.decocms.com is the native app's TLS dev origin
144
+ // (locally-trusted cert), so it — like every public domain — is https.
145
+ const insecure =
146
+ domain === "localhost" ||
147
+ domain === "127.0.0.1" ||
148
+ domain.endsWith(".localhost");
149
+ return `${insecure ? "http" : "https"}://${host}${port === undefined ? "" : `:${port}`}`;
109
150
  }
110
151
 
111
152
  /**
@@ -121,7 +162,7 @@ export function previewApiOriginForHost(
121
162
  // is invisible to the others. (The MIDDLEWARE runtime is a separate world
122
163
  // even so — which is why the page-side gate is the authoritative one and the
123
164
  // middleware only hard-gates when the env override is present.)
124
- const G = globalThis as { __decoDraftHosts?: string[] };
165
+ const G = globalThis as { __decoDraftHosts?: string[]; __decoSite?: string };
125
166
 
126
167
  /** Install the site-declared preview hosts. Called by the framework binding at setup. */
127
168
  export function setDraftPreviewHosts(hosts: readonly unknown[]): void {
@@ -131,6 +172,32 @@ export function setDraftPreviewHosts(hosts: readonly unknown[]): void {
131
172
  .filter(Boolean);
132
173
  }
133
174
 
175
+ /**
176
+ * Register the resolved site name (`DECO_SITE_NAME` / an explicit setup
177
+ * option, resolved by the framework binding at setup). deco-operated preview
178
+ * hosts are derived from it, both exact:
179
+ *
180
+ * - `<site>.deco.site` — the stable deco-hosted domain.
181
+ * - `<site>.deco-cx.workers.dev` — the workers.dev deploy URL
182
+ * (e.g. `acme-tanstack.deco-cx.workers.dev`).
183
+ *
184
+ * Both are MERGED with the site-block/env list rather than replacing it: they
185
+ * are deco-operated infra, so a signed draft grant can preview there out of the
186
+ * box, while a custom production domain — never inferred here — stays inert.
187
+ * Fed from the trusted setup-time site name, never from the request or a draft.
188
+ *
189
+ * Threat model, now that a named site is no longer inert by default: the
190
+ * request host is spoofable on a direct-to-origin request (the edge is trusted
191
+ * to set `x-forwarded-host`), so for a named site the SIGNED `?__draft=` grant
192
+ * is the sole remaining gate — host-scoping only bounds blast radius. Set
193
+ * `DECO_ALLOWED_PREVIEW_HOSTS=none` to kill preview entirely, including these
194
+ * inferred hosts, without a deploy.
195
+ */
196
+ export function setDecoSiteHost(site: string | null | undefined): void {
197
+ const s = (site ?? "").trim().toLowerCase();
198
+ G.__decoSite = s || undefined;
199
+ }
200
+
134
201
  /**
135
202
  * Hosts allowed to render drafts.
136
203
  *
@@ -138,20 +205,35 @@ export function setDraftPreviewHosts(hosts: readonly unknown[]): void {
138
205
  * reviewed in a PR, versioned with branches. `DECO_ALLOWED_PREVIEW_HOSTS`
139
206
  * REPLACES it when set: an operational escape hatch (kill a bad value without
140
207
  * a deploy, add a machine-specific port) — not the primary configuration.
208
+ *
209
+ * The deco-hosted domains inferred from the site name (via `setDecoSiteHost`)
210
+ * are always ADDED on top, so a signed draft grant can preview on
211
+ * deco-operated infra without any per-site config.
212
+ *
213
+ * The sentinel `DECO_ALLOWED_PREVIEW_HOSTS=none` is a KILL SWITCH: it disables
214
+ * preview entirely — the inferred hosts and the site block included — so a bad
215
+ * rollout can be stopped without a deploy. It must win over every other source.
141
216
  */
142
217
  function readAllowedHosts(env: Record<string, string | undefined>): string[] {
143
218
  const fromEnv = (env.DECO_ALLOWED_PREVIEW_HOSTS ?? "")
144
219
  .split(",")
145
220
  .map((s) => s.trim().toLowerCase())
146
221
  .filter(Boolean);
147
- return fromEnv.length > 0 ? fromEnv : (G.__decoDraftHosts ?? []);
222
+ if (fromEnv.includes("none")) return [];
223
+ const configured = fromEnv.length > 0 ? fromEnv : (G.__decoDraftHosts ?? []);
224
+ const site = G.__decoSite;
225
+ if (!site) return configured;
226
+ const inferred = [`${site}.deco.site`, `${site}.deco-cx.workers.dev`].filter(
227
+ (h) => !configured.includes(h),
228
+ );
229
+ return inferred.length > 0 ? [...configured, ...inferred] : configured;
148
230
  }
149
231
 
150
232
  /**
151
233
  * Whether `host` (as seen on the request) may render drafts.
152
234
  *
153
- * Compared against `DECO_ALLOWED_PREVIEW_HOSTS` verbatim, port included —
154
- * local dev is `localhost:3100`, not `localhost`. The header is spoofable by a
235
+ * Compared against the allowlist verbatim, port included — local dev is
236
+ * `localhost:3100`, not `localhost`. The header is spoofable by a
155
237
  * direct-to-origin request, but the draft id is the actual capability;
156
238
  * host-scoping bounds blast radius (production domains stay inert), it is not
157
239
  * a secret.
@@ -161,16 +243,23 @@ export function isDraftHostAllowed(
161
243
  env?: Record<string, string | undefined>,
162
244
  ): boolean {
163
245
  if (!host) return false;
164
- return readAllowedHosts(envOrProcess(env)).includes(host.trim().toLowerCase());
246
+ return readAllowedHosts(envOrProcess(env)).includes(
247
+ host.trim().toLowerCase(),
248
+ );
165
249
  }
166
250
 
167
251
  /**
168
252
  * True when any host is allowed to preview. A plain env read — callers use it
169
253
  * to gate BEFORE touching dynamic APIs (`cookies()`/`headers()`), so an
170
- * unconfigured site never loses static/ISR rendering. The per-request host
171
- * match happens later, in `isDraftHostAllowed`.
254
+ * unconfigured site never loses static/ISR rendering. A site with no config
255
+ * but a resolved name is now enabled here (its inferred `<site>.deco.site` /
256
+ * `<site>.deco-cx.workers.dev` hosts); `DECO_ALLOWED_PREVIEW_HOSTS=none`
257
+ * forces it back to fully inert. The per-request host match happens later, in
258
+ * `isDraftHostAllowed`.
172
259
  */
173
- export function isDraftPreviewEnabled(env?: Record<string, string | undefined>): boolean {
260
+ export function isDraftPreviewEnabled(
261
+ env?: Record<string, string | undefined>,
262
+ ): boolean {
174
263
  return readAllowedHosts(envOrProcess(env)).length > 0;
175
264
  }
176
265
 
@@ -179,7 +268,8 @@ function envOrProcess(
179
268
  ): Record<string, string | undefined> {
180
269
  return (
181
270
  env ??
182
- (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ??
271
+ (globalThis as { process?: { env?: Record<string, string | undefined> } })
272
+ .process?.env ??
183
273
  {}
184
274
  );
185
275
  }
@@ -208,7 +298,7 @@ export function clearDraftCache(): void {
208
298
  }
209
299
 
210
300
  export interface ResolveDraftOptions {
211
- /** Raw `<host[:port]>@<version>` token from the request. */
301
+ /** Raw `<host[:port]><path>@<version>` token from the request. */
212
302
  pointer: string | null | undefined;
213
303
  /** Defaults to `process.env`. */
214
304
  env?: Record<string, string | undefined>;
@@ -227,21 +317,33 @@ export async function resolveDraftDecofile(
227
317
  options: ResolveDraftOptions,
228
318
  ): Promise<Record<string, unknown> | null> {
229
319
  const env = envOrProcess(options.env);
230
- if (readAllowedHosts(env).length === 0) return null;
320
+ if (!isDraftPreviewEnabled(env)) return null;
231
321
 
232
322
  const parsed = parseDraftPointer(options.pointer);
233
323
  if (!parsed) return null;
234
324
 
235
- const cached = byVersion.get(parsed.version);
236
- if (cached) return cached;
237
-
325
+ // Origin validation BEFORE the cache: a cached version must never be served
326
+ // for a pointer whose authority the configuration would reject.
238
327
  const origin = previewApiOriginForHost(parsed.host, env);
239
328
  if (!origin) return null;
240
329
 
330
+ const cached = byVersion.get(parsed.version);
331
+ if (cached) return cached;
332
+
241
333
  const doFetch = options.fetchImpl ?? fetch;
334
+ // The pointer's version rides along as `v=`, making the fetch URL fully
335
+ // content-addressed (path + token + version). Today the server serves it
336
+ // no-store either way — token-protected drafts are deliberately NOT
337
+ // shared-cacheable (edge caches can't re-validate the grant, so revocation
338
+ // wouldn't propagate). The param still earns its place: version-tagged
339
+ // access logs, and it's the prerequisite for edge-validated caching later
340
+ // (a CDN worker checking the token per request, keyed on path+version)
341
+ // without another runtime deploy.
342
+ const url = new URL(parsed.path, origin);
343
+ url.searchParams.append("v", parsed.version);
242
344
  let res: Response;
243
345
  try {
244
- res = await doFetch(`${origin}/_sandbox/decofile`, { cache: "no-store" });
346
+ res = await doFetch(url.toString(), { cache: "no-store" });
245
347
  } catch {
246
348
  return null;
247
349
  }
@@ -277,7 +379,10 @@ export const DRAFT_COOKIE_NAME = "__deco_draft";
277
379
  export const DRAFT_QUERY_PARAM = "__draft";
278
380
 
279
381
  /** Read one cookie value out of a raw `Cookie:` header. */
280
- function readCookieValue(cookieHeader: string | null | undefined, name: string): string | null {
382
+ function readCookieValue(
383
+ cookieHeader: string | null | undefined,
384
+ name: string,
385
+ ): string | null {
281
386
  if (!cookieHeader) return null;
282
387
  for (const part of cookieHeader.split(";")) {
283
388
  const eq = part.indexOf("=");
@@ -328,10 +433,11 @@ export async function resolveDraftForRequest(
328
433
  options: ResolveDraftForRequestOptions = {},
329
434
  ): Promise<Record<string, unknown> | null> {
330
435
  const env = envOrProcess(options.env);
331
- if (readAllowedHosts(env).length === 0) return null;
436
+ if (!isDraftPreviewEnabled(env)) return null;
332
437
  const pointer = draftPointerFromRequest(request);
333
438
  if (!pointer) return null;
334
- const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
439
+ const host =
440
+ request.headers.get("x-forwarded-host") ?? request.headers.get("host");
335
441
  if (!isDraftHostAllowed(host, env)) return null;
336
442
  return resolveDraftDecofile({ pointer, env, fetchImpl: options.fetchImpl });
337
443
  }
@@ -342,7 +448,12 @@ export async function resolveDraftForRequest(
342
448
 
343
449
  type DraftOverrideGetter = () => Record<string, unknown> | null | undefined;
344
450
 
345
- let getDraftOverride: DraftOverrideGetter = () => undefined;
451
+ // globalThis-backed like the hosts above: bundlers can duplicate this module
452
+ // across graphs (nested node_modules installs, RSC layer splits), and a getter
453
+ // registered on one instance's module variable is invisible to the copy
454
+ // `loadBlocks()` imports — the framework binding then resolves the draft while
455
+ // the render silently serves published content.
456
+ const GG = globalThis as { __decoDraftOverrideGetter?: DraftOverrideGetter };
346
457
 
347
458
  /**
348
459
  * Inject the request-scoped draft getter.
@@ -353,10 +464,13 @@ let getDraftOverride: DraftOverrideGetter = () => undefined;
353
464
  * Never called → returns undefined → `loadBlocks()` behaves exactly as before.
354
465
  */
355
466
  export function setDraftOverrideGetter(getter: DraftOverrideGetter): void {
356
- getDraftOverride = getter;
467
+ GG.__decoDraftOverrideGetter = getter;
357
468
  }
358
469
 
359
470
  /** The current request's draft blocks, if a binding registered one. */
360
- export function getRequestDraftOverride(): Record<string, unknown> | null | undefined {
361
- return getDraftOverride();
471
+ export function getRequestDraftOverride():
472
+ | Record<string, unknown>
473
+ | null
474
+ | undefined {
475
+ return GG.__decoDraftOverrideGetter?.();
362
476
  }
package/src/cms/index.ts CHANGED
@@ -1,6 +1,9 @@
1
- export type { ApplySectionConventionsInput, SectionMetaEntry } from "./applySectionConventions";
1
+ export type {
2
+ ApplySectionConventionsInput,
3
+ SectionMetaEntry,
4
+ } from "./applySectionConventions";
2
5
  export { applySectionConventions } from "./applySectionConventions";
3
- export type { BlockSnapshot, BlockSource, KVNamespace } from "./blockSource";
6
+ export type { BlockSnapshot, BlockSource, KVNamespace, StoredRedirect } from "./blockSource";
4
7
  export {
5
8
  BUILD_HASH_ENV,
6
9
  BundledBlockSource,
@@ -9,9 +12,13 @@ export {
9
12
  DEPLOYMENTS_KEY,
10
13
  getDeploymentId,
11
14
  LIVE_KEY,
15
+ redirectKey,
16
+ redirectPrefix,
12
17
  revisionKey,
13
18
  snapshotKey,
14
19
  } from "./blockSource";
20
+ export type { DeferredTrigger } from "./deferredTrigger";
21
+ export { DEFAULT_DEFERRED_TRIGGER, getDeferredTrigger } from "./deferredTrigger";
15
22
  export type {
16
23
  DraftPointer,
17
24
  ResolveDraftForRequestOptions,
@@ -30,6 +37,7 @@ export {
30
37
  previewApiOriginForHost,
31
38
  resolveDraftDecofile,
32
39
  resolveDraftForRequest,
40
+ setDecoSiteHost,
33
41
  setDraftOverrideGetter,
34
42
  setDraftPreviewHosts,
35
43
  } from "./draftSource";
@@ -43,8 +51,13 @@ export {
43
51
  onChange,
44
52
  setBlocks,
45
53
  withBlocksOverride,
54
+ withDraftBlocks,
46
55
  } from "./loader";
47
- export type { OnBeforeResolveProps, SectionModule, SectionOptions } from "./registry";
56
+ export type {
57
+ OnBeforeResolveProps,
58
+ SectionModule,
59
+ SectionOptions,
60
+ } from "./registry";
48
61
  export {
49
62
  getResolvedComponent,
50
63
  getSection,
@@ -59,12 +72,23 @@ export {
59
72
  registerSections,
60
73
  registerSectionsSync,
61
74
  setResolvedComponent,
75
+ setSectionRenderJson,
62
76
  } from "./registry";
77
+ export type {
78
+ DeferredRef,
79
+ RenderJson,
80
+ RenderJsonModule,
81
+ SerializableSection,
82
+ SerializedSection,
83
+ SerializeOptions,
84
+ } from "./renderJson";
85
+ export { isSecretValue, serializeRenderJson, stringifyWithoutSecrets } from "./renderJson";
63
86
  export type {
64
87
  AsyncRenderingConfig,
65
88
  CommerceLoader,
66
89
  DanglingReferenceHandler,
67
90
  DecoPageResult,
91
+ Deferred,
68
92
  DeferredSection,
69
93
  MatcherContext,
70
94
  PageSeo,
@@ -73,6 +97,8 @@ export type {
73
97
  } from "./resolve";
74
98
  export {
75
99
  addSkipResolveType,
100
+ asResolved,
101
+ BOT_UA_SUBSTRINGS,
76
102
  cacheDeferredRawProps,
77
103
  clearCommerceLoaders,
78
104
  evaluateMatcher,
@@ -81,9 +107,11 @@ export {
81
107
  getAsyncRenderingConfig,
82
108
  getDeferredRawProps,
83
109
  isBot,
110
+ isDeferred,
84
111
  isEagerRequest,
85
112
  isSeoSection,
86
113
  onBeforeResolve,
114
+ readDeferredRawProps,
87
115
  reExtractRawProps,
88
116
  registerBotPattern,
89
117
  registerCommerceLoader,
@@ -93,6 +121,7 @@ export {
93
121
  registerNeverDeferSections,
94
122
  registerSeoSections,
95
123
  resolveDecoPage,
124
+ resolveDeferred,
96
125
  resolveDeferredSection,
97
126
  resolveDeferredSectionFull,
98
127
  resolvePageSections,