@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
@@ -9,8 +9,10 @@
9
9
  * in the browser can read and write the content through it, so it is meant
10
10
  * to run only while editing. This file is the Node HTTP layer:
11
11
  *
12
- * - Listens on 127.0.0.1 unless `--host` says otherwise (with a warning:
13
- * the network can reach it then).
12
+ * - Listens on loopback, 127.0.0.1 and ::1 on one port, so
13
+ * `http://localhost:<port>` reaches it whichever address the OS gives
14
+ * localhost; `--host` listens on that one address instead (with a warning
15
+ * beyond loopback: the network can reach it then).
14
16
  * - CORS is answered for any `Origin` (reflected, with `Vary: Origin`), and
15
17
  * so are Chrome's Private/Local Network Access preflights.
16
18
  * - Every save regenerates `.deco/blocks.gen.ts`.
@@ -34,7 +36,8 @@ import { CliError, decoPaths, findDecoRoot, packageVersion } from "../root.ts";
34
36
  const STUDIO_ORIGIN = "https://studio.decocms.com";
35
37
 
36
38
  const DEFAULT_PORT = 4545;
37
- const DEFAULT_HOST = "127.0.0.1";
39
+ /** Where it listens without `--host`; ::1 is skipped where IPv6 is unavailable. */
40
+ const DEFAULT_HOSTS = ["127.0.0.1", "::1"];
38
41
 
39
42
  const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
40
43
 
@@ -52,7 +55,7 @@ export interface ServeOptions {
52
55
  }
53
56
 
54
57
  export interface RunningServer {
55
- /** The content protocol endpoint, `http://127.0.0.1:4545/rpc`. */
58
+ /** The content protocol endpoint, `http://localhost:4545/rpc`. */
56
59
  endpoint: string;
57
60
  siteEditorUrl: string;
58
61
  port: number;
@@ -101,7 +104,7 @@ function previewUrl(input: string): string {
101
104
  export async function startServer(options: ServeOptions = {}): Promise<RunningServer> {
102
105
  const reporter = options.reporter ?? consoleReporter;
103
106
  const paths = decoPaths(findDecoRoot(options));
104
- const host = (options.host ?? DEFAULT_HOST).toLowerCase();
107
+ const host = options.host?.toLowerCase();
105
108
  const requestedPort = options.port ?? DEFAULT_PORT;
106
109
  const readOnly = options.readOnly ?? false;
107
110
  const preview = previewUrl(options.preview ?? defaultPreviewUrl(paths.root));
@@ -143,7 +146,7 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
143
146
  });
144
147
  const assets = createAssetHandler(storage);
145
148
 
146
- const server = http.createServer(async (req, res) => {
149
+ const handle: http.RequestListener = async (req, res) => {
147
150
  const origin = req.headers.origin;
148
151
  const cors: Record<string, string> = {};
149
152
  const refuse = (status: number, code: number, message: string) => {
@@ -181,39 +184,30 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
181
184
  } catch (error) {
182
185
  refuse(500, ErrorCode.InternalError, (error as Error).message);
183
186
  }
184
- });
187
+ };
185
188
 
186
- await new Promise<void>((resolve, reject) => {
187
- server.once("error", (error: NodeJS.ErrnoException) =>
188
- reject(
189
- error.code === "EADDRINUSE"
190
- ? new CliError(`port ${requestedPort} is in use; pass --port`)
191
- : error,
192
- ),
193
- );
194
- server.listen(requestedPort, host, () => resolve());
195
- });
196
- const port = (server.address() as AddressInfo).port;
189
+ const servers = await listen(handle, host ? [host] : DEFAULT_HOSTS, requestedPort);
190
+ const port = (servers[0].address() as AddressInfo).port;
197
191
 
198
- const displayHost = host.includes(":") ? `[${host}]` : host;
192
+ const displayHost = !host ? "localhost" : host.includes(":") ? `[${host}]` : host;
199
193
  const endpoint = `http://${displayHost}:${port}/rpc`;
200
194
  // The site editor connects only through loopback; a wildcard address
201
- // listens there too, so its link uses 127.0.0.1.
195
+ // listens there too, so its link uses localhost.
202
196
  const wildcard = host === "0.0.0.0" || host === "::";
203
- const linkEndpoint = wildcard ? `http://127.0.0.1:${port}/rpc` : endpoint;
197
+ const linkEndpoint = wildcard ? `http://localhost:${port}/rpc` : endpoint;
204
198
  const siteEditorUrl = `${STUDIO_ORIGIN}/site-editor#endpoint=${encodeURIComponent(linkEndpoint)}`;
205
199
 
206
- if (!LOOPBACK.has(host)) {
200
+ if (host && !LOOPBACK.has(host)) {
207
201
  reporter.warn(
208
202
  `warning: listening on ${host}: other machines on the network can reach this server and read and write the content` +
209
- (wildcard ? "" : "; the site editor connects only through 127.0.0.1/localhost"),
203
+ (wildcard ? "" : "; the site editor connects only through localhost"),
210
204
  );
211
205
  }
212
206
  const schemaFile = fs.existsSync(paths.schema)
213
207
  ? ".deco/schema.gen.json"
214
208
  : fs.existsSync(paths.legacySchema)
215
209
  ? ".deco/meta.gen.json"
216
- : "no schema: run deco schema";
210
+ : "no schema yet: run deco schema for typed forms";
217
211
  const count = Object.keys(readSavedBlocks(paths.blocks).blocks).length;
218
212
  const description = await storage.describe();
219
213
  const label = (name: string) => name.padEnd(21);
@@ -231,14 +225,56 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
231
225
  endpoint,
232
226
  siteEditorUrl,
233
227
  port,
234
- close: () =>
235
- new Promise<void>((resolve) => {
236
- server.closeAllConnections?.();
237
- server.close(() => resolve());
238
- }),
228
+ close: () => Promise.all(servers.map(close)).then(() => undefined),
239
229
  };
240
230
  }
