@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
package/src/v8/cms.ts CHANGED
@@ -12,17 +12,21 @@ import { builtIns } from "./builtins/index.ts";
12
12
  import { secretBlock } from "./builtins/secret.ts";
13
13
  import { CMSClient } from "./client.ts";
14
14
  import { ContentStore, isLoader, isSnapshot } from "./content.ts";
15
- import { draftCookieFor, endsPreview, parseDraftPointer, readDraftPointer } from "./draft.ts";
15
+ import type { Overrides } from "./current.ts";
16
+ import { draftCookieFor, endsPreview, parseClientVersion, readVersion } from "./draft.ts";
16
17
  import { parseDraftHosts } from "./draftChanges.ts";
17
18
  import { allowsHost, type HostPattern, parseHostPattern } from "./hosts.ts";
18
19
  import { clearGlobals, contentIdentity, fnv1a } from "./identity.ts";
19
20
  import { isPlainObject } from "./json.ts";
20
21
  import { remoteLoader, resetRemoteLoaders } from "./remoteLoader.ts";
21
22
  import {
23
+ deepFreeze,
22
24
  defaultSettings,
23
25
  isStatic,
24
26
  parseCodeHosts,
27
+ previewHosts,
25
28
  readSettings,
29
+ type SavedSettings,
26
30
  type SettingsCaps,
27
31
  } from "./settings.ts";
28
32
  import {
@@ -34,11 +38,14 @@ import {
34
38
  import type {
35
39
  Blocks,
36
40
  Client,
41
+ ClientOptions,
37
42
  CMS,
38
43
  CMSConfig,
39
44
  EffectiveSettings,
40
45
  Loader,
46
+ ReleaseCheckOptions,
41
47
  RequestLike,
48
+ RequestVersion,
42
49
  Snapshot,
43
50
  } from "./types.ts";
44
51
  import { forceVariants } from "./variants.ts";
@@ -75,13 +82,15 @@ class CMSInstance {
75
82
  readonly #telemetry: TelemetryPipeline | undefined;
76
83
  readonly #caps: SettingsCaps;
77
84
  /** Settings of a `CMS` block with nothing to run, per release snapshot. */
78
- #staticSettings = new WeakMap<Snapshot, EffectiveSettings>();
85
+ #staticSettings = new WeakMap<Snapshot, SavedSettings>();
86
+ /** Code's `preview.hosts`, parsed: added to the release's own preview hosts, or the only list without a site. */
87
+ readonly #codeHosts: readonly HostPattern[] | undefined;
79
88
  /** The release and time telemetry last read its section. */
80
89
  #telemetryRead: { snapshot: Snapshot; at: number } | undefined;
81
90
  /** One handle per block map, so the same config returns the same object. */
82
91
  readonly #handles = new WeakMap<Blocks, CMS>();
83
92
  /**
84
- * When the next check is due. The first is on the first `forRelease()` or `forDraft()`, not
93
+ * When the next check is due. The first is on the first `client()`, not
85
94
  * at construction: Workers read `Date.now()` as 0 at module scope.
86
95
  */
87
96
  #nextCheck: number | undefined;
@@ -91,10 +100,8 @@ class CMSInstance {
91
100
  this.#interval = interval;
92
101
  this.#store = new ContentStore(contentOf(config), parseDraftHosts(config.preview));
93
102
  this.fingerprint = fingerprintOf(config, interval);
94
- this.#caps = {
95
- hosts: parseCodeHosts(config.preview),
96
- limits: telemetryLimits(config.telemetry),
97
- };
103
+ this.#codeHosts = parseCodeHosts(config.preview);
104
+ this.#caps = { limits: telemetryLimits(config.telemetry) };
98
105
  const destination = resolveDestination(config.telemetry, config.site, config.token);
99
106
  if (destination !== null) {
100
107
  this.#telemetry = new TelemetryPipeline(destination);
@@ -106,17 +113,48 @@ class CMSInstance {
106
113
  this.#builtIns = Object.freeze({ ...builtIns, secret });
107
114
  }
108
115
 
109
- forRelease(blocks: Blocks): Client {
116
+ /**
117
+ * A client for one request: the version it reads (the current release, a
118
+ * published release by its commit SHA, or a draft pointer), the visitor it
119
+ * decides tests for and the date it checks campaigns at (default: now),
120
+ * all passed in, with the tests and campaigns it is given on top.
121
+ */
122
+ client(blocks: Blocks, options: ClientOptions = {}): Client {
110
123
  this.#scheduleUpdate();
124
+ const version = typeof options.version === "string" ? options.version : undefined;
125
+ const date = options.date instanceof Date ? options.date.getTime() : Number.NaN;
126
+ const inputs = {
127
+ version,
128
+ visitor: options.visitor ?? null,
129
+ date: Number.isNaN(date) ? Date.now() : date,
130
+ experiments: overridesOf(options.experiments),
131
+ campaigns: overridesOf(options.campaigns),
132
+ };
133
+ if (version === undefined) return this.#client(blocks, this.#release(blocks), inputs);
134
+ const parsed = parseClientVersion(version);
135
+ // A version that doesn't parse fails on the first read, as an invalid pointer always has.
136
+ const check = options.releaseCheck;
137
+ if (parsed === null)
138
+ return this.#client(blocks, () => this.#store.draft(version, check), inputs);
139
+ if (parsed.kind === "revision") {
140
+ return this.#client(blocks, () => this.#store.revision(parsed.sha), inputs);
141
+ }
142
+ const { variants } = parsed.pointer;
143
+ const load = () => this.#store.draft(version, check);
144
+ if (variants === undefined) return this.#client(blocks, load, inputs);
145
+ return this.#client(blocks, () => load().then((s) => forceVariants(s, variants)), inputs);
146
+ }
147
+
148
+ /** Loads the current release, keeping telemetry on the release's settings. */
149
+ #release(blocks: Blocks): () => Promise<Snapshot> {
111
150
  const telemetry = this.#telemetry;
112
- if (telemetry === undefined) return this.#client(blocks, () => this.#store.release());
113
- return this.#client(blocks, () =>
151
+ if (telemetry === undefined) return () => this.#store.release();
152
+ return () =>
114
153
  this.#store.release().then(async (snapshot) => {
115
154
  telemetry.useRelease(snapshot);
116
155
  await this.#followTelemetrySettings(blocks, telemetry, snapshot);
117
156
  return snapshot;
118
- }),
119
- );
157
+ });
120
158
  }
