@decocms/blocks 8.5.2 → 8.7.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 (126) hide show
  1. package/dist/async/default.d.ts +10 -0
  2. package/dist/async/default.d.ts.map +1 -0
  3. package/dist/async/default.js +5 -0
  4. package/dist/async/default.js.map +1 -0
  5. package/dist/async/node.d.ts +3 -0
  6. package/dist/async/node.d.ts.map +1 -0
  7. package/dist/async/node.js +11 -0
  8. package/dist/async/node.js.map +1 -0
  9. package/dist/async/types.d.ts +6 -0
  10. package/dist/async/types.d.ts.map +1 -0
  11. package/dist/async/types.js +2 -0
  12. package/dist/async/types.js.map +1 -0
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/v8/bucketing.d.ts +24 -0
  18. package/dist/v8/bucketing.d.ts.map +1 -0
  19. package/dist/v8/bucketing.js +78 -0
  20. package/dist/v8/bucketing.js.map +1 -0
  21. package/dist/v8/builtins/campaigns.d.ts +36 -0
  22. package/dist/v8/builtins/campaigns.d.ts.map +1 -0
  23. package/dist/v8/builtins/campaigns.js +107 -0
  24. package/dist/v8/builtins/campaigns.js.map +1 -0
  25. package/dist/v8/builtins/data.d.ts +2 -2
  26. package/dist/v8/builtins/data.js +2 -2
  27. package/dist/v8/builtins/experiments.d.ts +27 -0
  28. package/dist/v8/builtins/experiments.d.ts.map +1 -0
  29. package/dist/v8/builtins/experiments.js +62 -0
  30. package/dist/v8/builtins/experiments.js.map +1 -0
  31. package/dist/v8/builtins/index.d.ts.map +1 -1
  32. package/dist/v8/builtins/index.js +7 -2
  33. package/dist/v8/builtins/index.js.map +1 -1
  34. package/dist/v8/builtins/matchers.d.ts +0 -14
  35. package/dist/v8/builtins/matchers.d.ts.map +1 -1
  36. package/dist/v8/builtins/matchers.js +0 -19
  37. package/dist/v8/builtins/matchers.js.map +1 -1
  38. package/dist/v8/cli/builtins.d.ts +6 -0
  39. package/dist/v8/cli/builtins.d.ts.map +1 -1
  40. package/dist/v8/cli/builtins.js +19 -0
  41. package/dist/v8/cli/builtins.js.map +1 -1
  42. package/dist/v8/cli/check/index.d.ts.map +1 -1
  43. package/dist/v8/cli/check/index.js +231 -8
  44. package/dist/v8/cli/check/index.js.map +1 -1
  45. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  46. package/dist/v8/cli/schema/builtinSchemas.js +76 -21
  47. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  48. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  49. package/dist/v8/cli/schema/generate.js +48 -2
  50. package/dist/v8/cli/schema/generate.js.map +1 -1
  51. package/dist/v8/client.d.ts +25 -0
  52. package/dist/v8/client.d.ts.map +1 -1
  53. package/dist/v8/client.js +58 -10
  54. package/dist/v8/client.js.map +1 -1
  55. package/dist/v8/cms.d.ts.map +1 -1
  56. package/dist/v8/cms.js +113 -44
  57. package/dist/v8/cms.js.map +1 -1
  58. package/dist/v8/content.d.ts +80 -1
  59. package/dist/v8/content.d.ts.map +1 -1
  60. package/dist/v8/content.js +149 -4
  61. package/dist/v8/content.js.map +1 -1
  62. package/dist/v8/current.d.ts +28 -0
  63. package/dist/v8/current.d.ts.map +1 -0
  64. package/dist/v8/current.js +77 -0
  65. package/dist/v8/current.js.map +1 -0
  66. package/dist/v8/draft.d.ts +40 -21
  67. package/dist/v8/draft.d.ts.map +1 -1
  68. package/dist/v8/draft.js +160 -25
  69. package/dist/v8/draft.js.map +1 -1
  70. package/dist/v8/experiments.d.ts +107 -0
  71. package/dist/v8/experiments.d.ts.map +1 -0
  72. package/dist/v8/experiments.js +292 -0
  73. package/dist/v8/experiments.js.map +1 -0
  74. package/dist/v8/hosts.d.ts +3 -2
  75. package/dist/v8/hosts.d.ts.map +1 -1
  76. package/dist/v8/hosts.js +3 -2
  77. package/dist/v8/hosts.js.map +1 -1
  78. package/dist/v8/index.d.ts +7 -5
  79. package/dist/v8/index.d.ts.map +1 -1
  80. package/dist/v8/index.js +6 -4
  81. package/dist/v8/index.js.map +1 -1
  82. package/dist/v8/preview/DraftBadge.d.ts +9 -1
  83. package/dist/v8/preview/DraftBadge.d.ts.map +1 -1
  84. package/dist/v8/preview/DraftBadge.js +42 -2
  85. package/dist/v8/preview/DraftBadge.js.map +1 -1
  86. package/dist/v8/remoteLoader.d.ts.map +1 -1
  87. package/dist/v8/remoteLoader.js +169 -21
  88. package/dist/v8/remoteLoader.js.map +1 -1
  89. package/dist/v8/resolver.d.ts +4 -2
  90. package/dist/v8/resolver.d.ts.map +1 -1
  91. package/dist/v8/resolver.js +11 -3
  92. package/dist/v8/resolver.js.map +1 -1
  93. package/dist/v8/settings.d.ts +16 -4
  94. package/dist/v8/settings.d.ts.map +1 -1
  95. package/dist/v8/settings.js +24 -21
  96. package/dist/v8/settings.js.map +1 -1
  97. package/dist/v8/types.d.ts +162 -22
  98. package/dist/v8/types.d.ts.map +1 -1
  99. package/package.json +35 -1
  100. package/src/async/default.ts +13 -0
  101. package/src/async/node.ts +12 -0
  102. package/src/async/types.ts +5 -0
  103. package/src/index.ts +4 -0
  104. package/src/v8/bucketing.ts +88 -0
  105. package/src/v8/builtins/campaigns.ts +120 -0
  106. package/src/v8/builtins/data.ts +2 -2
  107. package/src/v8/builtins/experiments.ts +72 -0
  108. package/src/v8/builtins/index.ts +7 -2
  109. package/src/v8/builtins/matchers.ts +0 -26
  110. package/src/v8/cli/builtins.ts +23 -0
  111. package/src/v8/cli/check/index.ts +289 -8
  112. package/src/v8/cli/schema/builtinSchemas.ts +82 -22
  113. package/src/v8/cli/schema/generate.ts +48 -3
  114. package/src/v8/client.ts +76 -10
  115. package/src/v8/cms.ts +134 -45
  116. package/src/v8/content.ts +168 -4
  117. package/src/v8/current.ts +98 -0
  118. package/src/v8/draft.ts +170 -30
  119. package/src/v8/experiments.ts +340 -0
  120. package/src/v8/hosts.ts +3 -2
  121. package/src/v8/index.ts +8 -4
  122. package/src/v8/preview/DraftBadge.tsx +72 -2
  123. package/src/v8/remoteLoader.ts +193 -26
  124. package/src/v8/resolver.ts +14 -4
  125. package/src/v8/settings.ts +35 -29
  126. package/src/v8/types.ts +163 -20
