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

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 (178) hide show
  1. package/dist/protocol/client.d.ts +1 -3
  2. package/dist/protocol/client.d.ts.map +1 -1
  3. package/dist/protocol/client.js +0 -2
  4. package/dist/protocol/client.js.map +1 -1
  5. package/dist/protocol/conformance/cases/guards.d.ts.map +1 -1
  6. package/dist/protocol/conformance/cases/guards.js +10 -173
  7. package/dist/protocol/conformance/cases/guards.js.map +1 -1
  8. package/dist/protocol/conformance/cases/reads.d.ts.map +1 -1
  9. package/dist/protocol/conformance/cases/reads.js +24 -53
  10. package/dist/protocol/conformance/cases/reads.js.map +1 -1
  11. package/dist/protocol/conformance/cases/writes.d.ts.map +1 -1
  12. package/dist/protocol/conformance/cases/writes.js +3 -20
  13. package/dist/protocol/conformance/cases/writes.js.map +1 -1
  14. package/dist/protocol/conformance/contentHashFixtures.d.ts +0 -29
  15. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  16. package/dist/protocol/conformance/contentHashFixtures.js +0 -30
  17. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  18. package/dist/protocol/conformance/context.d.ts +4 -29
  19. package/dist/protocol/conformance/context.d.ts.map +1 -1
  20. package/dist/protocol/conformance/context.js +4 -13
  21. package/dist/protocol/conformance/context.js.map +1 -1
  22. package/dist/protocol/conformance/index.d.ts +1 -1
  23. package/dist/protocol/conformance/index.d.ts.map +1 -1
  24. package/dist/protocol/conformance/index.js +4 -4
  25. package/dist/protocol/conformance/index.js.map +1 -1
  26. package/dist/protocol/errors.d.ts +5 -9
  27. package/dist/protocol/errors.d.ts.map +1 -1
  28. package/dist/protocol/errors.js +4 -4
  29. package/dist/protocol/errors.js.map +1 -1
  30. package/dist/protocol/index.d.ts +3 -5
  31. package/dist/protocol/index.d.ts.map +1 -1
  32. package/dist/protocol/index.js +3 -5
  33. package/dist/protocol/index.js.map +1 -1
  34. package/dist/protocol/params.d.ts.map +1 -1
  35. package/dist/protocol/params.js +0 -4
  36. package/dist/protocol/params.js.map +1 -1
  37. package/dist/protocol/server/assets.d.ts +2 -3
  38. package/dist/protocol/server/assets.d.ts.map +1 -1
  39. package/dist/protocol/server/assets.js +2 -9
  40. package/dist/protocol/server/assets.js.map +1 -1
  41. package/dist/protocol/server/content.d.ts +2 -3
  42. package/dist/protocol/server/content.d.ts.map +1 -1
  43. package/dist/protocol/server/content.js +10 -22
  44. package/dist/protocol/server/content.js.map +1 -1
  45. package/dist/protocol/server/core.d.ts +8 -11
  46. package/dist/protocol/server/core.d.ts.map +1 -1
  47. package/dist/protocol/server/core.js +8 -24
  48. package/dist/protocol/server/core.js.map +1 -1
  49. package/dist/protocol/server/handler.d.ts.map +1 -1
  50. package/dist/protocol/server/handler.js +11 -23
  51. package/dist/protocol/server/handler.js.map +1 -1
  52. package/dist/protocol/server/http.d.ts +6 -4
  53. package/dist/protocol/server/http.d.ts.map +1 -1
  54. package/dist/protocol/server/http.js +1 -18
  55. package/dist/protocol/server/http.js.map +1 -1
  56. package/dist/protocol/server/index.d.ts +0 -1
  57. package/dist/protocol/server/index.d.ts.map +1 -1
  58. package/dist/protocol/server/index.js.map +1 -1
  59. package/dist/protocol/server/methods/apply.d.ts +2 -2
  60. package/dist/protocol/server/methods/apply.d.ts.map +1 -1
  61. package/dist/protocol/server/methods/apply.js +23 -71
  62. package/dist/protocol/server/methods/apply.js.map +1 -1
  63. package/dist/protocol/server/methods/read.d.ts +0 -6
  64. package/dist/protocol/server/methods/read.d.ts.map +1 -1
  65. package/dist/protocol/server/methods/read.js +7 -31
  66. package/dist/protocol/server/methods/read.js.map +1 -1
  67. package/dist/protocol/server/rpc.d.ts +1 -1
  68. package/dist/protocol/server/rpc.d.ts.map +1 -1
  69. package/dist/protocol/server/rpc.js +9 -39
  70. package/dist/protocol/server/rpc.js.map +1 -1
  71. package/dist/protocol/storage/fs/index.d.ts +0 -3
  72. package/dist/protocol/storage/fs/index.d.ts.map +1 -1
  73. package/dist/protocol/storage/fs/index.js +0 -5
  74. package/dist/protocol/storage/fs/index.js.map +1 -1
  75. package/dist/protocol/storage/memory.d.ts +1 -6
  76. package/dist/protocol/storage/memory.d.ts.map +1 -1
  77. package/dist/protocol/storage/memory.js +1 -30
  78. package/dist/protocol/storage/memory.js.map +1 -1
  79. package/dist/protocol/storage.d.ts +7 -50
  80. package/dist/protocol/storage.d.ts.map +1 -1
  81. package/dist/protocol/storage.js +1 -1
  82. package/dist/protocol/storage.js.map +1 -1
  83. package/dist/protocol/types.d.ts +23 -34
  84. package/dist/protocol/types.d.ts.map +1 -1
  85. package/dist/protocol/types.js +10 -10
  86. package/dist/protocol/types.js.map +1 -1
  87. package/dist/v8/boundedJson.d.ts +11 -0
  88. package/dist/v8/boundedJson.d.ts.map +1 -0
  89. package/dist/v8/boundedJson.js +44 -0
  90. package/dist/v8/boundedJson.js.map +1 -0
  91. package/dist/v8/canonical.d.ts +0 -35
  92. package/dist/v8/canonical.d.ts.map +1 -1
  93. package/dist/v8/canonical.js +0 -28
  94. package/dist/v8/canonical.js.map +1 -1
  95. package/dist/v8/cli/check/index.d.ts +5 -0
  96. package/dist/v8/cli/check/index.d.ts.map +1 -1
  97. package/dist/v8/cli/check/index.js +21 -1
  98. package/dist/v8/cli/check/index.js.map +1 -1
  99. package/dist/v8/cli/run.js +1 -1
  100. package/dist/v8/cli/schema/generate.d.ts +3 -1
  101. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  102. package/dist/v8/cli/schema/generate.js +2 -1
  103. package/dist/v8/cli/schema/generate.js.map +1 -1
  104. package/dist/v8/cli/serve/server.d.ts +1 -1
  105. package/dist/v8/cli/serve/server.d.ts.map +1 -1
  106. package/dist/v8/cli/serve/server.js +63 -23
  107. package/dist/v8/cli/serve/server.js.map +1 -1
  108. package/dist/v8/cms.d.ts.map +1 -1
  109. package/dist/v8/cms.js +7 -6
  110. package/dist/v8/cms.js.map +1 -1
  111. package/dist/v8/content.d.ts +6 -5
  112. package/dist/v8/content.d.ts.map +1 -1
  113. package/dist/v8/content.js +49 -39
  114. package/dist/v8/content.js.map +1 -1
  115. package/dist/v8/draft.d.ts +1 -1
  116. package/dist/v8/draft.d.ts.map +1 -1
  117. package/dist/v8/draft.js +24 -2
  118. package/dist/v8/draft.js.map +1 -1
  119. package/dist/v8/draftChanges.d.ts +44 -0
  120. package/dist/v8/draftChanges.d.ts.map +1 -0
  121. package/dist/v8/draftChanges.js +157 -0
  122. package/dist/v8/draftChanges.js.map +1 -0
  123. package/dist/v8/remoteLoader.d.ts +1 -1
  124. package/dist/v8/remoteLoader.d.ts.map +1 -1
  125. package/dist/v8/remoteLoader.js +19 -256
  126. package/dist/v8/remoteLoader.js.map +1 -1
  127. package/dist/v8/settings.d.ts.map +1 -1
  128. package/dist/v8/settings.js +9 -6
  129. package/dist/v8/settings.js.map +1 -1
  130. package/dist/v8/telemetry.d.ts +4 -0
  131. package/dist/v8/telemetry.d.ts.map +1 -1
  132. package/dist/v8/telemetry.js +49 -14
  133. package/dist/v8/telemetry.js.map +1 -1
  134. package/dist/v8/types.d.ts +20 -12
  135. package/dist/v8/types.d.ts.map +1 -1
  136. package/package.json +1 -1
  137. package/src/protocol/client.ts +1 -4
  138. package/src/protocol/conformance/cases/guards.ts +10 -188
  139. package/src/protocol/conformance/cases/reads.ts +29 -69
  140. package/src/protocol/conformance/cases/writes.ts +7 -35
  141. package/src/protocol/conformance/contentHashFixtures.ts +0 -57
  142. package/src/protocol/conformance/context.ts +9 -34
  143. package/src/protocol/conformance/index.ts +4 -9
  144. package/src/protocol/errors.ts +5 -10
  145. package/src/protocol/index.ts +2 -10
  146. package/src/protocol/params.ts +0 -4
  147. package/src/protocol/server/assets.ts +2 -12
  148. package/src/protocol/server/content.ts +10 -24
  149. package/src/protocol/server/core.ts +12 -34
  150. package/src/protocol/server/handler.ts +11 -30
  151. package/src/protocol/server/http.ts +1 -19
  152. package/src/protocol/server/index.ts +0 -1
  153. package/src/protocol/server/methods/apply.ts +22 -82
  154. package/src/protocol/server/methods/read.ts +7 -36
  155. package/src/protocol/server/rpc.ts +7 -47
  156. package/src/protocol/storage/fs/index.ts +0 -8
  157. package/src/protocol/storage/memory.ts +1 -36
  158. package/src/protocol/storage.ts +7 -39
  159. package/src/protocol/types.ts +21 -38
  160. package/src/v8/boundedJson.ts +47 -0
  161. package/src/v8/canonical.ts +0 -47
  162. package/src/v8/cli/check/index.ts +25 -1
  163. package/src/v8/cli/run.ts +1 -1
  164. package/src/v8/cli/schema/generate.ts +4 -1
  165. package/src/v8/cli/serve/server.ts +65 -29
  166. package/src/v8/cms.ts +7 -8
  167. package/src/v8/content.ts +55 -42
  168. package/src/v8/draft.ts +20 -2
  169. package/src/v8/draftChanges.ts +172 -0
  170. package/src/v8/remoteLoader.ts +23 -289
  171. package/src/v8/settings.ts +13 -6
  172. package/src/v8/telemetry.ts +58 -13
  173. package/src/v8/types.ts +23 -13
  174. package/dist/protocol/server/auth.d.ts +0 -31
  175. package/dist/protocol/server/auth.d.ts.map +0 -1
  176. package/dist/protocol/server/auth.js +0 -32
  177. package/dist/protocol/server/auth.js.map +0 -1
  178. package/src/protocol/server/auth.ts +0 -49
