@decocms/blocks 8.1.0-next.4 → 8.1.0-next.5

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 (96) hide show
  1. package/dist/protocol/client.d.ts +1 -1
  2. package/dist/protocol/conformance/cases/reads.d.ts.map +1 -1
  3. package/dist/protocol/conformance/cases/reads.js +22 -6
  4. package/dist/protocol/conformance/cases/reads.js.map +1 -1
  5. package/dist/protocol/conformance/cases/writes.d.ts.map +1 -1
  6. package/dist/protocol/conformance/cases/writes.js +1 -0
  7. package/dist/protocol/conformance/cases/writes.js.map +1 -1
  8. package/dist/protocol/conformance/contentHashFixtures.d.ts +0 -29
  9. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  10. package/dist/protocol/conformance/contentHashFixtures.js +0 -30
  11. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  12. package/dist/protocol/conformance/context.d.ts +3 -3
  13. package/dist/protocol/conformance/context.d.ts.map +1 -1
  14. package/dist/protocol/conformance/index.d.ts +1 -1
  15. package/dist/protocol/conformance/index.d.ts.map +1 -1
  16. package/dist/protocol/conformance/index.js +2 -2
  17. package/dist/protocol/conformance/index.js.map +1 -1
  18. package/dist/protocol/index.d.ts +3 -5
  19. package/dist/protocol/index.d.ts.map +1 -1
  20. package/dist/protocol/index.js +3 -5
  21. package/dist/protocol/index.js.map +1 -1
  22. package/dist/protocol/server/methods/read.d.ts.map +1 -1
  23. package/dist/protocol/server/methods/read.js +5 -2
  24. package/dist/protocol/server/methods/read.js.map +1 -1
  25. package/dist/protocol/types.d.ts +23 -0
  26. package/dist/protocol/types.d.ts.map +1 -1
  27. package/dist/protocol/types.js +10 -0
  28. package/dist/protocol/types.js.map +1 -1
  29. package/dist/v8/boundedJson.d.ts +11 -0
  30. package/dist/v8/boundedJson.d.ts.map +1 -0
  31. package/dist/v8/boundedJson.js +44 -0
  32. package/dist/v8/boundedJson.js.map +1 -0
  33. package/dist/v8/canonical.d.ts +0 -28
  34. package/dist/v8/canonical.d.ts.map +1 -1
  35. package/dist/v8/canonical.js +0 -19
  36. package/dist/v8/canonical.js.map +1 -1
  37. package/dist/v8/cli/check/index.d.ts +5 -0
  38. package/dist/v8/cli/check/index.d.ts.map +1 -1
  39. package/dist/v8/cli/check/index.js +21 -1
  40. package/dist/v8/cli/check/index.js.map +1 -1
  41. package/dist/v8/cli/run.js +1 -1
  42. package/dist/v8/cli/schema/generate.d.ts +3 -1
  43. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  44. package/dist/v8/cli/schema/generate.js +2 -1
  45. package/dist/v8/cli/schema/generate.js.map +1 -1
  46. package/dist/v8/cli/serve/server.d.ts +1 -1
  47. package/dist/v8/cli/serve/server.d.ts.map +1 -1
  48. package/dist/v8/cli/serve/server.js +63 -23
  49. package/dist/v8/cli/serve/server.js.map +1 -1
  50. package/dist/v8/cms.d.ts.map +1 -1
  51. package/dist/v8/cms.js +12 -7
  52. package/dist/v8/cms.js.map +1 -1
  53. package/dist/v8/content.d.ts +8 -6
  54. package/dist/v8/content.d.ts.map +1 -1
  55. package/dist/v8/content.js +50 -40
  56. package/dist/v8/content.js.map +1 -1
  57. package/dist/v8/draft.d.ts.map +1 -1
  58. package/dist/v8/draft.js +22 -0
  59. package/dist/v8/draft.js.map +1 -1
  60. package/dist/v8/draftChanges.d.ts +26 -0
  61. package/dist/v8/draftChanges.d.ts.map +1 -0
  62. package/dist/v8/draftChanges.js +102 -0
  63. package/dist/v8/draftChanges.js.map +1 -0
  64. package/dist/v8/remoteLoader.d.ts +1 -1
  65. package/dist/v8/remoteLoader.d.ts.map +1 -1
  66. package/dist/v8/remoteLoader.js +19 -256
  67. package/dist/v8/remoteLoader.js.map +1 -1
  68. package/dist/v8/settings.d.ts +7 -0
  69. package/dist/v8/settings.d.ts.map +1 -1
  70. package/dist/v8/settings.js +19 -6
  71. package/dist/v8/settings.js.map +1 -1
  72. package/dist/v8/types.d.ts +22 -11
  73. package/dist/v8/types.d.ts.map +1 -1
  74. package/package.json +1 -1
  75. package/src/protocol/client.ts +1 -1
  76. package/src/protocol/conformance/cases/reads.ts +24 -6
  77. package/src/protocol/conformance/cases/writes.ts +1 -0
  78. package/src/protocol/conformance/contentHashFixtures.ts +0 -57
  79. package/src/protocol/conformance/context.ts +3 -3
  80. package/src/protocol/conformance/index.ts +2 -7
  81. package/src/protocol/index.ts +2 -8
  82. package/src/protocol/server/methods/read.ts +5 -2
  83. package/src/protocol/types.ts +21 -1
  84. package/src/v8/boundedJson.ts +47 -0
  85. package/src/v8/canonical.ts +0 -36
  86. package/src/v8/cli/check/index.ts +25 -1
  87. package/src/v8/cli/run.ts +1 -1
  88. package/src/v8/cli/schema/generate.ts +4 -1
  89. package/src/v8/cli/serve/server.ts +65 -29
  90. package/src/v8/cms.ts +12 -8
  91. package/src/v8/content.ts +57 -43
  92. package/src/v8/draft.ts +18 -0
  93. package/src/v8/draftChanges.ts +117 -0
  94. package/src/v8/remoteLoader.ts +23 -289
  95. package/src/v8/settings.ts +27 -6
  96. package/src/v8/types.ts +25 -12