@@ -11,6 +11,9 @@
11
11
  *
12
12
  * - Renders nothing without a `pointer`, so a binding can mount it on every
13
13
  * page and pass the request's draft pointer (or `null`).
14
+ * - `unavailable`: the link named a draft that can't be read anymore, and
15
+ * the page shows the published site. Outside a frame, a calm notice says
16
+ * so (nothing to fix, nothing to retry); inside Studio's frame, nothing.
14
17
  * - Hidden inside a frame: Studio's site editor shows the draft in an iframe
15
18
  * with its own chrome. A reviewer who opens a shared link in their own tab
16
19
  * still sees it.
@@ -39,8 +42,17 @@ export interface DraftBadgeProps {
39
42
  * `?__draft=off`, which clears the draft cookie.
40
43
  */
41
44
  exitHref?: string;
45
+ /**
46
+ * The link's draft can't be read anymore (deleted, say): the binding
47
+ * rendered the published site instead. Shows a calm notice outside a frame.
48
+ */
49
+ unavailable?: boolean;
42
50
  }
43
51
 
52
+ /** What the notice says when a link's draft is gone. */
53
+ const DRAFT_UNAVAILABLE_MESSAGE =
54
+ "This draft isn't available anymore. You're seeing the published site.";
55
+
44
56
  /**
45
57
  * The link "Share preview" copies: the current URL with `?__draft=<pointer>`,
46
58
  * so the recipient sees this exact draft version.
@@ -114,7 +126,7 @@ function ShareIcon() {
114
126
  );
115
127
  }
116
128
 
117
- export function DraftBadge({ pointer, exitHref }: DraftBadgeProps): ReactNode {
129
+ export function DraftBadge({ pointer, exitHref, unavailable }: DraftBadgeProps): ReactNode {
118
130
  const [open, setOpen] = useState(false);
119
131
  const [copied, setCopied] = useState(false);
120
132
  const [visible, setVisible] = useState(false);
@@ -161,7 +173,8 @@ export function DraftBadge({ pointer, exitHref }: DraftBadgeProps): ReactNode {
161
173
  }
162
174
  }, [pointer]);
163
175
 
164
- if (!pointer || !visible) return null;
176
+ if (!visible) return null;
177
+ if (!pointer) return unavailable ? <UnavailableNotice /> : null;
165
178
 
166
179
  return (
167
180
  <div
@@ -236,6 +249,63 @@ export function DraftBadge({ pointer, exitHref }: DraftBadgeProps): ReactNode {
236
249
  );
237
250
  }
238
251
 
252
+ /** The notice for a link whose draft is gone: the published site is what shows. */
253
+ function UnavailableNotice() {
254
+ const [dismissed, setDismissed] = useState(false);
255
+ if (dismissed) return null;
256
+ return (
257
+ <div
258
+ role="status"
259
+ data-deco-preview-unavailable=""
260
+ style={{
261
+ position: "fixed",
262
+ bottom: 16,
263
+ left: 16,
264
+ zIndex: 2147483647,
265
+ display: "flex",
266
+ alignItems: "center",
267
+ gap: 10,
268
+ maxWidth: "calc(100vw - 32px)",
269
+ padding: "8px 8px 8px 12px",
270
+ background: "#fff",
271
+ color: "#1a1a1a",
272
+ borderRadius: 12,
273
+ boxShadow: "0 8px 30px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.05)",
274
+ fontFamily:
275
+ "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
276
+ fontSize: 13,
277
+ lineHeight: 1.4,
278
+ }}
279
+ >
280
+ <img
281
+ src={DECO_MARK_DATA_URI}
282
+ alt=""
283
+ width={18}
284
+ height={18}
285
+ style={{ display: "block", borderRadius: 4, flexShrink: 0 }}
286
+ />
287
+ <span>{DRAFT_UNAVAILABLE_MESSAGE}</span>
288
+ <button
289
+ type="button"
290
+ aria-label="Dismiss"
291
+ onClick={() => setDismissed(true)}
292
+ style={{
293
+ flexShrink: 0,
294
+ padding: "2px 8px",
295
+ background: "transparent",
296
+ border: "none",
297
+ color: "inherit",
298
+ cursor: "pointer",
299
+ fontSize: 16,
300
+ lineHeight: 1,
301
+ }}
302
+ >
303
+ ×
304
+ </button>
305
+ </div>
306
+ );
307
+ }
308
+
239
309
  function MenuItem({
240
310
  onClick,
241
311
  label,
@@ -8,14 +8,16 @@
8
8
  * last swapped in, or the fallback's content until then. Nothing persists
9
9
  * across restarts: every boot starts from the fallback.
10
10
  * - `update()` (the CMS calls it in the background, on first use and then
11
- * every interval) reads `sites/<site>/latest.json`,
12
- * `{ revision, schemaHash, publishedAt }`. Whoever is newer wins: when it
11
+ * every interval, and once per draft request, which waits for it, so a
12
+ * draft always shows over the latest release: `cms.checkRelease()`) reads
13
+ * `sites/<site>/latest.json`,
14
+ * `{ revision, schemaHash, publishedAt, previewHosts }`. Whoever is newer wins: when it
13
15
  * names a revision other than the one this process last swapped in, its
14
16
  * `schemaHash` equals the fallback's, and its `publishedAt` is later than
15
17
  * the fallback's `committedAt` (the commit time of the git HEAD
16
18
  * `deco content` built it from), it downloads