@@ -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,27 @@ 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
+ function parseCodePatterns(
50
+ preview: CMSConfig["preview"],
51
+ field: "hosts",
52
+ ): HostPattern[] | undefined {
46
53
  if (preview === undefined || preview === null) return undefined;
47
54
  if (typeof preview !== "object") {
48
55
  throw new TypeError("createCMS: `preview` must be an object, such as { hosts: [...] }");
49
56
  }
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");
57
+ const list = preview[field];
58
+ if (list === undefined) return undefined;
59
+ if (!Array.isArray(list)) {
60
+ throw new TypeError(`createCMS: \`preview.${field}\` must be a list of host patterns`);
54
61
  }
55
- return hosts.map((raw) => {
62
+ return list.map((raw) => {
56
63
  const pattern = parseHostPattern(raw);
57
64
  if (pattern === null) {
58
65
  throw new TypeError(
59
- `createCMS: ${JSON.stringify(raw)} in preview.hosts isn't a host pattern ` +
66
+ `createCMS: ${JSON.stringify(raw)} in preview.${field} isn't a host pattern ` +
60
67
  "(see /next/api-reference#host-patterns)",
61
68
  );
62
69
  }
@@ -3,8 +3,10 @@
3
3
  * /next/telemetry and /next/telemetry-internals.
4
4
  *
5
5
  * - **Where** comes from code: `createCMS({ telemetry })`, or the standard
6
- * `OTEL_EXPORTER_OTLP_ENDPOINT`/`OTEL_EXPORTER_OTLP_HEADERS` when it's left
7
- * out. `false` sends nothing.
6
+ * `OTEL_EXPORTER_OTLP_ENDPOINT`/`OTEL_EXPORTER_OTLP_HEADERS` (and the
7
+ * per-signal `OTEL_EXPORTER_OTLP_{METRICS,LOGS,TRACES}_ENDPOINT`) when it's
8
+ * left out. v7's `DECO_OTEL_*` names are read as aliases; the standard name
9
+ * wins when both are set. `false` sends nothing.
8
10
  * - **How much** comes from content: the `telemetry` section of the CMS
9
11
  * settings (`cms.settings()`, the release's `CMS` block), capped by
10
12
  * `telemetry.limits`. The CMS reads it outside any request, when the
@@ -49,8 +51,13 @@ export function telemetryLimits(config: false | TelemetryConfig | undefined): {
49
51
 
50
52
  type Attributes = Record<string, string | number | boolean | undefined>;
51
53
 
54
+ type Signal = "metrics" | "logs" | "traces";
55
+
52
56
  interface Destination {
57
+ /** The base URL each signal's `/v1/<signal>` is appended to; `""` with per-signal URLs only. */
53
58
  endpoint: string;
59
+ /** Full per-signal URLs, used as they are (the `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` form). */
60
+ signals?: Partial<Record<Signal, string>>;
54
61
  headers: Record<string, string>;
55
62
  site?: string;
56
63
  limits: { errorSampleRate: number; traceSampleRate: number };
@@ -99,12 +106,7 @@ export function resolveDestination(
99
106
  site?: string,
100
107
  ): Destination | null {
101
108
  if (config === false) return null;
102
- if (config === undefined || config === null) {
103
- const endpoint = readEnv("OTEL_EXPORTER_OTLP_ENDPOINT");
104
- if (!endpoint) return null;
105
- const headers = parseKeyValues(readEnv("OTEL_EXPORTER_OTLP_HEADERS"));
106
- return { endpoint, headers, site, limits: DEFAULT_LIMITS };
107
- }
109
+ if (config === undefined || config === null) return destinationFromEnv(site);
108
110
  const limits = telemetryLimits(config);
109
111
  if ("endpoint" in config) {
110
112
  if (typeof config.endpoint !== "string" || !config.endpoint) return null;
@@ -119,6 +121,46 @@ export function resolveDestination(
119
121
  };
120
122
  }
121
123
 
124
+ /** v7's names for the standard OTLP variables, read when the standard one is unset. */
125
+ const V7_ALIASES = {
126
+ OTEL_EXPORTER_OTLP_HEADERS: "DECO_OTEL_HEADERS",
127
+ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: "DECO_OTEL_METRICS_ENDPOINT",
128
+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: "DECO_OTEL_LOGS_ENDPOINT",
129
+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "DECO_OTEL_TRACES_ENDPOINT",
130
+ } as const;
131
+
132
+ /** The standard variable, else its v7 alias. */
133
+ function readOtlpEnv(name: keyof typeof V7_ALIASES | "OTEL_EXPORTER_OTLP_ENDPOINT") {
134
+ return (
135
+ readEnv(name) ||
136
+ (name in V7_ALIASES ? readEnv(V7_ALIASES[name as keyof typeof V7_ALIASES]) : undefined)
137
+ );
138
+ }
139
+
140
+ /**
141
+ * The destination the environment names: the standard OTLP variables, with
142
+ * v7's `DECO_OTEL_*` names as aliases. `DECO_OTEL_AUTH_TOKEN` (v7's secret
143
+ * for the collector) becomes the `authorization` header unless the headers
144
+ * set one. `null` when no endpoint is set.
145
+ */
146
+ function destinationFromEnv(site: string | undefined): Destination | null {
147
+ const endpoint = readOtlpEnv("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "";
148
+ const signals: Partial<Record<Signal, string>> = {};
149
+ for (const signal of ["metrics", "logs", "traces"] as const) {
150
+ const url = readOtlpEnv(
151
+ `OTEL_EXPORTER_OTLP_${signal.toUpperCase() as Uppercase<Signal>}_ENDPOINT`,
152
+ );
153
+ if (url) signals[signal] = url;
154
+ }
155
+ if (!endpoint && Object.keys(signals).length === 0) return null;
156
+ const token = readEnv("DECO_OTEL_AUTH_TOKEN");
157
+ const headers = {
158
+ ...(token ? { authorization: token } : {}),
159
+ ...parseKeyValues(readOtlpEnv("OTEL_EXPORTER_OTLP_HEADERS")),
160
+ };
161
+ return { endpoint, signals, headers, site, limits: DEFAULT_LIMITS };
162
+ }
163
+
122
164
  export class TelemetryPipeline {
123
165
  readonly #destination: Destination;
124
166
  #settings: Required<Telemetry> = { ...TELEMETRY_DEFAULTS };
@@ -273,7 +315,7 @@ export class TelemetryPipeline {
273
315
  const byName = new Map<string, Histogram[]>();
274
316
  for (const h of histograms) byName.set(h.name, [...(byName.get(h.name) ?? []), h]);
275
317
  sends.push(
276
- this.#send("/v1/metrics", {
318
+ this.#send("metrics", {
277
319
  resourceMetrics: [
278
320
  {
279
321
  resource,
@@ -307,7 +349,7 @@ export class TelemetryPipeline {
307
349
  }
308
350
  if (logs.length > 0) {
309
351
  sends.push(
310
- this.#send("/v1/logs", {
352
+ this.#send("logs", {
311
353
  resourceLogs: [
312
354
  {
313
355
  resource,
@@ -331,7 +373,7 @@ export class TelemetryPipeline {
331
373
  if (spans.length > 0) {
332
374
  const kinds = { internal: 1, server: 2, client: 3 };
333
375
  sends.push(
334
- this.#send("/v1/traces", {
376
+ this.#send("traces", {
335
377
  resourceSpans: [
336
378
  {
337
379
  resource,
@@ -401,8 +443,11 @@ export class TelemetryPipeline {
401
443
  };
402
444
  }
403
445
 
404
- async #send(path: string, payload: unknown): Promise<void> {
405
- const url = this.#destination.endpoint.replace(/\/+$/, "") + path;
446
+ async #send(signal: Signal, payload: unknown): Promise<void> {
447
+ const { endpoint, signals } = this.#destination;
448
+ const url =
449
+ signals?.[signal] ?? (endpoint ? `${endpoint.replace(/\/+$/, "")}/v1/${signal}` : "");
450
+ if (!url) return; // this signal has no destination
406
451
  const { body, gzipped } = await gzip(JSON.stringify(payload));
407
452
  const headers: Record<string, string> = {
408
453
  ...this.#destination.headers,
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,18 @@ 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
+ };
233
238
  /** The private key that decrypts `secret` blocks. */
234
239
  secrets?: { key?: string };
235
- /** Your site's ID, for hosted releases and drafts. */
240
+ /** Your site's ID, for hosted releases. Drafts don't need it. */
236
241
  site?: string;
237
- /** Your site token (secret), for hosted releases and drafts. */
242
+ /** Your site token (secret), for hosted releases. Drafts don't need it. */
238
243
  token?: string;
239
244
  }
240
245
 
@@ -273,7 +278,12 @@ export interface Client {
273
278
  export interface CMS {
274
279
  /** A client reading the current release. */
275
280
  forRelease(): Client;
276
- /** A client reading the draft a pointer names. */
281
+ /**
282
+ * A client reading the draft a pointer names: its changes, fetched from a
283
+ * preview API domain (`*.decocms.com` and loopback by default;
284
+ * `DECO_PREVIEW_API_DOMAINS` replaces the list), over this server's
285
+ * production content.
286
+ */
277
287
  forDraft(pointer: string): Client;
278
288
  /** A client pinned to a revision this CMS has served; an unknown revision behaves like the release. */
279
289
  forRevision(revision: string): Client;
@@ -286,7 +296,7 @@ export interface CMS {
286
296
  */
287
297
  settings(): Promise<EffectiveSettings>;
288
298
  /**
289
- * The request's draft pointer: `?__draft=` first, then the `deco-draft`
299
+ * The request's draft pointer: `?__draft=` first, then the `__deco_draft`
290
300
  * cookie. `null` when neither is present, for `?__draft=off`, and on a host
291
301
  * outside `settings().preview.hosts`, where the request gets the release.
292
302
  */
@@ -1,31 +0,0 @@
1
- /**
2
- * What an `authorize` hook decides:
3
- * - `true` or `{ scope }` — allowed. `scope` names the tenant and principal,
4
- * and scopes request-key receipts, so one tenant never replays another's.
5
- * - `false` or `"unauthorized"` — a missing or invalid bearer token (HTTP 401).
6
- * - `"forbidden"` — authenticated, but not allowed for this project.
7
- */
8
- export type AuthorizeResult = boolean | "unauthorized" | "forbidden" | {
9
- scope?: string;
10
- };
11
- export interface AuthOptions {
12
- /** When set, every request must carry `Authorization: Bearer <token>`. */
13
- token?: string;
14
- /** Decides whether a request may proceed (runs after the token check). */
15
- authorize?: (request: Request) => AuthorizeResult | Promise<AuthorizeResult>;
16
- }
17
- /**
18
- * Refuses options that would lock every client out by accident: an empty
19
- * token can never be presented, so every request would be 401.
20
- */
21
- export declare function assertAuthOptions(options: AuthOptions): void;
22
- type AuthOutcome = {
23
- ok: true;
24
- scope: string;
25
- } | {
26
- ok: false;
27
- reason: "unauthorized" | "forbidden";
28
- };
29
- export declare function authenticate(request: Request, options: AuthOptions): Promise<AuthOutcome>;
30
- export {};
31
- //# sourceMappingURL=auth.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/protocol/server/auth.ts"],"names":[],"mappings":"AAKA;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,cAAc,GAAG,WAAW,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE1F,MAAM,WAAW,WAAW;IAC1B,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;CAC9E;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAI5D;AAED,KAAK,WAAW,GACZ;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,cAAc,GAAG,WAAW,CAAA;CAAE,CAAC;AAExD,wBAAsB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAa/F"}