@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
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * Browser-safe: types and small error classes only.
12
12
  */
13
- import type { Limits, StorageKind } from "./types.ts";
13
+ import type { StorageKind } from "./types.ts";
14
14
 
15
15
  /** What a storage tells `describe`. */
16
16
  export interface StorageDescription {
@@ -18,19 +18,10 @@ export interface StorageDescription {
18
18
  /** The app root, relative to the repository root (`"."` when they're the same). */
19
19
  root: string;
20
20
  readOnly: boolean;
21
- /** Branch support; `null` when the storage has no refs (`ref` params are then Unsupported). */
22
- refs: null | { default: string; autoCreate: boolean };
23
21
  /** Where uploads go; `null` when read-only or uploads go elsewhere. */
24
22
  assets: null | { dir: string; maxBytes: number };
25
- /**
26
- * Durable request-key receipts. Advertise only when `getReceipt` is
27
- * implemented and `commit` persists `attempt.receipt` with the mutation.
28
- */
29
- idempotency: null | { retentionMs: number };
30
23
  /** Overrides the poll interval (default: 2000 for a working tree, 30000 for git). */
31
24
  pollIntervalMs?: number;
32
- /** Lowers the protocol's default limits. Higher values are ignored. */
33
- limits?: Partial<Limits>;
34
25
  }
35
26
 
36
27
  /** One saved-block file in a snapshot. */
@@ -47,7 +38,7 @@ export interface StorageFile {
47
38
  export interface StorageSnapshot {
48
39
  /** An opaque revision of the whole set, compared only for equality. */
49
40
  revision: string;
50
- /** The ref actually read (it can differ from the requested one); `null` without refs. */
41
+ /** The branch actually read, for a storage that reads one; `null` for a working tree. */
51
42
  resolvedRef: string | null;
52
43
  files: StorageFile[];
53
44
  }
@@ -72,21 +63,8 @@ export interface StoredSchema {
72
63
  resolvedRef: string | null;
73
64
  }
74
65
 
75
- /** A durable receipt for one `blocks.apply` request key. */
76
- export interface StoredReceipt {
77
- /** The canonical digest of the request the key was first used with. */
78
- digest: string;
79
- /** The revision that commit produced. */
80
- revision: string;
81
- /** The versions of the files that commit wrote. */
82
- versions: Record<string, string>;
83
- /** The files that commit deleted (`attempt.delete`), so a replay reports the same names. */
84
- deleted?: string[];
85
- }
86
-
87
66
  /** One atomic commit attempt. */
88
67
  export interface CommitAttempt {
89
- ref?: string;
90
68
  /** The snapshot the core validated against. */
91
69
  base: StorageSnapshot;
92
70
  /** Files to write, by file name, with their full content. */
@@ -101,19 +79,11 @@ export interface CommitAttempt {
101
79
  expected: Record<string, string | null>;
102
80
  /**
103
81
  * The schema version the core validated against (`null` = no schema), when
104
- * the write depends on it (`ifSchemaMatch`, or the secret guard). When set,
82
+ * the write depends on it (the secret guard checks `set` against it). When set,
105
83
  * a storage MUST reject the attempt as stale if the schema's version at
106
84
  * commit time differs, checked atomically with `expected`.
107
85
  */
108
86
  expectedSchemaVersion?: string | null;
109
- /**
110
- * Persist this receipt atomically with the mutation (only when idempotency
111
- * is advertised). The key also reserves the request: a storage MUST reject
112
- * the attempt as stale when a receipt for `receipt.key` already exists,
113
- * including one written concurrently by another replica, so two requests
114
- * with the same key never both commit.
115
- */
116
- receipt?: { key: string; digest: string };
117
87
  }
118
88
 
119
89
  export type CommitResult =
@@ -129,9 +99,9 @@ export interface ContentStorage {
129
99
  describe(): StorageDescription | Promise<StorageDescription>;
130
100
  /**
131
101
  * Lists the saved-block files. Throws `StorageNotFoundError` when there's no
132
- * `.deco` folder at all, or the ref can't be read.
102
+ * `.deco` folder at all.
133
103
  */
134
- snapshot(options: { ref?: string }): Promise<StorageSnapshot>;
104
+ snapshot(): Promise<StorageSnapshot>;
135
105
  /**
136
106
  * Reads file bodies (UTF-8 text) from a snapshot, each with the version of
137
107
  * the bytes read. A file that vanished is left out. A storage that can't
@@ -140,18 +110,16 @@ export interface ContentStorage {
140
110
  */
141
111
  readFiles(snapshot: StorageSnapshot, files: string[]): Promise<Record<string, StoredFileBody>>;
142
112
  /** Reads `schema.gen.json`, falling back to `meta.gen.json`; `null` when neither exists. */
143
- readSchema(options: { ref?: string }): Promise<StoredSchema | null>;
113
+ readSchema(): Promise<StoredSchema | null>;
144
114
  /** Reads `<root>/.deco/secrets.pub`; `null` without one. */
145
115
  readSecretsPublicKey(): Promise<string | null>;
146
116
  /** One all-or-nothing commit attempt; durable when it resolves. */
147
117
  commit(attempt: CommitAttempt): Promise<CommitResult>;
148
- /** Looks up a receipt by its scoped key; `null` when unknown or expired. */
149
- getReceipt?(key: string): Promise<StoredReceipt | null>;
150
118
  /** Stores an uploaded file, never overwriting one; returns the stored file name. */
151
119
  putAsset?(name: string, body: Uint8Array): Promise<{ name: string }>;
152
120
  }
153
121
 
154
- /** Thrown by a storage when there's no `.deco` folder, or a ref can't be read or created. */
122
+ /** Thrown by a storage when there's no `.deco` folder. */
155
123
  export class StorageNotFoundError extends Error {
156
124
  constructor(message: string) {
157
125
  super(message);
@@ -10,6 +10,17 @@ export const PROTOCOL_VERSION = { major: 1, minor: 0 } as const;
10
10
 
11
11
  export const SCHEMA_FORMAT = "deco-meta@1";
12
12
 
13
+ /**
14
+ * The Blocks major a generated schema declares, as its top-level
15
+ * `blocksMajor`. `deco schema` writes it and `deco check` requires it. It is
16
+ * the package's major version, not the full version string, and it is the
17
+ * only signal a host such as the site editor should read to tell a v8 site
18
+ * from a v7 one: the schema's file name (`schema.gen.json` or
19
+ * `meta.gen.json`) doesn't tell. A schema without it, or with another value,
20
+ * is not a v8 schema.
21
+ */
22
+ export const BLOCKS_MAJOR = 8;
23
+
13
24
  /** The path the local server (`deco serve`) mounts the endpoint at. */
14
25
  export const RPC_PATH = "/rpc";
15
26
 
@@ -19,33 +30,6 @@ export const MAX_BATCH_CALLS = 10;
19
30
  /** The URL prefix every uploaded asset is stored under in a field. */
20
31
  export const ASSETS_URL_PREFIX = "/assets/";
21
32
 
22
- export interface Limits {
23
- /** Names (set plus delete) in one `blocks.apply`. */
24
- maxOpsPerApply: number;
25
- /** Bytes of one stored entry. */
26
- maxBlockBytes: number;
27
- /** Bytes of one HTTP request body, uncompressed. */
28
- maxRequestBytes: number;
29
- /** Uncompressed bytes of the whole block list. */
30
- maxListBytes: number;
31
- /** Uncompressed bytes of the schema. */
32
- maxSchemaBytes: number;
33
- /** Uncompressed bytes of a whole batch response. */
34
- maxBatchResponseBytes: number;
35
- }
36
-
37
- const MiB = 1024 * 1024;
38
-
39
- /** The protocol's default limits. A storage or a server can lower them. */
40
- export const DEFAULT_LIMITS: Readonly<Limits> = Object.freeze({
41
- maxOpsPerApply: 500,
42
- maxBlockBytes: 1 * MiB,
43
- maxRequestBytes: 8 * MiB,
44
- maxListBytes: 16 * MiB,
45
- maxSchemaBytes: 16 * MiB,
46
- maxBatchResponseBytes: 32 * MiB,
47
- });
48
-
49
33
  export type StorageKind = "working-tree" | "git";
50
34
 
51
35
  export interface DescribeResult {
@@ -58,12 +42,8 @@ export interface DescribeResult {
58
42
  /** The app root: the folder that contains `.deco/`, relative to the repository root. */
59
43
  root: string;
60
44
  schemaFormat: typeof SCHEMA_FORMAT;
61
- /** Branches; `null` on the local server. */
62
- refs: null | { default: string; autoCreate: boolean };
63
- writes: { idempotency: null | { retentionMs: number }; schemaPreconditions: boolean };
64
45
  /** Local: 2000; git: 30000, plus on window focus. */
65
46
  pollIntervalMs: number;
66
- limits: Limits;
67
47
  /**
68
48
  * The app the site editor shows in its Preview tab (and where "open the real
69
49
  * page" points); the local server reports `deco serve --preview`. `null`: no preview.
@@ -83,15 +63,23 @@ export interface DecoMeta {
83
63
  }
84
64
 
85
65
  export interface ReadParams {
86
- ref?: string;
87
66
  ifNoneMatch?: string;
88
67
  }
89
68
 
90
69
  export type SchemaGetParams = ReadParams;
91
70
 
71
+ /**
72
+ * `schema: null` (with `version: null`) means the site has no schema yet:
73
+ * neither `.deco/schema.gen.json` nor `.deco/meta.gen.json` exists. It's a
74
+ * normal state, not an error: `blocks.list` and `blocks.apply` work without a
75
+ * schema, so a client still lists and edits the blocks (without typed forms)
76
+ * and keeps polling until a schema appears. There's no version to send as
77
+ * `ifNoneMatch`, so the poll reads it unconditionally; the answer is tiny.
78
+ */
92
79
  export type SchemaGetResult =
93
80
  | { notModified: true; version: string }
94
- | { notModified: false; version: string; resolvedRef: string | null; schema: DecoMeta };
81
+ | { notModified: false; version: string; resolvedRef: string | null; schema: DecoMeta }
82
+ | { notModified: false; version: null; resolvedRef: string | null; schema: null };
95
83
 
96
84
  export type BlocksListParams = ReadParams;
97
85
 
@@ -122,11 +110,6 @@ export type BlocksListResult =
122
110
  };
123
111
 
124
112
  export interface BlocksApplyParams {
125
- ref?: string;
126
- /** Retry the same logical write; only when advertised. */
127
- requestKey?: string;
128
- /** Reject if the schema changed; only when advertised. */
129
- ifSchemaMatch?: string;
130
113
  /** Whole-entry replace (create or update). */
131
114
  set?: Record<string, Record<string, unknown>>;
132
115
  /** A missing name counts as deleted. */
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Network reads the SDK makes on its own (hosted releases, draft changes):
3
+ * a timeout on the whole request, and a JSON body refused as soon as it
4
+ * would exceed a size, before it's buffered whole (a Worker isolate has
5
+ * 128 MB).
6
+ */
7
+
8
+ /** An abort signal that fires after `ms`, where the runtime has `AbortSignal.timeout`. */
9
+ export function timeoutSignal(ms: number): AbortSignal | undefined {
10
+ return typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
11
+ ? AbortSignal.timeout(ms)
12
+ : undefined;
13
+ }
14
+
15
+ /** Parses a JSON body, refusing it once it passes `maxBytes`. */
16
+ export async function readBoundedJson(
17
+ response: Response,
18
+ label: string,
19
+ maxBytes: number,
20
+ ): Promise<unknown> {
21
+ const tooLarge = () => new Error(`${label}: larger than ${maxBytes} bytes`);
22
+ if (Number(response.headers.get("content-length")) > maxBytes) {
23
+ await response.body?.cancel();
24
+ throw tooLarge();
25
+ }
26
+ if (response.body === null) {
27
+ const text = await response.text();
28
+ if (text.length > maxBytes) throw tooLarge();
29
+ return JSON.parse(text);
30
+ }
31
+ const reader = response.body.getReader();
32
+ const decoder = new TextDecoder();
33
+ const parts: string[] = [];
34
+ let size = 0;
35
+ for (;;) {
36
+ const { done, value } = await reader.read();
37
+ if (done) break;
38
+ size += value.byteLength;
39
+ if (size > maxBytes) {
40
+ await reader.cancel();
41
+ throw tooLarge();
42
+ }
43
+ parts.push(decoder.decode(value, { stream: true }));
44
+ }
45
+ parts.push(decoder.decode());
46
+ return JSON.parse(parts.join(""));
47
+ }
@@ -104,50 +104,3 @@ export const CONTENT_HASH_FORMAT = 1;
104
104
  export async function computeContentRevision(blocks: Record<string, unknown>): Promise<string> {
105
105
  return sha256Hex(canonicalJson(blocks));
106
106
  }
107
-
108
- /** The domain prefix of `blocks.apply` request digests, so they never equal another hash. */
109
- export const APPLY_DIGEST_DOMAIN = "deco-content/blocks.apply@1\n";
110
-
111
- /**
112
- * The digest a request key is bound to: SHA-256 over the domain prefix and
113
- * the canonical JSON of every supplied parameter.
114
- */
115
- export function applyRequestDigest(params: object): Promise<string> {
116
- return sha256Hex(APPLY_DIGEST_DOMAIN + canonicalJson(params));
117
- }
118
-
119
- /** The version of the draft overlay manifest format below. */
120
- export const DRAFT_OVERLAY_FORMAT = 1;
121
-
122
- /**
123
- * A draft overlay manifest (see /next/content-delivery#exact-draft-previews):
124
- * the complete, cumulative set of a draft's changes, never a patch over an
125
- * earlier version. `set` maps each changed entry's name to the block hash of
126
- * its JSON; `delete` names the entries the draft removed (tombstones). The two
127
- * are disjoint. There is no base revision: the server rendering the draft layers it over the
128
- * production content it already has.
129
- */
130
- export interface DraftOverlay {
131
- format: typeof DRAFT_OVERLAY_FORMAT;
132
- set: Record<string, string>;
133
- delete: string[];
134
- }
135
-
136
- /**
137
- * The block hash of one changed entry: SHA-256 over its canonical JSON,
138
- * lowercase hex. A draft block asset is stored under it
139
- * (`/sites/<site>/draft-blocks/<block-hash>.json`), and the SDK checks every
140
- * asset it downloads hashes to its name.
141
- */
142
- export function computeBlockHash(entry: unknown): Promise<string> {
143
- return sha256Hex(canonicalJson(entry));
144
- }
145
-
146
- /**
147
- * The overlay version: SHA-256 over the manifest's canonical JSON, lowercase
148
- * hex. The manifest is stored under it (`/sites/<site>/drafts/<version>.json`)
149
- * and a draft pointer names it after its `@`.
150
- */
151
- export function computeOverlayVersion(overlay: DraftOverlay): Promise<string> {
152
- return sha256Hex(canonicalJson(overlay));
153
- }
@@ -20,6 +20,7 @@
20
20
  import fs from "node:fs";
21
21
  import { Ajv, type ValidateFunction } from "ajv";
22
22
  import { isWellFormedCiphertext } from "../../../protocol/secrets.ts";
23
+ import { BLOCKS_MAJOR } from "../../../protocol/types.ts";
23
24
  import { SETTINGS_BLOCK, SETTINGS_TYPE } from "../../builtins/data.ts";
24
25
  import { isBlock, own } from "../../json.ts";
25
26
  import { findRouteConflicts } from "../../matchRoute.ts";
@@ -767,11 +768,34 @@ function readSchemaFile(file: string): DecoMeta {
767
768
  } catch {
768
769
  throw new CliError(`no ${file}; run deco schema first`);
769
770
  }
771
+ let meta: DecoMeta;
770
772
  try {
771
- return JSON.parse(text) as DecoMeta;
773
+ meta = JSON.parse(text) as DecoMeta;
772
774
  } catch (error) {
773
775
  throw new CliError(`${file}: invalid JSON: ${(error as Error).message}`);
774
776
  }
777
+ assertBlocksMajor(meta, file);
778
+ return meta;
779
+ }
780
+
781
+ /**
782
+ * A schema must declare `"blocksMajor": 8`: the site editor treats a site as
783
+ * v8 only on that field, so a schema without it would edit as a v7 site.
784
+ */
785
+ export function assertBlocksMajor(meta: unknown, file: string): void {
786
+ const found =
787
+ typeof meta === "object" && meta !== null && !Array.isArray(meta)
788
+ ? (meta as { blocksMajor?: unknown }).blocksMajor
789
+ : undefined;
790
+ if (found === BLOCKS_MAJOR) return;
791
+ const what =
792
+ found === undefined
793
+ ? 'has no top-level "blocksMajor"'
794
+ : `has "blocksMajor": ${JSON.stringify(found)}`;
795
+ throw new CliError(
796
+ `${file} ${what}; expected "blocksMajor": ${BLOCKS_MAJOR}. ` +
797
+ "It was written by an older or different deco schema: run deco schema to regenerate it, then commit it.",
798
+ );
775
799
  }
776
800
 
777
801
  /** `deco check`. Returns the exit code: 0 when everything fits (warnings aside), 1 otherwise. */
package/src/v8/cli/run.ts CHANGED
@@ -42,7 +42,7 @@ Commands:
42
42
  schema turn the types in .deco/index.ts into .deco/schema.gen.json
43
43
  content turn .deco/blocks into the content module, .deco/blocks.gen.ts
44
44
  check check that every saved block fits the schema (writes nothing)
45
- serve serve .deco to the site editor on this machine
45
+ serve serve .deco to the site editor on this machine, at http://localhost:4545/rpc
46
46
 
47
47
  ${Object.values(COMMANDS)
48
48
  .map((c) => ` ${c.usage}`)
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import fs from "node:fs";
14
14
  import path from "node:path";
15
- import { SCHEMA_FORMAT } from "../../../protocol/types.ts";
15
+ import { BLOCKS_MAJOR, SCHEMA_FORMAT } from "../../../protocol/types.ts";
16
16
  import { BUILT_IN_BLOCKS, LEGACY_ALIASES } from "../builtins.ts";
17
17
  import { CliError, type DecoPaths, packageVersion } from "../root.ts";
18
18
  import {
@@ -51,6 +51,8 @@ type ManifestEntry = { $ref: string; namespace: string };
51
51
 
52
52
  export interface DecoMeta {
53
53
  major: 1;
54
+ /** The Blocks major that generated this schema; `deco check` requires it. */
55
+ blocksMajor: typeof BLOCKS_MAJOR;
54
56
  version: string;
55
57
  namespace: string;
56
58
  site: string;
@@ -424,6 +426,7 @@ export async function generateSchema(paths: DecoPaths): Promise<SchemaResult> {
424
426
 
425
427
  const meta: DecoMeta = {
426
428
  major: 1,
429
+ blocksMajor: BLOCKS_MAJOR,
427
430
  version: packageVersion(),
428
431
  namespace: "site",
429
432
  site: siteName(paths.root),
@@ -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
@@ -141,17 +141,16 @@ class CMSInstance {
141
141
  }
142
142
 
143
143
  /**
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.
144
+ * The draft, with the variants the pointer forces (even for a `local`
145
+ * pointer, which names no draft). A draft client is a production client
146
+ * reading a draft pointer, so it schedules the release check like any other.
147
147
  */
148
148
  forDraft(blocks: Blocks, pointer: string): Client {
149
149
  this.#scheduleUpdate();
150
+ const load = () => this.#store.draft(pointer);
150
151
  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
- );
152
+ if (variants === undefined) return this.#client(blocks, load);
153
+ return this.#client(blocks, () => load().then((snapshot) => forceVariants(snapshot, variants)));
155
154
  }
156
155
 
157
156
  forRevision(blocks: Blocks, revision: string): Client {
@@ -366,7 +365,7 @@ export function resetForTests(): void {
366
365
  setCurrentTelemetry(undefined);
367
366
  }
368
367
 
369
- /** With `site` and `token`, the content is the fallback of hosted releases and drafts. */
368
+ /** With `site` and `token`, the content is the fallback of hosted releases. */
370
369
  function contentOf(config: CMSConfig): Snapshot | Loader {
371
370
  if (!config.site || !config.token) return config.content;
372
371
  return remoteLoader(config.content, { site: config.site, token: config.token });