@@ -1,7 +1,8 @@
1
1
  /**
2
- * `remoteLoader`: hosted releases and drafts from the Deco API, over a
3
- * fallback (the content module, or any loader). See
4
- * /next/hosted-releases-internals and /next/hosted-publishing.
2
+ * `remoteLoader`: hosted releases from the Deco API, over a fallback (the
3
+ * content module, or any loader). See /next/hosted-releases-internals and
4
+ * /next/hosted-publishing. Drafts aren't a loader's job: the CMS layers a
5
+ * draft's changes over what `load()` returns (see ./draftChanges.ts).
5
6
  *
6
7
  * - `load()` never touches the network: it returns the newest release this
7
8
  * process fetched, or the fallback's content until one is fetched.
@@ -11,55 +12,29 @@
11
12
  * ignored; a revision equal to the fallback's is served from the fallback
12
13
  * without a download; anything else is fetched, verified against its
13
14
  * content hash and swapped in whole. Any error keeps memory as it was.
14
- * - `load(pointer)` loads a draft overlay (see /next/content-delivery#exact-draft-previews)
15
- * and waits for it: it captures the production snapshot `load()` would
16
- * return right now, fetches the overlay manifest the pointer's version names
17
- * and only the changed-block assets not already cached, and layers their
18
- * replacements and tombstones over the captured snapshot. It never fetches a
19
- * production revision to align. An authorized manifest is cached only as long
20
- * as its response's `max-age` (the grant's remaining life), so an expired
21
- * grant stops working on a warm server too. Only pointers into this site's drafts on the
22
- * delivery host are fetched; anything else is refused. Any failure rejects:
23
- * a draft never falls back to published content.
24
15
  * - In development (`NODE_ENV=development`), releases stay on the fallback so
25
- * local files win; drafts still load.
26
- * - A release, or any one draft asset, larger than `MAX_SNAPSHOT_BYTES` is
27
- * refused while it downloads, before it's buffered whole (a Worker isolate
28
- * has 128 MB); a draft whose manifest and changed blocks together exceed it
29
- * is refused as each asset is counted.
30
- * - Without `site` or `token` it's a plain loader over the fallback: no
31
- * releases, no drafts beyond what the fallback serves.
16
+ * local files win.
17
+ * - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
18
+ * before it's buffered whole (a Worker isolate has 128 MB).
19
+ * - Without `site` or `token` it's a plain loader over the fallback.
32
20
  *
33
21
  * Instances are process-wide singletons, like `createCMS`'s.
34
22
  */