241
231
 
232
+ /**
233
+ * One server per address, all on the port the first one gets. An address
234
+ * after the first that the machine doesn't have (::1 without IPv6) is
235
+ * skipped; with port 0, a port the next address can't take is tried again.
236
+ */
237
+ async function listen(
238
+ handle: http.RequestListener,
239
+ hosts: string[],
240
+ requestedPort: number,
241
+ ): Promise<http.Server[]> {
242
+ for (let attempt = 0; ; attempt++) {
243
+ const servers: http.Server[] = [];
244
+ let port = requestedPort;
245
+ try {
246
+ for (const [i, host] of hosts.entries()) {
247
+ const server = http.createServer(handle);
248
+ try {
249
+ await new Promise<void>((resolve, reject) => {
250
+ server.once("error", reject);
251
+ server.listen(port, host, () => resolve());
252
+ });
253
+ } catch (error) {
254
+ const code = (error as NodeJS.ErrnoException).code;
255
+ if (i > 0 && (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT")) continue;
256
+ throw error;
257
+ }
258
+ servers.push(server);
259
+ port = (server.address() as AddressInfo).port;
260
+ }
261
+ return servers;
262
+ } catch (error) {
263
+ await Promise.all(servers.map(close));
264
+ if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE") throw error;
265
+ if (requestedPort === 0 && attempt < 5) continue;
266
+ throw new CliError(`port ${port} is in use; pass --port`);
267
+ }
268
+ }
269
+ }
270
+
271
+ function close(server: http.Server): Promise<void> {
272
+ return new Promise((resolve) => {
273
+ server.closeAllConnections?.();
274
+ server.close(() => resolve());
275
+ });
276
+ }
277
+
242
278
  /** A Node request as a fetch `Request`, its body streamed. */
243
279
  function toRequest(req: http.IncomingMessage): Request {
244
280
  const headers = new Headers();
package/src/v8/cms.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  defaultSettings,
22
22
  isStatic,
23
23
  parseCodeHosts,
24
+ parseCodeSources,
24
25
  readSettings,
25
26
  type SettingsCaps,
26
27
  } from "./settings.ts";
@@ -72,6 +73,8 @@ class CMSInstance {
72
73
  readonly #builtIns: Readonly<Blocks>;
73
74
  readonly #telemetry: TelemetryPipeline | undefined;
74
75
  readonly #caps: SettingsCaps;
76
+ /** The hosts a draft pointer may name (`preview.sources`): code only, never content. */
77
+ readonly #sources: readonly HostPattern[];
75
78
  /** Settings of a `CMS` block with nothing to run, per release snapshot. */
76
79
  #staticSettings = new WeakMap<Snapshot, EffectiveSettings>();
77
80
  /** The release and time telemetry last read its section. */
@@ -93,6 +96,7 @@ class CMSInstance {
93
96
  hosts: parseCodeHosts(config.preview),
94
97
  limits: telemetryLimits(config.telemetry),
95
98
  };
99
+ this.#sources = parseCodeSources(config.preview);
96
100
  const destination = resolveDestination(config.telemetry, config.site);
97
101
  if (destination !== null) {
98
102
  this.#telemetry = new TelemetryPipeline(destination);
@@ -141,17 +145,16 @@ class CMSInstance {
141
145
  }
142
146
 
143
147
  /**
144
- * The draft, with the variants the pointer forces (even over a source with no
145
- * drafts). A draft client is a production client reading a draft pointer, so
146
- * it schedules the release check like any other client.
148
+ * The draft, with the variants the pointer forces (even for a `local`
149
+ * pointer, which names no draft). A draft client is a production client
150
+ * reading a draft pointer, so it schedules the release check like any other.
147
151
  */
148
152
  forDraft(blocks: Blocks, pointer: string): Client {
149
153
  this.#scheduleUpdate();
154
+ const load = () => this.#store.draft(pointer, this.#sources);
150
155
  const variants = parseDraftPointer(pointer)?.variants;
151
- if (variants === undefined) return this.#client(blocks, () => this.#store.draft(pointer));
152
- return this.#client(blocks, () =>
153
- this.#store.draft(pointer).then((snapshot) => forceVariants(snapshot, variants)),
154
- );
156
+ if (variants === undefined) return this.#client(blocks, load);
157
+ return this.#client(blocks, () => load().then((snapshot) => forceVariants(snapshot, variants)));
155
158
  }
156
159
 
157
160
  forRevision(blocks: Blocks, revision: string): Client {
@@ -366,7 +369,7 @@ export function resetForTests(): void {
366
369
  setCurrentTelemetry(undefined);
367
370
  }
368
371
 
369
- /** With `site` and `token`, the content is the fallback of hosted releases and drafts. */
372
+ /** With `site` and `token`, the content is the fallback of hosted releases. */
370
373
  function contentOf(config: CMSConfig): Snapshot | Loader {
371
374
  if (!config.site || !config.token) return config.content;
372
375
  return remoteLoader(config.content, { site: config.site, token: config.token });
@@ -385,6 +388,7 @@ function validate(config: CMSConfig): void {
385
388
  );
386
389
  }
387
390
  parseCodeHosts(config.preview);
391
+ parseCodeSources(config.preview);
388
392
  }
389
393
 
390
394
  function resolveInterval(configured: number | undefined): number {
package/src/v8/content.ts CHANGED
@@ -3,24 +3,32 @@
3
3
  * the caches every client shares, and the release revisions this process has
4
4
  * served. Clients only ever see whole `{ revision, blocks }` snapshots.
5
5
  *
6
- * Drafts are never recorded as served: `forRevision(revision)` takes a
7
- * revision string a client may hand back, so it must only ever reach published
8
- * content, never a draft someone loaded with a pointer.
6
+ * A draft is the release with a draft's changes layered over it (see
7
+ * ./draftChanges.ts). Drafts are never recorded as served:
8
+ * `forRevision(revision)` takes a revision string a client may hand back, so
9
+ * it must only ever reach published content, never a draft someone loaded
10
+ * with a pointer.
9
11
  */
10
12
  import { formatDraftPointer, parseDraftPointer } from "./draft.ts";
13
+ import { type DraftChanges, fetchDraftChanges, LOCAL_VERSION, layerDraft } from "./draftChanges.ts";
11
14
  import { errors, isResolutionError } from "./errors.ts";
15
+ import type { HostPattern } from "./hosts.ts";
12
16
  import { isPlainObject } from "./json.ts";
13
17
  import type { Loader, Snapshot } from "./types.ts";
14
18
 
15
19
  const SERVED_REVISIONS = 16;
16
- /** Composed drafts kept per CMS (see /next/studio-implementation's initial limits). */
20
+ /** Fetched drafts kept per CMS. */
17
21
  const CACHED_DRAFTS = 3;
18
- /**
19
- * How long a loaded draft is reused before `load(pointer)` runs again, so a
20
- * loader's own checks (a hosted grant's expiry) apply on a warm server too.
21
- */
22
+ /** How long a fetched draft is reused before it's fetched again, so its token is checked again. */
22
23
  const DRAFT_TTL_MS = 60_000;
23
24
 
25
+ /** A fetched draft, and the views of it over each release it was layered on. */
26
+ interface CachedDraft {
27
+ changes: Promise<DraftChanges>;
28
+ at: number;
29
+ views: WeakMap<Snapshot, Snapshot>;
30
+ }
31
+
24
32
  export function isLoader(content: unknown): content is Loader {
25
33
  return (
26
34
  (typeof content === "object" || typeof content === "function") &&
@@ -56,9 +64,7 @@ export class ContentStore {
56
64
  #source: Snapshot | Loader;
57
65
  #release: Promise<Snapshot> | undefined;
58
66
  #updating: Promise<{ updated: boolean }> | undefined;
59
- readonly #drafts = new BoundedMap<string, { pending: Promise<Snapshot>; at: number }>(
60
- CACHED_DRAFTS,
61
- );
67
+ readonly #drafts = new BoundedMap<string, CachedDraft>(CACHED_DRAFTS);
62
68
  readonly #served = new BoundedMap<string, Snapshot>(SERVED_REVISIONS);
63
69
  /** The release this store last handed a client, for a loader that can't peek. */
64
70
  #latest: Snapshot | undefined;
@@ -80,9 +86,9 @@ export class ContentStore {
80
86
  release(): Promise<Snapshot> {
81
87
  const source = this.#source;
82
88
  if (!isLoader(source)) return Promise.resolve(this.#serve(source));
83
- if (!this.updatable) return this.#load(source, null).then((snapshot) => this.#serve(snapshot));
89
+ if (!this.updatable) return this.#load(source).then((snapshot) => this.#serve(snapshot));
84
90
  if (this.#release === undefined) {
85
- const pending = this.#load(source, null).then((snapshot) => this.#serve(snapshot));
91
+ const pending = this.#load(source).then((snapshot) => this.#serve(snapshot));
86
92
  this.#release = pending;
87
93
  // A failed load isn't cached: the next client tries again.
88
94
  pending.catch(() => {
@@ -93,33 +99,46 @@ export class ContentStore {
93
99
  }
94
100
 
95
101
  /**
96
- * The draft a pointer names. A snapshot has no drafts and ignores the
97
- * pointer. A loader gets `load(pointer)` only for a pointer that parses,
98
- * formatted again without its `__variant` parameters (so every variant of
99
- * one draft shares one load); anything else is `LOADER_FAILED`, never a
100
- * silent fallback to the release. A loaded draft is reused for a minute.
102
+ * The draft a pointer names: its changes, fetched from a host in `sources`,
103
+ * layered over the release. A pointer that doesn't parse, or any failure, is
104
+ * `LOADER_FAILED`, never a silent fallback to the release. A pointer whose
105
+ * version is `local` names no draft: the release, with nothing fetched. The
106
+ * changes are keyed by the pointer without its `__variant` parameters (every
107
+ * variant of one draft shares one fetch) and reused for a minute.
101
108
  */
102
- draft(pointer: string): Promise<Snapshot> {
103
- const source = this.#source;
104
- if (!isLoader(source)) return this.release();
109
+ draft(pointer: string, sources: readonly HostPattern[]): Promise<Snapshot> {
105
110
  const parsed = parseDraftPointer(pointer);
106
111
  if (parsed === null) {
107
112
  return Promise.reject(errors.loaderFailed(`invalid draft pointer "${truncate(pointer)}"`));
108
113
  }
109
- // The draft itself, without the variants a preview forces: those apply per client.
110
- const key = formatDraftPointer({
111
- host: parsed.host,
112
- path: parsed.path,
113
- version: parsed.version,
114
- });
115
- const cached = this.#drafts.get(key);
116
- if (cached !== undefined && Date.now() - cached.at < DRAFT_TTL_MS) return cached.pending;
117
- const entry = { pending: this.#load(source, key), at: Date.now() };
118
- this.#drafts.set(key, entry);
119
- entry.pending.catch(() => {
120
- if (this.#drafts.get(key) === entry) this.#drafts.delete(key);
114
+ if (parsed.version === LOCAL_VERSION) return this.release();
115
+ const { host, path, version } = parsed;
116
+ const key = formatDraftPointer({ host, path, version });
117
+ let entry = this.#drafts.get(key);
118
+ if (entry === undefined || Date.now() - entry.at >= DRAFT_TTL_MS) {
119
+ const fetched: CachedDraft = {
120
+ changes: fetchDraftChanges(parsed, sources).catch((error: unknown) => {
121
+ throw errors.loaderFailed("the draft's changes couldn't be fetched", error);
122
+ }),
123
+ at: Date.now(),
124
+ views: new WeakMap(),
125
+ };
126
+ this.#drafts.set(key, fetched);
127
+ // A failure isn't reused: the next client fetches again.
128
+ fetched.changes.catch(() => {
129
+ if (this.#drafts.get(key) === fetched) this.#drafts.delete(key);
130
+ });
131
+ entry = fetched;
132
+ }
133
+ const { changes, views } = entry;
134
+ return Promise.all([this.release(), changes]).then(([base, draft]) => {
135
+ let view = views.get(base);
136
+ if (view === undefined) {
137
+ view = layerDraft(base, draft, version);
138
+ views.set(base, view);
139
+ }
140
+ return view;
121
141
  });
122
- return entry.pending;
123
142
  }
124
143
 
125
144
  /**
@@ -151,8 +170,7 @@ export class ContentStore {
151
170
  this.#release = undefined;
152
171
  // `#latest` stays: settings keep the release that was serving until
153
172
  // the next one loads, never the defaults (which may allow every host).
154
- // A loader that ignores the pointer hands back the release as the
155
- // draft; that copy is as stale as the release now.
173
+ // Drafts are fetched again, so a preview follows the release too.
156
174
  this.#drafts.clear();
157
175
  }
158
176
  return { updated };
@@ -175,7 +193,6 @@ export class ContentStore {
175
193
  const previous = this.#source;
176
194
  if (source === previous) {
177
195
  // The same loader (a hosted remoteLoader that adopted new fallback content): re-read it.
178
- // Cached drafts were layered over the old content, so they go too.
179
196
  this.#release = undefined;
180
197
  this.#latest = undefined;
181
198
  this.#drafts.clear();
@@ -188,16 +205,13 @@ export class ContentStore {
188
205
  this.#drafts.clear();
189
206
  }
190
207
 
191
- async #load(loader: Loader, pointer: string | null): Promise<Snapshot> {
208
+ async #load(loader: Loader): Promise<Snapshot> {
192
209
  let snapshot: unknown;
193
210
  try {
194
- snapshot = pointer === null ? await loader.load() : await loader.load(pointer);
211
+ snapshot = await loader.load();
195
212
  } catch (error) {
196
213
  if (isResolutionError(error)) throw error;
197
- throw errors.loaderFailed(
198
- pointer === null ? "the content loader failed" : "the draft couldn't load",
199
- error,
200
- );
214
+ throw errors.loaderFailed("the content loader failed", error);
201
215
  }
202
216
  if (!isSnapshot(snapshot)) {
203
217
  throw errors.loaderFailed("the content loader returned something other than a snapshot");
package/src/v8/draft.ts CHANGED
@@ -128,6 +128,7 @@ function plainVariant({ block, path, index }: ForcedVariant): ForcedVariant {
128
128
  }
129
129
 
130
130
  function normalizeHost(authority: string): string | null {
131
+ if (authority.startsWith("[")) return normalizeIPv6Host(authority);
131
132
  const parts = authority.toLowerCase().split(":");
132
133
  if (parts.length > 2) return null;
133
134
  const [host, port] = parts;
@@ -137,6 +138,23 @@ function normalizeHost(authority: string): string | null {
137
138
  return `${host}:${port}`;
138
139
  }
139
140
 
141
+ /** `[addr]` or `[addr]:port`, the address in the compressed, lowercase form a URL gives it. */
142
+ function normalizeIPv6Host(authority: string): string | null {
143
+ const end = authority.indexOf("]");
144
+ const address = authority.slice(0, end + 1);
145
+ const rest = authority.slice(end + 1);
146
+ if (end === -1 || !/^\[[0-9a-fA-F:.]+\]$/.test(address)) return null;
147
+ if (rest !== "" && (!rest.startsWith(":") || !PORT_RE.test(rest.slice(1)))) return null;
148
+ if (rest !== "" && Number(rest.slice(1)) > 65535) return null;
149
+ let host: string;
150
+ try {
151
+ host = new URL(`http://${address}/`).hostname;
152
+ } catch {
153
+ return null;
154
+ }
155
+ return `${host}${rest}`;
156
+ }
157
+
140
158
  /**
141
159
  * The draft pointer a request carries: `?__draft=` from the URL first, then
142
160
  * the `deco-draft` cookie. `null` when neither is present, or when the URL
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Draft changes (see /next/content-delivery#draft-previews): what a draft
3
+ * pointer's address answers, and how the CMS layers it over production.
4
+ *
5
+ * - The pointer's host must be one of `preview.sources` (code only, default
6
+ * `studio.decocms.com`); any other host is refused before anything is fetched.
7
+ * - `GET https://<host><path>&v=<version>`: plain `http` only for loopback
8
+ * hosts. The pointer's `__variant` parameters are already gone (the parser
9
+ * lifts them out), no cookies or credentials are sent, and redirects aren't
10
+ * followed (a response that was redirected anyway is refused).
11
+ * - Only a 200 is accepted, within 10 s and up to 16 MiB, shaped exactly
12
+ * `{ format: 1, set: { <name>: <block JSON> }, delete: [<name>…] }` with
13
+ * `set` and `delete` disjoint.
14
+ */
15
+ import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
16
+ import { allowsHost, type HostPattern } from "./hosts.ts";
17
+ import { isPlainObject } from "./json.ts";
18
+ import type { DraftPointer, Snapshot } from "./types.ts";
19
+
20
+ /** The version a pointer has when it names no draft: `deco serve`'s working tree. */
21
+ export const LOCAL_VERSION = "local";
22
+
23
+ const FORMAT = 1;
24
+ const TIMEOUT_MS = 10_000;
25
+ const MAX_BYTES = 16 * 1024 * 1024;
26
+
27
+ /** What a draft changed compared with production: whole blocks, and deletions. */
28
+ export interface DraftChanges {
29
+ format: typeof FORMAT;
30
+ set: Record<string, unknown>;
31
+ delete: string[];
32
+ }
33
+
34
+ /** The URL the SDK fetches for a pointer: the scheme from its host, the version as `v`. */
35
+ export function draftChangesUrl(pointer: DraftPointer): string {
36
+ const scheme = isLoopback(pointer.host) ? "http" : "https";
37
+ const separator = pointer.path.includes("?") ? "&" : "?";
38
+ return `${scheme}://${pointer.host}${pointer.path}${separator}v=${encodeURIComponent(pointer.version)}`;
39
+ }
40
+
41
+ /** Fetches a draft's changes; rejects on a host outside `sources` (without fetching) or on any failure. */
42
+ export async function fetchDraftChanges(
43
+ pointer: DraftPointer,
44
+ sources: readonly HostPattern[],
45
+ ): Promise<DraftChanges> {
46
+ const url = draftChangesUrl(pointer);
47
+ if (!allowsHost(sources, url)) {
48
+ throw new Error(
49
+ `draft pointer names "${pointer.host}", which isn't in preview.sources; nothing was fetched`,
50
+ );
51
+ }
52
+ const response = await fetch(url, {
53
+ headers: { accept: "application/json" },
54
+ redirect: "manual",
55
+ signal: timeoutSignal(TIMEOUT_MS),
56
+ });
57
+ // Some fetch polyfills (React Native, whatwg-fetch) ignore `redirect: "manual"`
58
+ // and follow anyway: refuse a response that came from anywhere else.
59
+ if (response.redirected || (response.url && !allowsHost(sources, response.url))) {
60
+ await response.body?.cancel();
61
+ throw new Error("draft changes: the pointer's address redirected; nothing was read");
62
+ }
63
+ if (response.status !== 200) {
64
+ await response.body?.cancel();
65
+ throw new Error(`draft changes: HTTP ${response.status}`);
66
+ }
67
+ return parseDraftChanges(await readBoundedJson(response, "draft changes", MAX_BYTES));
68
+ }
69
+
70
+ /** Validates a draft changes response; throws on an unknown format or any unexpected shape. */
71
+ export function parseDraftChanges(body: unknown): DraftChanges {
72
+ const invalid = (why: string) => new Error(`draft changes: ${why}`);
73
+ if (!isPlainObject(body) || body.format !== FORMAT) throw invalid("unknown format");
74
+ if (Object.keys(body).some((key) => key !== "format" && key !== "set" && key !== "delete")) {
75
+ throw invalid("unexpected field");
76
+ }
77
+ const { set, delete: deleted } = body;
78
+ if (!isPlainObject(set)) throw invalid("set must be an object");
79
+ if (!Array.isArray(deleted) || deleted.some((name) => typeof name !== "string")) {
80
+ throw invalid("delete must be a list of names");
81
+ }
82
+ if (new Set(deleted).size !== deleted.length) throw invalid("delete repeats a name");
83
+ if (deleted.some((name) => Object.hasOwn(set, name))) throw invalid("set and delete overlap");
84
+ return body as unknown as DraftChanges;
85
+ }
86
+
87
+ /**
88
+ * The draft as a snapshot: production's entries, with the changed ones
89
+ * replaced whole and the deleted ones gone. A shallow copy: every unchanged
90
+ * entry is production's own object, and production is never mutated. Its
91
+ * revision is an opaque identity of the pair, never a release's.
92
+ */
93
+ export function layerDraft(base: Snapshot, changes: DraftChanges, version: string): Snapshot {
94
+ const blocks: Record<string, unknown> = { ...base.blocks };
95
+ for (const name of changes.delete) delete blocks[name];
96
+ for (const [name, entry] of Object.entries(changes.set)) {
97
+ // defineProperty, so an entry named "__proto__" stays an entry.
98
+ Object.defineProperty(blocks, name, {
99
+ value: entry,
100
+ enumerable: true,
101
+ writable: true,
102
+ configurable: true,
103
+ });
104
+ }
105
+ const view: Snapshot = { revision: `${base.revision}~${version}`, blocks };
106
+ if (base.aliases !== undefined) view.aliases = base.aliases;
107
+ return view;
108
+ }
109
+
110
+ function isLoopback(authority: string): boolean {
111
+ const host = authority.startsWith("[")
112
+ ? authority.slice(0, authority.indexOf("]") + 1)
113
+ : authority.split(":")[0]!;
114
+ return (
115
+ host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]"
116
+ );
117
+ }