121
159
 
122
160
  /**
@@ -124,35 +162,39 @@ class CMSInstance {
124
162
  * `CMS` block resolves on each call, so a field with variants is decided
125
163
  * where it's called; one with nothing to run is resolved once per release.
126
164
  */
127
- settings(blocks: Blocks): Promise<EffectiveSettings> {
128
- return this.#settingsOf(blocks, this.#store.current());
165
+ async settings(blocks: Blocks): Promise<EffectiveSettings> {
166
+ const [saved, hosts] = await Promise.all([
167
+ this.#settingsOf(blocks, this.#store.current()),
168
+ this.#store.previewHosts(true),
169
+ ]);
170
+ return deepFreeze({ ...saved, preview: { hosts: previewHosts(hosts, this.#codeHosts) } });
171
+ }
172
+
173
+ async readVersion(
174
+ request: RequestLike,
175
+ options: ReleaseCheckOptions = {},
176
+ ): Promise<RequestVersion | null> {
177
+ const version = readVersion(request);
178
+ if (version === null) return null;
179
+ // The request's release check first: it reads `latest.json`, the preview hosts with it.
180
+ if (typeof options.releaseCheck === "string") {
181
+ await this.#store.waitForCheck(options.releaseCheck);
182
+ }
183
+ return (await this.#previewAllowed(request)) ? version : null;
129
184
  }
130
185
 
131
- async draftPointer(blocks: Blocks, request: RequestLike): Promise<string | null> {
132
- const pointer = readDraftPointer(request);
133
- if (pointer === null) return null;
134
- return (await this.#previewAllowed(blocks, request)) ? pointer : null;
186
+ /** A release check for one draft request (see `ContentStore.checkRelease`); it counts as the background's too. */
187
+ checkRelease(releaseCheck?: string | null): Promise<string> {
188
+ if (this.#store.updatable) this.#nextCheck = this.#due();
189
+ return this.#store.checkRelease(releaseCheck);
135
190
  }
136
191
 
137
- async draftCookie(blocks: Blocks, request: RequestLike): Promise<string | null> {
192
+ async draftCookie(request: RequestLike): Promise<string | null> {
138
193
  const cookie = draftCookieFor(request);
139
194
  if (cookie === null) return null;
140
195
  // Ending a preview is allowed anywhere, so a cookie set before a host was removed still goes.
141
196
  if (endsPreview(request)) return cookie;
142
- return (await this.#previewAllowed(blocks, request)) ? cookie : null;
143
- }
144
-
145
- /**
146
- * The draft, with the variants the pointer forces (even for a `local`
147
- * pointer, which names no draft). A draft client is a production client
148
- * reading a draft pointer, so it schedules the release check like any other.
149
- */
150
- forDraft(blocks: Blocks, pointer: string): Client {
151
- this.#scheduleUpdate();
152
- const load = () => this.#store.draft(pointer);
153
- const variants = parseDraftPointer(pointer)?.variants;
154
- if (variants === undefined) return this.#client(blocks, load);
155
- return this.#client(blocks, () => load().then((snapshot) => forceVariants(snapshot, variants)));
197
+ return (await this.#previewAllowed(request)) ? cookie : null;
156
198
  }
157
199
 
158
200
  update(): Promise<{ updated: boolean }> {
@@ -181,7 +223,7 @@ class CMSInstance {
181
223
  this.#telemetryRead = undefined;
182
224
  }
183
225
 
184
- async #settingsOf(blocks: Blocks, snapshot: Snapshot | undefined): Promise<EffectiveSettings> {
226
+ async #settingsOf(blocks: Blocks, snapshot: Snapshot | undefined): Promise<SavedSettings> {
185
227
  if (snapshot === undefined) return defaultSettings(this.#caps);
186
228
  const cached = this.#staticSettings.get(snapshot);
187
229
  if (cached !== undefined) return cached;
@@ -192,6 +234,7 @@ class CMSInstance {
192
234
  load: () => Promise.resolve(snapshot),
193
235
  blocks,
194
236
  builtIns: this.#builtIns,
237
+ date: Date.now(),
195
238
  onCollision: (name) => this.#warnCollision(name),
196
239
  }),
197
240
  this.#caps,
@@ -205,9 +248,14 @@ class CMSInstance {
205
248
  return settings;
206
249
  }
207
250
 
208
- /** Whether the release's preview hosts allow this request's host. */
209
- async #previewAllowed(blocks: Blocks, request: RequestLike): Promise<boolean> {
210
- const { hosts } = (await this.settings(blocks)).preview;
251
+ /**
252
+ * Whether the current release's preview hosts (the release metadata's,
253
+ * read once if this process hasn't yet) or code's allow this request's host.
254
+ * No list published (or no remote site and no code list): every host; a
255
+ * failed read of the metadata: code's list alone (see `previewHosts`).
256
+ */
257
+ async #previewAllowed(request: RequestLike): Promise<boolean> {
258
+ const hosts = previewHosts(await this.#store.previewHosts(), this.#codeHosts);
211
259
  const patterns = hosts
212
260
  .map((raw) => parseHostPattern(raw))
213
261
  .filter((pattern): pattern is HostPattern => pattern !== null);
@@ -235,11 +283,23 @@ class CMSInstance {
235
283
  if (last?.snapshot !== snapshot) await read;
236
284
  }
237
285
 
238
- #client(blocks: Blocks, load: () => Promise<Snapshot>): Client {
286
+ /** A client with its inputs (each client copies its visitor, so none is shared). */
287
+ #client(
288
+ blocks: Blocks,
289
+ load: () => Promise<Snapshot>,
290
+ inputs: {
291
+ version: string | undefined;
292
+ visitor: ClientOptions["visitor"];
293
+ date: number;
294
+ experiments: Overrides | undefined;
295
+ campaigns: Overrides | undefined;
296
+ },
297
+ ): Client {
239
298
  return new CMSClient({
240
299
  load,
241
300
  blocks,
242
301
  builtIns: this.#builtIns,
302
+ ...inputs,
243
303
  onCollision: (name) => this.#warnCollision(name),
244
304
  telemetry: this.#telemetry?.forClient(),
245
305
  });
@@ -247,7 +307,8 @@ class CMSInstance {
247
307
 
248
308
  /**
249
309
  * Checks a content source with `update()` on first use and then every
250
- * `interval` (± up to 10 s), at an idle moment, never in front of a request.
310
+ * `interval` (± up to 10 s), at an idle moment, never in front of a release
311
+ * request (a draft read waits for a check of its own: `ContentStore.draft`).
251
312
  */
252
313
  #scheduleUpdate(): void {
253
314
  if (!this.#store.updatable) return;
@@ -292,12 +353,23 @@ class CMSHandle implements CMS {
292
353
  return this.#instance;
293
354
  }
294
355
 
356
+ client(options: ClientOptions = {}): Client {
357
+ return this.#instance.client(this.#blocks, options);
358
+ }
359
+
295
360
  forRelease(): Client {
296
- return this.#instance.forRelease(this.#blocks);
361
+ return this.#instance.client(this.#blocks);
362
+ }
363
+
364
+ forDraft(pointer: string, options: ReleaseCheckOptions = {}): Client {
365
+ return this.#instance.client(this.#blocks, {
366
+ version: pointer,
367
+ releaseCheck: options.releaseCheck ?? null,
368
+ });
297
369
  }
298
370
 
299
- forDraft(pointer: string): Client {
300
- return this.#instance.forDraft(this.#blocks, pointer);
371
+ checkRelease(releaseCheck?: string | null): Promise<string> {
372
+ return this.#instance.checkRelease(releaseCheck);
301
373
  }
302
374
 
303
375
  update(): Promise<{ updated: boolean }> {
@@ -308,12 +380,16 @@ class CMSHandle implements CMS {
308
380
  return this.#instance.settings(this.#blocks);
309
381
  }
310
382
 
311
- draftPointer(request: RequestLike): Promise<string | null> {
312
- return this.#instance.draftPointer(this.#blocks, request);
383
+ readVersion(request: RequestLike, options?: ReleaseCheckOptions): Promise<RequestVersion | null> {
384
+ return this.#instance.readVersion(request, options);
385
+ }
386
+
387
+ async draftPointer(request: RequestLike): Promise<string | null> {
388
+ return (await this.#instance.readVersion(request))?.version ?? null;
313
389
  }
314
390
 
315
391
  draftCookie(request: RequestLike): Promise<string | null> {
316
- return this.#instance.draftCookie(this.#blocks, request);
392
+ return this.#instance.draftCookie(request);
317
393
  }
318
394
  }
319
395
 
@@ -388,6 +464,19 @@ export function adoptContent(content: Snapshot): number {
388
464
  return adopted;
389
465
  }
390
466
 
467
+ /**
468
+ * A client's own frozen copy of the tests or campaigns it is given: the
469
+ * entries that are `true` or `false`; `undefined` for none.
470
+ */
471
+ function overridesOf(given: unknown): Overrides | undefined {
472
+ if (typeof given !== "object" || given === null || Array.isArray(given)) return undefined;
473
+ const out = Object.create(null) as Record<string, boolean>;
474
+ for (const [name, on] of Object.entries(given as Record<string, unknown>)) {
475
+ if (typeof on === "boolean") out[name] = on;
476
+ }
477
+ return Object.freeze(out);
478
+ }
479
+
391
480
  /** Clears every stored CMS instance, so a test starts clean. */
392
481
  export function resetForTests(): void {
393
482
  clearGlobals(INSTANCE_PREFIX);
package/src/v8/content.ts CHANGED
@@ -50,6 +50,44 @@ export function peekRelease(source: Snapshot | Loader): Snapshot | undefined {
50
50
  return typeof peek === "function" ? peek.call(source) : undefined;
51
51
  }
52
52
 
53
+ /**
54
+ * An internal hook `remoteLoader` has: a published release by its commit SHA
55
+ * (`sites/<site>/revisions/<sha>.json`), kept in memory once read. Rejects
56
+ * with `LOADER_FAILED`, never falls back to another release.
57
+ */
58
+ export const READ_REVISION: unique symbol = Symbol.for("decocms.blocks.readRevision");
59
+
60
+ /**
61
+ * An internal hook `remoteLoader` has: the current release's preview hosts
62
+ * from the release metadata (`latest.json`), read once when this process
63
+ * hasn't read them yet (see `ReleasePreviewHosts`).
64
+ */
65
+ export const PREVIEW_HOSTS: unique symbol = Symbol.for("decocms.blocks.previewHosts");
66
+
67
+ /**
68
+ * What the current release says about where it may be previewed (PO 2026-10-22):
69
+ * - a list: the hosts Studio wrote (`previewHosts`), enforced;
70
+ * - `"every"`: a remote site with no list published, so every host: no
71
+ * `latest.json` yet (a 404), or one without `previewHosts` (published
72
+ * before Studio wrote the list; its next publish writes one);
73
+ * - `"local"`: content with no remote site (no release metadata at all):
74
+ * `createCMS`'s `preview.hosts` when set, else every host;
75
+ * - `"unknown"`: the metadata couldn't be read (a network error, a 5xx, a
76
+ * malformed `latest.json`). That isn't "missing": previews stay closed.
77
+ */
78
+ export type ReleasePreviewHosts = readonly string[] | "every" | "local" | "unknown";
79
+
80
+ /**
81
+ * A release's `previewHosts` as Studio wrote them: the strings of a list;
82
+ * `undefined` when the field is absent (no list written); an empty list (no
83
+ * host) for a field that isn't a list, so a malformed one never opens previews.
84
+ */
85
+ export function previewHostsOf(value: unknown): string[] | undefined {
86
+ if (value === undefined) return undefined;
87
+ if (!Array.isArray(value)) return [];
88
+ return value.filter((host): host is string => typeof host === "string");
89
+ }
90
+
53
91
  export function isSnapshot(content: unknown): content is Snapshot {
54
92
  return (
55
93
  isPlainObject(content) &&
@@ -57,7 +95,8 @@ export function isSnapshot(content: unknown): content is Snapshot {
57
95
  isPlainObject(content.blocks) &&
58
96
  (content.aliases === undefined || isPlainObject(content.aliases)) &&
59
97
  (content.schemaHash === undefined || typeof content.schemaHash === "string") &&
60
- (content.committedAt === undefined || typeof content.committedAt === "string")
98
+ (content.committedAt === undefined || typeof content.committedAt === "string") &&
99
+ (content.previewHosts === undefined || Array.isArray(content.previewHosts))
61
100
  );
62
101
  }
63
102
 
@@ -65,6 +104,17 @@ export class ContentStore {
65
104
  #source: Snapshot | Loader;
66
105
  #release: Promise<Snapshot> | undefined;
67
106
  #updating: Promise<{ updated: boolean }> | undefined;
107
+ /** The check a draft read waits on when one was already running when it arrived (see `checkRelease`). */
108
+ #queued: Promise<string> | undefined;
109
+ /**
110
+ * Release checks a request can share (`checkRelease`): how many ended (a
111
+ * check's id is handed out only once it ended), and this store's prefix
112
+ * for their ids, so an id from another process (or another CMS) is never
113
+ * taken for one of these. The prefix is made on the first check, never at
114
+ * module scope.
115
+ */
116
+ #checksDone = 0;
117
+ #checkPrefix: string | undefined;
68
118
  readonly #drafts = new BoundedMap<string, CachedDraft>(CACHED_DRAFTS);
69
119
  /** Draft reads in flight, so concurrent renders of one draft share one request. */
70
120
  readonly #draftReads = new Map<string, Promise<CachedDraft>>();
@@ -110,8 +160,16 @@ export class ContentStore {
110
160
  * changes are keyed by the pointer without its `__variant` parameters (every
111
161
  * variant of one draft shares one body) and revalidated on every read: a
112
162
  * `304` reuses the body held, a `200` replaces it.
163
+ *
164
+ * Before layering, a draft read checks the source for a newer release and
165
+ * waits for that check (see `checkRelease`), so a draft always shows over
166
+ * the latest release, even in a process that hasn't picked it up yet. The
167
+ * check runs beside the draft's own revalidation. With `releaseCheck` (the
168
+ * id `checkRelease` resolved with, for this request), it waits for that
169
+ * check instead of making its own; an id this store didn't make is a check
170
+ * of its own.
113
171
  */
114
- draft(pointer: string): Promise<Snapshot> {
172
+ draft(pointer: string, releaseCheck?: string | null): Promise<Snapshot> {
115
173
  const parsed = parseDraftPointer(pointer);
116
174
  if (parsed === null) {
117
175
  return Promise.reject(errors.loaderFailed(`invalid draft pointer "${truncate(pointer)}"`));
@@ -145,7 +203,8 @@ export class ContentStore {
145
203
  const changes = read.catch((error: unknown) => {
146
204
  throw errors.loaderFailed("the draft's changes couldn't be fetched", error);
147
205
  });
148
- return Promise.all([this.release(), changes]).then(([base, entry]) => {
206
+ const release = this.waitForCheck(releaseCheck).then(() => this.release());
207
+ return Promise.all([release, changes]).then(([base, entry]) => {
149
208
  let view = entry.views.get(base);
150
209
  if (view === undefined) {
151
210
  // OPEN: the view is keyed by the body's ETag (the pointer outlives later saves); the version without one.
@@ -156,6 +215,31 @@ export class ContentStore {
156
215
  });
157
216
  }
158
217
 
218
+ /**
219
+ * A published release by its commit SHA: from the source's hosted releases
220
+ * (`remoteLoader`, which `createCMS` builds with `site`), or the content in
221
+ * memory when it is that revision. Anything else is `LOADER_FAILED`, never
222
+ * a silent fallback to the current release.
223
+ */
224
+ revision(sha: string): Promise<Snapshot> {
225
+ const source = this.#source;
226
+ const read = isLoader(source)
227
+ ? (source as { [READ_REVISION]?: (sha: string) => Promise<Snapshot> })[READ_REVISION]
228
+ : undefined;
229
+ if (typeof read === "function") {
230
+ return read.call(source, sha).catch((error: unknown) => {
231
+ if (isResolutionError(error)) throw error;
232
+ throw errors.loaderFailed(`the release ${sha} couldn't be read`, error);
233
+ });
234
+ }
235
+ return this.release().then((snapshot) => {
236
+ if (snapshot.revision === sha) return snapshot;
237
+ throw errors.loaderFailed(
238
+ `the release ${sha} isn't available: published releases are read from hosted releases (createCMS with site)`,
239
+ );
240
+ });
241
+ }
242
+
159
243
  /**
160
244
  * The current release as it is in memory, without loading anything: the
161
245
  * content module, what a built-in loader holds, or the release this store
@@ -165,6 +249,26 @@ export class ContentStore {
165
249
  return peekRelease(this.#source) ?? this.#latest;
166
250
  }
167
251
 
252
+ /**
253
+ * The current release's preview hosts (see `ReleasePreviewHosts`): what the
254
+ * source's release metadata says (`remoteLoader` reads it once if it hasn't
255
+ * yet; a failed read is `"unknown"`), else, for a source with no release
256
+ * metadata (no remote site), the release in memory's own `previewHosts`, or
257
+ * `"local"` without one. `peek` reads memory only, never the network.
258
+ */
259
+ async previewHosts(peek = false): Promise<ReleasePreviewHosts> {
260
+ const source = this.#source;
261
+ const read = isLoader(source)
262
+ ? (source as { [PREVIEW_HOSTS]?: (peek: boolean) => Promise<ReleasePreviewHosts> })[
263
+ PREVIEW_HOSTS
264
+ ]
265
+ : undefined;
266
+ if (typeof read === "function") {
267
+ return read.call(source, peek).catch((): ReleasePreviewHosts => "unknown");
268
+ }
269
+ return previewHostsOf(this.current()?.previewHosts) ?? "local";
270
+ }
271
+
168
272
  /** Asks the source for newer content; never throws, and concurrent calls share one check. */
169
273
  update(): Promise<{ updated: boolean }> {
170
274
  const source = this.#source;
@@ -178,7 +282,7 @@ export class ContentStore {
178
282
  if (updated) {
179
283
  this.#release = undefined;
180
284
  // `#latest` stays: settings keep the release that was serving until
181
- // the next one loads, never the defaults (which may allow every host).
285
+ // the next one loads, never the defaults (which allow no host).
182
286
  // Drafts are fetched again, so a preview follows the release too.
183
287
  this.#drafts.clear();
184
288
  }
@@ -192,6 +296,66 @@ export class ContentStore {
192
296
  return this.#updating;
193
297
  }
194
298
 
299
+ /**
300
+ * The release check a draft request waits on (PO 2026-10-23: a draft always
301
+ * shows over the latest release), resolving with its id once it ends. With
302
+ * no check running, it starts one. With one running, that one started
303
+ * before this request, so it waits on the next one instead, shared by every
304
+ * request that arrives meanwhile: a burst makes at most two checks, and no
305
+ * request relies on a check that started before it. No time-based throttle:
306
+ * the request right after a publish always checks. One request shares one
307
+ * check: the binding passes the id on to the host check and every draft
308
+ * read (`waitForCheck`), so a preview request reads `latest.json` once.
309
+ * Never rejects (`update()` doesn't), and a check that hangs ends with the
310
+ * loader's fetch timeout, leaving the release held. Release reads never
311
+ * come here: they keep the background check.
312
+ *
313
+ * Given the id of a check this store made (one a proxy in front made for
314
+ * the same request, say; an id is handed out once its check ended), it
315
+ * resolves with that id at once; any other id is ignored and a check is
316
+ * made.
317
+ */
318
+ checkRelease(releaseCheck?: string | null): Promise<string> {
319
+ if (!this.updatable) return Promise.resolve(this.#checkId(0));
320
+ if (typeof releaseCheck === "string" && this.#madeCheck(releaseCheck)) {
321
+ return Promise.resolve(releaseCheck);
322
+ }
323
+ const running = this.#updating;
324
+ if (running === undefined) return this.#startCheck();
325
+ this.#queued ??= running.then(() => {
326
+ this.#queued = undefined;
327
+ return this.#startCheck();
328
+ });
329
+ return this.#queued;
330
+ }
331
+
332
+ /**
333
+ * Nothing to wait for when this store made the check `releaseCheck` names
334
+ * (it ended); with no id, or one this store didn't make, makes a check of
335
+ * its own (`checkRelease`). A source that can't change never waits.
336
+ */
337
+ waitForCheck(releaseCheck: string | null | undefined): Promise<void> {
338
+ if (!this.updatable) return Promise.resolve();
339
+ return this.checkRelease(releaseCheck).then(() => undefined);
340
+ }
341
+
342
+ #startCheck(): Promise<string> {
343
+ return this.update().then(() => this.#checkId(++this.#checksDone));
344
+ }
345
+
346
+ #checkId(n: number): string {
347
+ this.#checkPrefix ??= `${globalThis.crypto.randomUUID()}:`;
348
+ return `${this.#checkPrefix}${n}`;
349
+ }
350
+
351
+ /** Whether `id` names a check this store made (and so one that ended). */
352
+ #madeCheck(id: string): boolean {
353
+ const prefix = this.#checkPrefix;
354
+ if (prefix === undefined || !id.startsWith(prefix)) return false;
355
+ const digits = id.slice(prefix.length);
356
+ return /^\d{1,15}$/.test(digits) && Number(digits) <= this.#checksDone;
357
+ }
358
+
195
359
  /**
196
360
  * Swaps the content in place, for a hot reload that hands the same CMS a new
197
361
  * content module. Any new object swaps, even with the same `revision`: an
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `currentClient()`: the client whose resolve is running a block function.
3
+ *
4
+ * The inputs of a request (the visitor, the version) arrive as arguments to
5
+ * `cms.client()`; this only hands that client to the functions it runs, so a
6
+ * rule or a section can resolve other blocks through it (`experiments`,
7
+ * `campaigns`) and read `client.visitor`, `client.version` and `client.date`.
8
+ *
9
+ * The resolver sets the client while it calls a block function, so every
10
+ * runtime has it at the start of the function, before any `await`. Where an
11
+ * `AsyncLocalStorage` exists (the `#async-store` import picks it by
12
+ * condition, so this module imports no Node built-in) it also survives
13
+ * `await`. The slot lives on `globalThis` under a `Symbol.for` key, so two
14
+ * copies of the package share it, like the CMS instances.
15
+ */
16
+ import { createAsyncStore } from "#async-store";
17
+ import type { AsyncStore } from "../async/types.ts";
18
+ import type { Client } from "./types.ts";
19
+
20
+ const SLOT = Symbol.for("decocms.blocks.currentClient");
21
+
22
+ /** What a client was given, test or campaign name → on or off. */
23
+ export type Overrides = Readonly<Record<string, boolean>>;
24
+
25
+ /**
26
+ * The tests a client was given (`cms.client({ experiments })`): read by the
27
+ * built-in `split-traffic`. `Symbol.for`, so a second copy of the package
28
+ * reads it too.
29
+ */
30
+ export const EXPERIMENT_OVERRIDES: unique symbol = Symbol.for("decocms.blocks.experimentOverrides");
31
+
32
+ /**
33
+ * The campaigns a client was given (`cms.client({ campaigns })`): read by the
34
+ * built-in `calendar`. `Symbol.for`, like `EXPERIMENT_OVERRIDES`.
35
+ */
36
+ export const CAMPAIGN_OVERRIDES: unique symbol = Symbol.for("decocms.blocks.campaignOverrides");
37
+
38
+ interface Slot {
39
+ /** Set while a block function runs synchronously. */
40
+ active: Client | undefined;
41
+ /** Carries the client across `await`, where the runtime has one. */
42
+ store: AsyncStore<Client> | undefined;
43
+ }
44
+
45
+ function slot(): Slot {
46
+ const global = globalThis as unknown as Record<symbol, Slot | undefined>;
47
+ let current = global[SLOT];
48
+ if (current === undefined || typeof current !== "object") {
49
+ current = { active: undefined, store: createAsyncStore<Client>() };
50
+ global[SLOT] = current;
51
+ }
52
+ return current;
53
+ }
54
+
55
+ /**
56
+ * The client resolving the block function that calls it. Call it at the
57
+ * start of the function: without `AsyncLocalStorage` (browsers, React
58
+ * Native) it is only there before the function's first `await`. Throws
59
+ * outside a block function.
60
+ */
61
+ export function currentClient(): Client {
62
+ const { active, store } = slot();
63
+ const client = active ?? store?.getStore();
64
+ if (client === undefined) {
65
+ throw new Error(
66
+ "currentClient() was called outside a block function, or after an await where the " +
67
+ "runtime has no AsyncLocalStorage: call it at the start of the function, before any await",
68
+ );
69
+ }
70
+ return client;
71
+ }
72
+
73
+ /** Runs `fn` with `client` as the current client (the resolver calls each block function this way). */
74
+ export function runWithClient<R>(client: Client, fn: () => R): R {
75
+ const current = slot();
76
+ const previous = current.active;
77
+ current.active = client;
78
+ try {
79
+ return current.store === undefined ? fn() : current.store.run(client, fn);
80
+ } finally {
81
+ current.active = previous;
82
+ }
83
+ }
84
+
85
+ /** The tests a client was given, by name; `undefined` when none. */
86
+ export function experimentOverrides(client: Client): Overrides | undefined {
87
+ return overridesAt(client, EXPERIMENT_OVERRIDES);
88
+ }
89
+
90
+ /** The campaigns a client was given, by name; `undefined` when none. */
91
+ export function campaignOverrides(client: Client): Overrides | undefined {
92
+ return overridesAt(client, CAMPAIGN_OVERRIDES);
93
+ }
94
+
95
+ function overridesAt(client: Client, key: symbol): Overrides | undefined {
96
+ const value = (client as unknown as Record<symbol, unknown>)[key];
97
+ return typeof value === "object" && value !== null ? (value as Overrides) : undefined;
98
+ }