35
- import {
36
- computeBlockHash,
37
- computeContentRevision,
38
- computeOverlayVersion,
39
- DRAFT_OVERLAY_FORMAT,
40
- type DraftOverlay,
41
- } from "./canonical.ts";
42
- import { BoundedMap, isSnapshot, PEEK_RELEASE, peekRelease } from "./content.ts";
43
- import { parseDraftPointer } from "./draft.ts";
23
+ import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
24
+ import { computeContentRevision } from "./canonical.ts";
25
+ import { isSnapshot, PEEK_RELEASE, peekRelease } from "./content.ts";
44
26
  import { clearGlobals, contentIdentity, fnv1a } from "./identity.ts";
45
27
  import { isPlainObject } from "./json.ts";
46
28
  import type { Loader, Snapshot } from "./types.ts";
47
29
 
48
- /** The hosted delivery origin: channel manifests, release assets and drafts. */
30
+ /** The hosted delivery origin: channel manifests and release assets. */
49
31
  const HOSTED_DELIVERY_ORIGIN = "https://delivery.decocms.com";
50
32
 
51
33
  const INSTANCE_PREFIX = "decocms.blocks.remote:";
52
34
  const MANIFEST_FORMAT = 1;
53
35
  const FETCH_TIMEOUT_MS = 10_000;
54
- /** The largest release, or draft (manifest plus changed blocks), accepted, in bytes of JSON. */
36
+ /** The largest release accepted, in bytes of JSON. */
55
37
  const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
56
- /** Draft caches, per site: authorized overlay manifests, and changed-block bytes. */
57
- const CACHED_OVERLAYS = 16;
58
- const CACHED_BLOCK_BYTES = 16 * 1024 * 1024;
59
- /** Changed-block downloads in flight at once, per draft. */
60
- const BLOCK_FETCH_CONCURRENCY = 8;
61
- /** Overlay versions and block hashes: SHA-256, lowercase hex. */
62
- const HASH_RE = /^[0-9a-f]{64}$/;
63
38
 