17
- * `sites/<site>/revisions/<revision>.json`, `{ revision, schemaHash, blocks }`,
18
- * and swaps it in whole. Otherwise, and on any error, memory stays as it is.
19
+ * `sites/<site>/revisions/<revision>.json`,
20
+ * `{ revision, schemaHash, blocks, previewHosts }`, and swaps it in whole. Otherwise, and on any error, memory stays as it is.
19
21
  * A fallback without a `schemaHash` never swaps; one without a `committedAt`
20
22
  * (a custom loader, an older content module, a build outside git) counts as
21
23
  * the oldest. Studio writes `publishedAt` on Publish, on "Make current" (a
@@ -25,17 +27,49 @@
25
27
  * a publish still loses to it.
26
28
  * Pointers aren't ordered among themselves, and the fallback's content is
27
29
  * never compared: only the two timestamps are.
30
+ * - `previewHosts` (host patterns) is where the site may be previewed: Studio
31
+ * knows the site's addresses and writes them into the release metadata
32
+ * whenever it writes `latest.json` or a revision (delivery is trusted).
33
+ * Previews are checked against the current release's list: the last
34
+ * `latest.json` read, whether or not its revision was swapped in (a newer
35
+ * bundle still previews where Studio says). With no list to check
36
+ * (PO 2026-10-22), previews are allowed on every host: a site with no
37
+ * `latest.json` yet (a 404), or one whose `latest.json` has no
38
+ * `previewHosts` (published before Studio wrote the list; its next publish
39
+ * writes one). A read that fails (a network error, a 5xx, a malformed
40
+ * `latest.json`) isn't "no list": until a read succeeds, previews stay
41
+ * closed, and a later failure keeps the last answer (a 404 once a list
42
+ * was read is a failure too: a published site stays published).
43
+ * A preview request before this process has read `latest.json` reads it
44
+ * then (only `latest.json`, once, shared); a read older than the interval
45
+ * is read again the same way, so `dev: true` follows Studio too.
28
46
  * - With `dev: true`, it never swaps, so local files win. `createCMS` passes
29
47
  * its `dev` option, or `NODE_ENV === "development"` when the site omits it;
30
48
  * this loader reads no environment itself.
31
49
  * - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
32
50
  * before it's buffered whole (a Worker isolate has 128 MB).
51
+ * - A client can ask for a published release by its commit SHA
52
+ * (`cms.client({ version })`): it's read from
53
+ * `sites/<site>/revisions/<sha>.json` on first use and kept in memory, a
54
+ * few at a time (the least recently used dropped first), since a revision
55
+ * never changes. One built with another schema than the bundled content is
56
+ * an error, never half a page.
33
57
  * - Without `site` it's a plain loader over the fallback.
34
58
  *
35
59
  * Instances are process-wide singletons, like `createCMS`'s.
36
60
  */
37
61
  import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
38
- import { isSnapshot, PEEK_RELEASE, peekRelease } from "./content.ts";
62
+ import {
63
+ BoundedMap,
64
+ isSnapshot,
65
+ PEEK_RELEASE,
66
+ PREVIEW_HOSTS,
67
+ peekRelease,
68
+ previewHostsOf,
69
+ READ_REVISION,
70
+ type ReleasePreviewHosts,
71
+ } from "./content.ts";
72
+ import { errors } from "./errors.ts";
39
73
  import { clearGlobals, contentIdentity } from "./identity.ts";
40
74
  import { isPlainObject } from "./json.ts";
41
75
  import type { Loader, Snapshot } from "./types.ts";
@@ -49,9 +83,15 @@ const INSTANCE_PREFIX = "decocms.blocks.remote:";
49
83
  const FETCH_TIMEOUT_MS = 10_000;
50
84
  /** The largest release accepted, in bytes of JSON. */
51
85
  const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
86
+ /** Published releases kept in memory once read (a client asked for one by its SHA). */
87
+ const CACHED_REVISIONS = 3;
52
88
  // OPEN: a revision is the git commit SHA; only SHA-1 (40 hex) object names are accepted.
53
89
  const REVISION = /^[0-9a-f]{40}$/;
54
90
  const SCHEMA_HASH = /^[0-9a-f]{64}$/;
91
+ /** How long a failed read of the preview hosts waits before a preview request tries again. */
92
+ const PREVIEW_HOSTS_RETRY_MS = 10_000;
93
+ /** How old the preview hosts may get before a preview request reads them again (without `interval`). */
94
+ const PREVIEW_HOSTS_MAX_AGE_MS = 60_000;
55
95
 
56
96
  interface RemoteLoaderOptions {
57
97
  site?: string;
@@ -66,6 +106,15 @@ interface Latest {
66
106
  revision: string;
67
107
  schemaHash: string;
68
108
  publishedAt: string;
109
+ /** Where the site may be previewed; `undefined` when Studio wrote none. */
110
+ previewHosts: string[] | undefined;
111
+ }
112
+
113
+ /** A revision file's body. */
114
+ interface Revision {
115
+ blocks: Record<string, unknown>;
116
+ schemaHash: string;
117
+ previewHosts: string[] | undefined;
69
118
  }
70
119
 
71
120
  class RemoteLoader implements Loader {
@@ -78,6 +127,18 @@ class RemoteLoader implements Loader {
78
127
  /** The release this process last swapped in; `undefined` serves the fallback. */
79
128
  #current: Snapshot | undefined;
80
129
  readonly #dev: boolean;
130
+ /** Published releases read by SHA; immutable, so a hit is never revalidated. */
131
+ readonly #revisions = new BoundedMap<string, Promise<Snapshot>>(CACHED_REVISIONS);
132
+ /**
133
+ * The preview hosts the last read of `latest.json` found (its list, or
134
+ * `"every"`: a 404, or no `previewHosts` in it), and when. A failed read
135
+ * leaves it as it was.
136
+ */
137
+ #hosts: { list: readonly string[] | "every"; at: number } | undefined;
138
+ /** A read of `latest.json` for its preview hosts, in flight. */
139
+ #hostsRead: Promise<void> | undefined;
140
+ /** When that read last failed. */
141
+ #hostsFailedAt = Number.NEGATIVE_INFINITY;
81
142
 
82
143
  constructor(
83
144
  fallback: Snapshot | Loader,
@@ -118,13 +179,117 @@ class RemoteLoader implements Loader {
118
179
  // OPEN: a process that already swapped a release in keeps it (memory stays as it is).
119
180
  if (!isNewer(latest.publishedAt, fallback.committedAt)) return { updated: false };
120
181
  if (latest.revision === this.#current?.revision) return { updated: false };
121
- const blocks = await this.#revision(site, latest);
122
- const next: Snapshot = { revision: latest.revision, blocks, schemaHash: latest.schemaHash };
182
+ const revision = await this.#revision(site, latest);
183
+ const next: Snapshot = {
184
+ revision: latest.revision,
185
+ blocks: revision.blocks,
186
+ schemaHash: latest.schemaHash,
187
+ };
188
+ if (revision.previewHosts !== undefined) next.previewHosts = revision.previewHosts;
123
189
  if (fallback.aliases !== undefined) next.aliases = fallback.aliases;
124
190
  this.#current = next;
125
191
  return { updated: true };
126
192
  }
127
193
 
194
+ /**
195
+ * The current release's preview hosts (see `PREVIEW_HOSTS`): the last
196
+ * successful read of `latest.json`, reading it first when there is none yet
197
+ * or it is older than the interval (`peek`: never). `"every"` when
198
+ * the site has no `latest.json` (a 404) or it names no `previewHosts`;
199
+ * `"unknown"` while no read has succeeded (a failed one is retried after a
200
+ * pause), so previews stay closed rather than open on an error.
201
+ */
202
+ async [PREVIEW_HOSTS](peek = false): Promise<ReleasePreviewHosts> {
203
+ const known = this.#hosts;
204
+ const maxAge = this.interval ?? PREVIEW_HOSTS_MAX_AGE_MS;
205
+ const stale = known === undefined || Date.now() - known.at >= maxAge;
206
+ if (!peek && stale && Date.now() - this.#hostsFailedAt >= PREVIEW_HOSTS_RETRY_MS) {
207
+ this.#hostsRead ??= this.#latest(encodeURIComponent(this.#site))
208
+ .then(
209
+ () => undefined,
210
+ () => {
211
+ // A 404 is an answer (`#latest` recorded it), not a failure.
212
+ if (this.#hosts === known) this.#hostsFailedAt = Date.now();
213
+ },
214
+ )
215
+ .finally(() => {
216
+ this.#hostsRead = undefined;
217
+ });
218
+ await this.#hostsRead;
219
+ }
220
+ const list = this.#hosts?.list;
221
+ if (list === undefined) return "unknown";
222
+ return list === "every" ? list : list.slice();
223
+ }
224
+
225
+ /** A published release by its commit SHA (see `READ_REVISION`). */
226
+ async [READ_REVISION](sha: string): Promise<Snapshot> {
227
+ if (!REVISION.test(sha)) throw errors.loaderFailed(`"${sha}" is not a release's commit SHA`);
228
+ if (this.#current?.revision === sha) return this.#current;
229
+ const fallback = this.#fallbackSnapshot ?? (await this.#loadFallback());
230
+ if (fallback.revision === sha) return fallback;
231
+ if (fallback.schemaHash === undefined) {
232
+ throw errors.loaderFailed(
233
+ `the release ${sha} can't be checked against this code: the bundled content has no schemaHash (run deco content)`,
234
+ );
235
+ }
236
+ const snapshot = await this.#readRevision(sha);
237
+ if (snapshot.schemaHash !== fallback.schemaHash) {
238
+ throw errors.loaderFailed(
239
+ `the release ${sha} was published with another schema than this code's ` +
240
+ `(${snapshot.schemaHash} ≠ ${fallback.schemaHash}): preview it on a deploy of its own code`,
241
+ );
242
+ }
243
+ if (fallback.aliases === undefined) return snapshot;
244
+ return { ...snapshot, aliases: fallback.aliases };
245
+ }
246
+
247
+ /** Reads a revision once; a failed read isn't kept, so the next client tries again. */
248
+ #readRevision(sha: string): Promise<Snapshot> {
249
+ const held = this.#revisions.get(sha);
250
+ if (held !== undefined) return held;
251
+ const site = encodeURIComponent(this.#site);
252
+ const pending = this.#fetchRevision(site, sha, "the revision asked for").then((body) => {
253
+ const snapshot: Snapshot = {
254
+ revision: sha,
255
+ blocks: body.blocks,
256
+ schemaHash: body.schemaHash,
257
+ };
258
+ if (body.previewHosts !== undefined) snapshot.previewHosts = body.previewHosts;
259
+ return snapshot;
260
+ });
261
+ this.#revisions.set(sha, pending);
262
+ pending.catch(() => {
263
+ if (this.#revisions.get(sha) === pending) this.#revisions.delete(sha);
264
+ });
265
+ return pending;
266
+ }
267
+
268
+ async #fetchRevision(site: string, sha: string, expected: string): Promise<Revision> {
269
+ const label = `revision ${sha}`;
270
+ const response = await fetchWithTimeout(
271
+ `${deliveryOrigin()}/sites/${site}/revisions/${sha}.json`,
272
+ );
273
+ if (!response.ok) {
274
+ await response.body?.cancel();
275
+ throw new Error(`${label}: HTTP ${response.status}`);
276
+ }
277
+ const body = await readBoundedJson(response, label, MAX_SNAPSHOT_BYTES);
278
+ if (
279
+ !isPlainObject(body) ||
280
+ body.revision !== sha ||
281
+ typeof body.schemaHash !== "string" ||
282
+ !isPlainObject(body.blocks)
283
+ ) {
284
+ throw new Error(`${label}: unexpected format, or not ${expected}`);
285
+ }
286
+ return {
287
+ blocks: body.blocks,
288
+ schemaHash: body.schemaHash,
289
+ previewHosts: previewHostsOf(body.previewHosts),
290
+ };
291
+ }
292
+
128
293
  async #loadFallback(): Promise<Snapshot> {
129
294
  const fallback = this.#fallback;
130
295
  const snapshot = isSnapshot(fallback) ? fallback : await (fallback as Loader).load();
@@ -136,6 +301,12 @@ class RemoteLoader implements Loader {
136
301
  const response = await fetchWithTimeout(`${deliveryOrigin()}/sites/${site}/latest.json`);
137
302
  if (!response.ok) {
138
303
  await response.body?.cancel();
304
+ // Not published yet: no list, so previews are allowed on every host (PO 2026-10-22).
305
+ // A site this process has read a list for can't be unpublished: a 404 then
306
+ // (a CDN fault, a publish caught mid-write) is a failed read, so it keeps the list.
307
+ if (response.status === 404 && !Array.isArray(this.#hosts?.list)) {
308
+ this.#hosts = { list: "every", at: Date.now() };
309
+ }
139
310
  throw new Error(`latest.json: HTTP ${response.status}`);
140
311
  }
141
312
  const body: unknown = await response.json();
@@ -150,28 +321,24 @@ class RemoteLoader implements Loader {
150
321
  ) {
151
322
  throw new Error("latest.json: unexpected format");
152
323
  }
153
- return body as unknown as Latest;
324
+ const previewHosts = previewHostsOf(body.previewHosts);
325
+ // The current release's metadata, whether or not its revision is swapped in.
326
+ // No `previewHosts` (published before Studio wrote the list): every host, as with no latest.json.
327
+ this.#hosts = { list: previewHosts ?? "every", at: Date.now() };
328
+ return {
329
+ revision: body.revision,
330
+ schemaHash: body.schemaHash,
331
+ publishedAt: body.publishedAt,
332
+ previewHosts,
333
+ };
154
334
  }
155
335
 
156
- async #revision(site: string, latest: Latest): Promise<Record<string, unknown>> {
157
- const label = `revision ${latest.revision}`;
158
- const response = await fetchWithTimeout(
159
- `${deliveryOrigin()}/sites/${site}/revisions/${latest.revision}.json`,
160
- );
161
- if (!response.ok) {
162
- await response.body?.cancel();
163
- throw new Error(`${label}: HTTP ${response.status}`);
164
- }
165
- const body = await readBoundedJson(response, label, MAX_SNAPSHOT_BYTES);
166
- if (
167
- !isPlainObject(body) ||
168
- body.revision !== latest.revision ||
169
- body.schemaHash !== latest.schemaHash ||
170
- !isPlainObject(body.blocks)
171
- ) {
172
- throw new Error(`${label}: unexpected format, or not the revision latest.json names`);
336
+ async #revision(site: string, latest: Latest): Promise<Revision> {
337
+ const body = await this.#fetchRevision(site, latest.revision, "the revision latest.json names");
338
+ if (body.schemaHash !== latest.schemaHash) {
339
+ throw new Error(`revision ${latest.revision}: not the schema latest.json names`);
173
340
  }
174
- return body.blocks;
341
+ return body;
175
342
  }
176
343
  }
177
344
 
@@ -12,7 +12,9 @@
12
12
  * order and stop at the first `true` one (later rules never run, as in v7).
13
13
  *
14
14
  * A `Resolver` belongs to one client, so its memo (results per block function
15
- * and canonical inputs) never outlives a request. Within the request the memo
15
+ * and canonical inputs) never outlives a request, and every block function it
16
+ * calls runs with that client as `currentClient()` (a lazy value called after
17
+ * the resolve returned included). Within the request the memo
16
18
  * hands every occurrence of the same block the same result object, so results
17
19
  * are read-only (see `Client` in ./types): mutating one in place would change
18
20
  * the others, the class of bug behind the v7 layout-cache race.
@@ -21,9 +23,10 @@ import { RESERVED_NAMES } from "./builtins/index.ts";
21
23
  import { isLazyBuiltin } from "./builtins/lazy.ts";
22
24
  import { LEGACY_ALIASES, wrapLegacyVariants } from "./builtins/legacy.ts";
23
25
  import { isMultivariateBuiltin } from "./builtins/multivariate.ts";
26
+ import { runWithClient } from "./current.ts";
24
27
  import { errors, isResolutionError } from "./errors.ts";
25
28
  import { canonicalKey, isPlainObject, type JsonObject, own } from "./json.ts";
26
- import type { BlockFunction, Blocks, Lazy, Snapshot } from "./types.ts";
29
+ import type { BlockFunction, Blocks, Client, Lazy, Snapshot } from "./types.ts";
27
30
 
28
31
  type Path = (string | number)[];
29
32
 
@@ -32,6 +35,8 @@ interface ResolverOptions {
32
35
  blocks: Blocks;
33
36
  /** The built-ins, with this CMS's `secret`. */
34
37
  builtIns: Readonly<Blocks>;
38
+ /** The client this resolver belongs to: `currentClient()` while a block function runs. */
39
+ client?: Client;
35
40
  /** Called once per name a saved block shares with a function. */
36
41
  onCollision?: (name: string) => void;
37
42
  /** Called after each block function runs (telemetry: spans and failures). */
@@ -42,15 +47,17 @@ export class Resolver {
42
47
  readonly #snapshot: Snapshot;
43
48
  readonly #blocks: Blocks;
44
49
  readonly #builtIns: Readonly<Blocks>;
50
+ readonly #client: Client | undefined;
45
51
  readonly #onCollision?: (name: string) => void;
46
52
  readonly #onBlock?: ResolverOptions["onBlock"];
47
53
  readonly #memo = new WeakMap<BlockFunction, Map<string, Promise<unknown>>>();
48
54
  readonly #keys = new WeakMap<object, string | null>();
49
55
 
50
- constructor({ snapshot, blocks, builtIns, onCollision, onBlock }: ResolverOptions) {
56
+ constructor({ snapshot, blocks, builtIns, client, onCollision, onBlock }: ResolverOptions) {
51
57
  this.#snapshot = snapshot;
52
58
  this.#blocks = blocks;
53
59
  this.#builtIns = builtIns;
60
+ this.#client = client;
54
61
  this.#onCollision = onCollision;
55
62
  this.#onBlock = onBlock;
56
63
  }
@@ -248,7 +255,10 @@ export class Resolver {
248
255
  : await this.#resolveFields(inputs, path, chain, true);
249
256
  const start = Date.now();
250
257
  try {
251
- const value = await fn(resolved);
258
+ const client = this.#client;
259
+ const value = await (client === undefined
260
+ ? fn(resolved)
261
+ : runWithClient(client, () => fn(resolved)));
252
262
  this.#onBlock?.(type, start, Date.now());
253
263
  return value;
254
264
  } catch (error) {
@@ -9,9 +9,12 @@
9
9
  * - A missing block, a block of another type, or a section that fails to
10
10
  * resolve gives that section's defaults, still capped. Nothing rejects.
11
11
  * - Telemetry rates are the lower of content's and `telemetry.limits`.
12
- * - Preview hosts: content's entries that fall within code's `preview.hosts`
13
- * (all of them when code sets none); without the field, code's list, or
14
- * every host.
12
+ * - Preview hosts aren't content: Studio writes them into the release
13
+ * metadata (PO 2026-10-22), and `previewHosts` merges them with code's
14
+ * `preview.hosts`. A remote site with no list published (no `latest.json`
15
+ * yet, or one without `previewHosts`): every host. Content with no remote
16
+ * site: code's list, else every host. Metadata that couldn't be read:
17
+ * code's list alone, or none. `["*"]` means every host.
15
18
  */
16
19
  import {
17
20
  analyticsSection,
@@ -19,24 +22,20 @@ import {
19
22
  SETTINGS_TYPE,
20
23
  telemetrySection,
21
24
  } from "./builtins/data.ts";
22
- import {
23
- EVERY_HOST,
24
- formatHostPattern,
25
- type HostPattern,
26
- parseHostPattern,
27
- patternWithin,
28
- } from "./hosts.ts";
25
+ import type { ReleasePreviewHosts } from "./content.ts";
26
+ import { EVERY_HOST, formatHostPattern, type HostPattern, parseHostPattern } from "./hosts.ts";
29
27
  import { isPlainObject } from "./json.ts";
30
28
  import type { Client, CMSConfig, EffectiveSettings, Snapshot } from "./types.ts";
31
29
 
32
30
  /** What code allows: the caps every section's content is held to. */
33
31
  export interface SettingsCaps {
34
- /** Code's `preview.hosts`, parsed; `undefined` when code sets none. */
35
- hosts: readonly HostPattern[] | undefined;
36
32
  limits: { errorSampleRate: number; traceSampleRate: number };
37
33
  }
38
34
 
39
- const SECTIONS = ["preview", "telemetry", "analytics"] as const;
35
+ /** The settings a release's `CMS` block holds: every section but `preview`, which isn't content. */
36
+ export type SavedSettings = Omit<EffectiveSettings, "preview">;
37
+
38
+ const SECTIONS = ["telemetry", "analytics"] as const;
40
39
 
41
40
  /**
42
41
  * Code's `preview.hosts`, parsed. Throws a `TypeError` on anything that isn't
@@ -72,7 +71,7 @@ function parseCodePatterns(
72
71
  }
73
72
 
74
73
  /** The settings with nothing saved: every default, capped. */
75
- export function defaultSettings(caps: SettingsCaps): EffectiveSettings {
74
+ export function defaultSettings(caps: SettingsCaps): SavedSettings {
76
75
  return effectiveSettings({}, caps);
77
76
  }
78
77
 
@@ -85,7 +84,7 @@ export async function readSettings(
85
84
  snapshot: Snapshot | undefined,
86
85
  client: () => Client,
87
86
  caps: SettingsCaps,
88
- ): Promise<EffectiveSettings> {
87
+ ): Promise<SavedSettings> {
89
88
  try {
90
89
  const entry = snapshot?.blocks[SETTINGS_BLOCK];
91
90
  if (!isPlainObject(entry) || entry.__resolveType !== SETTINGS_TYPE) {
@@ -125,10 +124,9 @@ function holdsBlock(value: unknown): boolean {
125
124
  * The settings, deep-frozen: one object per release is handed to every caller,
126
125
  * so a caller that writes to it would change it for every request.
127
126
  */
128
- function effectiveSettings(value: Record<string, unknown>, caps: SettingsCaps): EffectiveSettings {
127
+ function effectiveSettings(value: Record<string, unknown>, caps: SettingsCaps): SavedSettings {
129
128
  const telemetry = telemetrySection(value.telemetry);
130
129
  return deepFreeze({
131
- preview: { hosts: effectiveHosts(value.preview, caps.hosts) },
132
130
  telemetry: {
133
131
  ...telemetry,
134
132
  errorSampleRate: Math.min(telemetry.errorSampleRate, caps.limits.errorSampleRate),
@@ -138,7 +136,7 @@ function effectiveSettings(value: Record<string, unknown>, caps: SettingsCaps):
138
136
  });
139
137
  }
140
138
 
141
- function deepFreeze<T>(value: T): T {
139
+ export function deepFreeze<T>(value: T): T {
142
140
  if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
143
141
  Object.freeze(value);
144
142
  for (const child of Object.values(value)) deepFreeze(child);
@@ -146,17 +144,25 @@ function deepFreeze<T>(value: T): T {
146
144
  return value;
147
145
  }
148
146
 
149
- function effectiveHosts(preview: unknown, code: readonly HostPattern[] | undefined): string[] {
150
- const saved = isPlainObject(preview) && Array.isArray(preview.hosts) ? preview.hosts : undefined;
151
- if (saved === undefined) return code ? unique(code.map(formatHostPattern)) : [EVERY_HOST];
152
- const kept: string[] = [];
153
- for (const raw of saved) {
154
- const pattern = parseHostPattern(raw);
155
- if (pattern === null) continue; // not a pattern: left out
156
- if (code && !code.some((cap) => patternWithin(pattern, cap))) continue;
157
- kept.push(formatHostPattern(pattern));
158
- }
159
- return unique(kept);
147
+ /**
148
+ * The preview hosts in effect, in their normal form, each once:
149
+ * - the release has a list: it (entries that aren't host patterns left out)
150
+ * plus code's `preview.hosts`;
151
+ * - a remote site published no list (`"every"`): every host (`["*"]`);
152
+ * - no remote site (`"local"`): code's `preview.hosts` when set, else every host;
153
+ * - the release metadata couldn't be read (`"unknown"`): code's alone, or
154
+ * none, so a failed read never opens previews.
155
+ */
156
+ export function previewHosts(
157
+ release: ReleasePreviewHosts,
158
+ code: readonly HostPattern[] | undefined,
159
+ ): string[] {
160
+ if (release === "every" || (release === "local" && code === undefined)) return [EVERY_HOST];
161
+ const listed = typeof release === "string" ? [] : release.map((raw) => parseHostPattern(raw));
162
+ const patterns = [...listed, ...(code ?? [])].filter(
163
+ (pattern): pattern is HostPattern => pattern !== null,
164
+ );
165
+ return unique(patterns.map(formatHostPattern));
160
166
  }
161
167
 
162
168
  function unique(values: string[]): string[] {