64
39
  interface RemoteLoaderOptions {
65
40
  site?: string;
@@ -74,17 +49,6 @@ interface Manifest {
74
49
  snapshot: string;
75
50
  }
76
51
 
77
- /** A downloaded, verified JSON asset and its size in bytes. */
78
- interface Asset<T> {
79
- value: T;
80
- bytes: number;
81
- }
82
-
83
- /** An authorized overlay manifest, usable until its grant's `max-age` runs out. */
84
- interface AuthorizedOverlay extends Asset<DraftOverlay> {
85
- expiresAt: number;
86
- }
87
-
88
52
  class RemoteLoader implements Loader {
89
53
  readonly #site: string;
90
54
  readonly #token: string;
@@ -96,11 +60,6 @@ class RemoteLoader implements Loader {
96
60
  #fallbackSnapshot: Snapshot | undefined;
97
61
  #current: Snapshot | undefined;
98
62
  #generation = -1;
99
- /** Authorized manifests, by overlay version and grant: a version alone unlocks nothing. */
100
- readonly #overlays = new BoundedMap<string, Promise<AuthorizedOverlay>>(CACHED_OVERLAYS);
101
- /** Verified changed blocks, by block hash, bounded by their bytes. */
102
- readonly #blocks = new BoundedMap<string, Asset<unknown>>(CACHED_BLOCK_BYTES, (b) => b.bytes);
103
- readonly #pendingBlocks = new Map<string, Promise<Asset<unknown>>>();
104
63
 
105
64
  constructor(
106
65
  fallback: Snapshot | Loader,
@@ -125,8 +84,7 @@ class RemoteLoader implements Loader {
125
84
  return this.#current ?? peekRelease(this.#fallback) ?? this.#fallbackSnapshot;
126
85
  }
127
86
 
128
- load(pointer?: string | null): Promise<Snapshot> {
129
- if (pointer) return this.#draft(pointer);
87
+ load(): Promise<Snapshot> {
130
88
  if (this.#current !== undefined) return Promise.resolve(this.#current);
131
89
  return this.#loadFallback();
132
90
  }
@@ -202,9 +160,11 @@ class RemoteLoader implements Loader {
202
160
  this.#auth(),
203
161
  );
204
162
  if (!response.ok) throw new Error(`release ${manifest.revision}: HTTP ${response.status}`);
205
- const [snapshot] = await readBoundedJson(response, `release ${manifest.revision}`, {
206
- remaining: MAX_SNAPSHOT_BYTES,
207
- });
163
+ const snapshot = await readBoundedJson(
164
+ response,
165
+ `release ${manifest.revision}`,
166
+ MAX_SNAPSHOT_BYTES,
167
+ );
208
168
  if (
209
169
  !isSnapshot(snapshot) ||
210
170
  snapshot.revision !== manifest.revision ||
@@ -215,120 +175,6 @@ class RemoteLoader implements Loader {
215
175
  return snapshot;
216
176
  }
217
177
 
218
- async #draft(raw: string): Promise<Snapshot> {
219
- const pointer = parseDraftPointer(raw);
220
- if (pointer === null) throw new Error("invalid draft pointer");
221
- if (pointer.host !== new URL(HOSTED_DELIVERY_ORIGIN).host) {
222
- throw new Error(`draft pointer names an unexpected host "${pointer.host}"`);
223
- }
224
- const site = `/sites/${encodeURIComponent(this.#site)}`;
225
- const query = pointer.path.indexOf("?");
226
- const pathname = query === -1 ? pointer.path : pointer.path.slice(0, query);
227
- if (pathname !== `${site}/drafts`) throw new Error("draft pointer names another site's drafts");
228
- if (!HASH_RE.test(pointer.version)) throw new Error("draft pointer names no overlay version");
229
- // The grant (the pointer's query) goes, opaque, on every draft asset read.
230
- const grant = query === -1 ? "" : pointer.path.slice(query);
231
-
232
- // Capture production once, before any network: this draft is layered over it.
233
- const base = this.#current ?? (await this.#loadFallback());
234
- const budget: Budget = { remaining: MAX_SNAPSHOT_BYTES };
235
- const manifest = charge(
236
- budget,
237
- await this.#authorizedOverlay(
238
- `${site}/drafts/${pointer.version}.json${grant}`,
239
- pointer.version,
240
- ),
241
- );
242
- const hashes = [...new Set(Object.values(manifest.set))];
243
- const values = new Map<string, unknown>();
244
- let next = 0;
245
- const worker = async () => {
246
- while (next < hashes.length) {
247
- const hash = hashes[next++]!;
248
- values.set(
249
- hash,
250
- await this.#block(`${site}/draft-blocks/${hash}.json${grant}`, hash, budget),
251
- );
252
- }
253
- };
254
- const workers = Math.min(BLOCK_FETCH_CONCURRENCY, hashes.length);
255
- await Promise.all(Array.from({ length: workers }, worker));
256
- return composeOverlay(base, manifest, values, pointer.version);
257
- }
258
-
259
- /**
260
- * The manifest a pointer's grant authorizes: cached by version and grant
261
- * until the response's `max-age` runs out (none, or 0, isn't cached), so an
262
- * expired grant is asked about again. Concurrent callers share a download.
263
- */
264
- async #authorizedOverlay(path: string, version: string): Promise<AuthorizedOverlay> {
265
- const asked = Date.now();
266
- const cached = this.#overlays.get(path);
267
- if (cached !== undefined) {
268
- const overlay = await cached;
269
- if (overlay.expiresAt >= asked) return overlay;
270
- if (this.#overlays.get(path) === cached) this.#overlays.delete(path);
271
- }
272
- const pending = this.#overlay(path, version);
273
- this.#overlays.set(path, pending);
274
- const forget = () => {
275
- if (this.#overlays.get(path) === pending) this.#overlays.delete(path);
276
- };
277
- pending.then((overlay) => {
278
- if (overlay.expiresAt <= Date.now()) forget();
279
- }, forget);
280
- return pending;
281
- }
282
-
283
- async #overlay(path: string, version: string): Promise<AuthorizedOverlay> {
284
- const response = await fetchWithTimeout(`${HOSTED_DELIVERY_ORIGIN}${path}`, this.#auth());
285
- if (!response.ok) throw new Error(`draft overlay ${version}: HTTP ${response.status}`);
286
- const maxAge = cacheLifetimeMs(response.headers.get("cache-control"));
287
- const [body, bytes] = await readBoundedJson(response, `draft overlay ${version}`, {
288
- remaining: MAX_SNAPSHOT_BYTES,
289
- });
290
- const overlay = parseOverlay(body);
291
- if ((await computeOverlayVersion(overlay)) !== version) {
292
- throw new Error(`draft overlay ${version}: content doesn't match its version`);
293
- }
294
- return { value: overlay, bytes, expiresAt: Date.now() + maxAge };
295
- }
296
-
297
- /**
298
- * A changed block, charged to this draft's budget: from the cache, or
299
- * downloaded once and verified against its hash. Concurrent drafts share
300
- * one download, which is bounded on its own and then charged to each of
301
- * them, so one draft's budget never fails another. Only hashes an
302
- * authorized manifest lists get here.
303
- */
304
- async #block(path: string, hash: string, budget: Budget): Promise<unknown> {
305
- const cached = this.#blocks.get(hash);
306
- if (cached !== undefined) return charge(budget, cached);
307
- let pending = this.#pendingBlocks.get(hash);
308
- if (pending === undefined) {
309
- const download = (async () => {
310
- const response = await fetchWithTimeout(`${HOSTED_DELIVERY_ORIGIN}${path}`, this.#auth());
311
- if (!response.ok) throw new Error(`draft block ${hash}: HTTP ${response.status}`);
312
- const [value, bytes] = await readBoundedJson(response, `draft block ${hash}`, {
313
- remaining: MAX_SNAPSHOT_BYTES,
314
- });
315
- if ((await computeBlockHash(value)) !== hash) {
316
- throw new Error(`draft block ${hash}: content doesn't match its hash`);
317
- }
318
- const block = { value, bytes };
319
- this.#blocks.set(hash, block);
320
- return block;
321
- })();
322
- pending = download;
323
- this.#pendingBlocks.set(hash, download);
324
- void download.then(
325
- () => this.#pendingBlocks.delete(hash),
326
- () => this.#pendingBlocks.delete(hash),
327
- );
328
- }
329
- return charge(budget, await pending);
330
- }
331
-
332
178
  #auth(): Record<string, string> {
333
179
  return { authorization: `Bearer ${this.#token}` };
334
180
  }
@@ -350,14 +196,14 @@ class LocalLoader implements Loader {
350
196
  return peekRelease(this.#fallback);
351
197
  }
352
198
 
353
- load(pointer?: string | null): Promise<Snapshot> {
199
+ load(): Promise<Snapshot> {
354
200
  const fallback = this.#fallback;
355
- return isSnapshot(fallback) ? Promise.resolve(fallback) : fallback.load(pointer);
201
+ return isSnapshot(fallback) ? Promise.resolve(fallback) : fallback.load();
356
202
  }
357
203
  }
358
204
 
359
205
  /**
360
- * Hosted releases and drafts over a fallback. `createCMS` builds it for you
206
+ * Hosted releases over a fallback. `createCMS` builds it for you
361
207
  * when `site` and `token` are set. With either unset (a dev or test
362
208
  * environment without the variables), it's a loader over the fallback alone.
363
209
  */
@@ -391,120 +237,8 @@ export function resetRemoteLoaders(): void {
391
237
  clearGlobals(INSTANCE_PREFIX);
392
238
  }
393
239
 
394
- /** What a download may still read, in bytes; shared by every asset of one draft. */
395
- interface Budget {
396
- remaining: number;
397
- }
398
-
399
- /** Charges an asset's bytes to a draft's budget, and returns its value. */
400
- function charge<T>(budget: Budget, asset: Asset<T>): T {
401
- budget.remaining -= asset.bytes;
402
- if (budget.remaining < 0) throw new Error(`draft: larger than ${MAX_SNAPSHOT_BYTES} bytes`);
403
- return asset.value;
404
- }
405
-
406
- /** A response's private cache lifetime in ms: its `max-age`, or 0 without one or with `no-store`. */
407
- function cacheLifetimeMs(header: string | null): number {
408
- if (header === null || /(?:^|,)\s*no-store\b/i.test(header)) return 0;
409
- const seconds = /(?:^|,)\s*max-age=(\d+)/i.exec(header)?.[1];
410
- return seconds === undefined ? 0 : Number(seconds) * 1000;
411
- }
412
-
413
- /**
414
- * Parses a JSON body and returns it with its size, refusing it as soon as it
415
- * would exceed the budget (charged as bytes arrive, so parallel reads share it).
416
- */
417
- async function readBoundedJson(
418
- response: Response,
419
- label: string,
420
- budget: Budget,
421
- ): Promise<[unknown, number]> {
422
- const tooLarge = () => new Error(`${label}: larger than ${MAX_SNAPSHOT_BYTES} bytes`);
423
- if (Number(response.headers.get("content-length")) > budget.remaining) {
424
- await response.body?.cancel();
425
- throw tooLarge();
426
- }
427
- if (response.body === null) {
428
- const text = await response.text();
429
- budget.remaining -= text.length;
430
- if (budget.remaining < 0) throw tooLarge();
431
- return [JSON.parse(text), text.length];
432
- }
433
- const reader = response.body.getReader();
434
- const decoder = new TextDecoder();
435
- const parts: string[] = [];
436
- let size = 0;
437
- for (;;) {
438
- const { done, value } = await reader.read();
439
- if (done) break;
440
- size += value.byteLength;
441
- budget.remaining -= value.byteLength;
442
- if (budget.remaining < 0) {
443
- await reader.cancel();
444
- throw tooLarge();
445
- }
446
- parts.push(decoder.decode(value, { stream: true }));
447
- }
448
- parts.push(decoder.decode());
449
- return [JSON.parse(parts.join("")), size];
450
- }
451
-
452
- /** Validates a draft overlay manifest; throws on an unknown format or any unexpected shape. */
453
- function parseOverlay(body: unknown): DraftOverlay {
454
- const invalid = (why: string) => new Error(`draft overlay: ${why}`);
455
- if (!isPlainObject(body) || body.format !== DRAFT_OVERLAY_FORMAT) {
456
- throw invalid("unknown format");
457
- }
458
- if (Object.keys(body).some((key) => key !== "format" && key !== "set" && key !== "delete")) {
459
- throw invalid("unexpected field");
460
- }
461
- const { set, delete: deleted } = body;
462
- if (!isPlainObject(set)) throw invalid("set must be an object");
463
- for (const hash of Object.values(set)) {
464
- if (typeof hash !== "string" || !HASH_RE.test(hash)) throw invalid("set names a bad hash");
465
- }
466
- if (!Array.isArray(deleted) || deleted.some((name) => typeof name !== "string")) {
467
- throw invalid("delete must be a list of names");
468
- }
469
- if (new Set(deleted).size !== deleted.length) throw invalid("delete repeats a name");
470
- if (deleted.some((name) => Object.hasOwn(set, name))) throw invalid("set and delete overlap");
471
- return body as unknown as DraftOverlay;
472
- }
473
-
474
- /**
475
- * The draft as a snapshot: the captured production entries, with the
476
- * overlay's replacements and without its tombstones. A shallow copy: every
477
- * unchanged entry is production's own object, and production is never
478
- * mutated. Its revision is an opaque identity of the pair, not a content hash.
479
- */
480
- function composeOverlay(
481
- base: Snapshot,
482
- overlay: DraftOverlay,
483
- values: Map<string, unknown>,
484
- version: string,
485
- ): Snapshot {
486
- const blocks: Record<string, unknown> = { ...base.blocks };
487
- for (const name of overlay.delete) delete blocks[name];
488
- for (const [name, hash] of Object.entries(overlay.set)) {
489
- // defineProperty, so an entry named "__proto__" stays an entry.
490
- Object.defineProperty(blocks, name, {
491
- value: values.get(hash),
492
- enumerable: true,
493
- writable: true,
494
- configurable: true,
495
- });
496
- }
497
- const view: Snapshot = { revision: `${base.revision}~${version}`, blocks };
498
- if (base.aliases !== undefined) view.aliases = base.aliases;
499
- return view;
500
- }
501
-
502
240
  function fetchWithTimeout(url: string, headers: Record<string, string>): Promise<Response> {
503
- const signal =
504
- typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
505
- ? AbortSignal.timeout(FETCH_TIMEOUT_MS)
506
- : undefined;
507
- return fetch(url, { headers, signal });
241
+ return fetch(url, { headers, signal: timeoutSignal(FETCH_TIMEOUT_MS) });
508
242
  }
509
243
 
510
244
  function isDevelopment(): boolean {
@@ -43,20 +43,41 @@ const SECTIONS = ["preview", "telemetry", "analytics"] as const;
43
43
  * a list of host patterns: that's a bug in the app, not in content.
44
44
  */
45
45
  export function parseCodeHosts(preview: CMSConfig["preview"]): HostPattern[] | undefined {
46
+ return parseCodePatterns(preview, "hosts");
47
+ }
48
+
49
+ /** The hosts a draft pointer may name when code sets no `preview.sources`. */
50
+ export const DEFAULT_SOURCES: readonly string[] = ["studio.decocms.com"];
51
+
52
+ /**
53
+ * Code's `preview.sources`, parsed, or the default (`studio.decocms.com`).
54
+ * Throws a `TypeError` like {@link parseCodeHosts}.
55
+ */
56
+ export function parseCodeSources(preview: CMSConfig["preview"]): HostPattern[] {
57
+ return (
58
+ parseCodePatterns(preview, "sources") ??
59
+ DEFAULT_SOURCES.map((raw) => parseHostPattern(raw) as HostPattern)
60
+ );
61
+ }
62
+
63
+ function parseCodePatterns(
64
+ preview: CMSConfig["preview"],
65
+ field: "hosts" | "sources",
66
+ ): HostPattern[] | undefined {
46
67
  if (preview === undefined || preview === null) return undefined;
47
68
  if (typeof preview !== "object") {
48
69
  throw new TypeError("createCMS: `preview` must be an object, such as { hosts: [...] }");
49
70
  }
50
- const { hosts } = preview;
51
- if (hosts === undefined) return undefined;
52
- if (!Array.isArray(hosts)) {
53
- throw new TypeError("createCMS: `preview.hosts` must be a list of host patterns");
71
+ const list = preview[field];
72
+ if (list === undefined) return undefined;
73
+ if (!Array.isArray(list)) {
74
+ throw new TypeError(`createCMS: \`preview.${field}\` must be a list of host patterns`);
54
75
  }
55
- return hosts.map((raw) => {
76
+ return list.map((raw) => {
56
77
  const pattern = parseHostPattern(raw);
57
78
  if (pattern === null) {
58
79
  throw new TypeError(
59
- `createCMS: ${JSON.stringify(raw)} in preview.hosts isn't a host pattern ` +
80
+ `createCMS: ${JSON.stringify(raw)} in preview.${field} isn't a host pattern ` +
60
81
  "(see /next/api-reference#host-patterns)",
61
82
  );
62
83
  }
package/src/v8/types.ts CHANGED
@@ -37,19 +37,22 @@ export type Snapshot = {
37
37
  */
38
38
  export type ContentModule = Snapshot & { root?: string };
39
39
 
40
- /** A source of content. `load()` is the release; `load(pointer)` is a draft. */
40
+ /**
41
+ * A source of content: `load()` returns it. Drafts aren't a loader's job:
42
+ * `forDraft` layers a draft's changes over what `load()` returned.
43
+ */
41
44
  export interface Loader {
42
- load(pointer?: string | null): Promise<Snapshot>;
45
+ load(): Promise<Snapshot>;
43
46
  update?(): Promise<{ updated: boolean }>;
44
47
  }
45
48
 
46
49
  /** The parts of a draft pointer, `<host[:port]><path[?query]>@<version>`. */
47
50
  export interface DraftPointer {
48
- /** `host[:port]` of the content source that holds the draft. */
51
+ /** `host[:port]` of the Studio API that serves the draft's changes. */
49
52
  host: string;
50
53
  /** Starts with `/`; opaque to the app. Never carries the `__variant` parameters. */
51
54
  path: string;
52
- /** Opaque and immutable: the branch head or ETag. */
55
+ /** Opaque: the commit of the editor's last save. `"local"` names no draft (`deco serve`). */
53
56
  version: string;
54
57
  /** The variants this preview forces (the query's `__variant` parameters); absent when none. */
55
58
  variants?: ForcedVariant[];
@@ -225,16 +228,23 @@ export interface CMSConfig {
225
228
  interval?: number;
226
229
  /** Where telemetry goes; see /next/telemetry. */
227
230
  telemetry?: false | TelemetryConfig;
228
- /**
229
- * The most content may allow previews on, in the host pattern format
230
- * (/next/api-reference#host-patterns). Without it, content may allow any host.
231
- */
232
- preview?: { hosts?: string[] };
231
+ preview?: {
232
+ /**
233
+ * The most content may allow previews on, in the host pattern format
234
+ * (/next/api-reference#host-patterns). Without it, content may allow any host.
235
+ */
236
+ hosts?: string[];
237
+ /**
238
+ * The hosts a draft pointer may name, in the host pattern format; code
239
+ * only, never content. Default `["studio.decocms.com"]`.
240
+ */
241
+ sources?: string[];
242
+ };
233
243
  /** The private key that decrypts `secret` blocks. */
234
244
  secrets?: { key?: string };
235
- /** Your site's ID, for hosted releases and drafts. */
245
+ /** Your site's ID, for hosted releases. Drafts don't need it. */
236
246
  site?: string;
237
- /** Your site token (secret), for hosted releases and drafts. */
247
+ /** Your site token (secret), for hosted releases. Drafts don't need it. */
238
248
  token?: string;
239
249
  }
240
250
 
@@ -273,7 +283,10 @@ export interface Client {
273
283
  export interface CMS {
274
284
  /** A client reading the current release. */
275
285
  forRelease(): Client;
276
- /** A client reading the draft a pointer names. */
286
+ /**
287
+ * A client reading the draft a pointer names: its changes, fetched from a
288
+ * host in `preview.sources`, over this server's production content.
289
+ */
277
290
  forDraft(pointer: string): Client;
278
291
  /** A client pinned to a revision this CMS has served; an unknown revision behaves like the release. */
279
292
  forRevision(revision: string): Client;