@decocms/blocks 8.0.0 → 8.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. package/tsconfig.json +0 -7
@@ -0,0 +1,168 @@
1
+ /**
2
+ * `describe`, `schema.get` and `blocks.list`, including conditional reads.
3
+ */
4
+ import { ErrorCode } from "../../errors";
5
+ import { PROTOCOL_NAME, SCHEMA_FORMAT } from "../../types";
6
+ import { assert, assertEqual, expectError } from "../context";
7
+ import type { ConformanceCase } from "./types";
8
+
9
+ const LIMIT_KEYS = [
10
+ "maxOpsPerApply",
11
+ "maxBlockBytes",
12
+ "maxRequestBytes",
13
+ "maxListBytes",
14
+ "maxSchemaBytes",
15
+ "maxBatchResponseBytes",
16
+ ] as const;
17
+
18
+ export const readCases: ConformanceCase[] = [
19
+ {
20
+ id: "describe/shape",
21
+ title: "describe reports the protocol, its version, kind, root, limits and features",
22
+ async run(ctx) {
23
+ const d = await ctx.client.describe();
24
+ assertEqual(d.protocol, PROTOCOL_NAME, "protocol");
25
+ assertEqual(d.version.major, 1, "version.major");
26
+ assert(Number.isInteger(d.version.minor) && d.version.minor >= 0, "version.minor");
27
+ assert(typeof d.server?.name === "string" && typeof d.server?.version === "string", "server");
28
+ assert(d.kind === "working-tree" || d.kind === "git", `kind ${String(d.kind)}`);
29
+ assert(typeof d.readOnly === "boolean", "readOnly");
30
+ assert(typeof d.root === "string" && !d.root.startsWith("/"), "root is relative");
31
+ assertEqual(d.schemaFormat, SCHEMA_FORMAT, "schemaFormat");
32
+ assert(d.refs === null || typeof d.refs.default === "string", "refs");
33
+ assert(
34
+ d.writes.idempotency === null || d.writes.idempotency.retentionMs > 0,
35
+ "writes.idempotency",
36
+ );
37
+ assert(typeof d.writes.schemaPreconditions === "boolean", "writes.schemaPreconditions");
38
+ assert(d.pollIntervalMs > 0, "pollIntervalMs");
39
+ for (const key of LIMIT_KEYS) assert(d.limits[key] > 0, `limits.${key}`);
40
+ assert(
41
+ d.preview === null || /^https?:\/\//.test(String(d.preview?.url)),
42
+ "preview is null or { url } with an http(s) URL",
43
+ );
44
+ if (d.readOnly) assertEqual(d.assets, null, "assets is null when read-only");
45
+ if (d.assets) {
46
+ assertEqual(d.assets.urlPrefix, "/assets/", "assets.urlPrefix");
47
+ assert(d.assets.maxBytes > 0 && typeof d.assets.dir === "string", "assets");
48
+ }
49
+ assert(d.secrets === null || typeof d.secrets.publicKey === "string", "secrets");
50
+ },
51
+ },
52
+ {
53
+ id: "describe/secrets",
54
+ title: "describe returns the committed public key for secrets",
55
+ async run(ctx) {
56
+ const expected = ctx.options.secretsPublicKey;
57
+ if (expected === undefined) return ctx.skip("no secretsPublicKey fixture");
58
+ const d = await ctx.client.describe();
59
+ assertEqual(d.secrets, { publicKey: expected }, "describe.secrets");
60
+ },
61
+ },
62
+ {
63
+ id: "schema/read",
64
+ title: "schema.get returns the schema and a version, and 'not modified' for that version",
65
+ async run(ctx) {
66
+ if (ctx.options.hasSchema === false) {
67
+ await expectError(ctx.client.schemaGet(), ErrorCode.NotFound, "no schema");
68
+ return;
69
+ }
70
+ const first = await ctx.client.schemaGet();
71
+ assert(!first.notModified, "the first read returns the schema");
72
+ assert(typeof first.version === "string" && first.version.length > 0, "a version");
73
+ assert(typeof first.schema === "object" && first.schema !== null, "a schema object");
74
+ const again = await ctx.client.schemaGet({ ifNoneMatch: first.version });
75
+ assertEqual(again, { notModified: true, version: first.version }, "the conditional read");
76
+ const stale = await ctx.client.schemaGet({ ifNoneMatch: `${first.version}-stale` });
77
+ assert(!stale.notModified, "another version returns the schema");
78
+ },
79
+ },
80
+ {
81
+ id: "list/read",
82
+ title: "blocks.list returns every entry with versions, and 'not modified' for its revision",
83
+ async run(ctx) {
84
+ const first = await ctx.client.blocksList();
85
+ assert(!first.notModified, "the first read returns the map");
86
+ assert(typeof first.revision === "string" && first.revision.length > 0, "a revision");
87
+ assert(Array.isArray(first.diagnostics), "diagnostics");
88
+ assertEqual(
89
+ Object.keys(first.versions).sort(),
90
+ Object.keys(first.blocks).sort(),
91
+ "one version per entry",
92
+ );
93
+ const d = await ctx.describe();
94
+ if (d.refs === null) assertEqual(first.resolvedRef, null, "resolvedRef without refs");
95
+ const again = await ctx.client.blocksList({ ifNoneMatch: first.revision });
96
+ assertEqual(
97
+ again,
98
+ { notModified: true, revision: first.revision, resolvedRef: first.resolvedRef },
99
+ "the conditional read",
100
+ );
101
+ },
102
+ },
103
+ {
104
+ id: "list/poll-batch",
105
+ title: "one batched poll reads the schema and the blocks conditionally",
106
+ async run(ctx) {
107
+ const list = await ctx.client.blocksList();
108
+ const calls = [{ method: "blocks.list" as const, params: { ifNoneMatch: list.revision } }];
109
+ const outcomes = await ctx.client.batch(
110
+ ctx.options.hasSchema === false
111
+ ? calls
112
+ : [
113
+ {
114
+ method: "schema.get" as const,
115
+ params: { ifNoneMatch: (await ctx.client.schemaGet()).version },
116
+ },
117
+ ...calls,
118
+ ],
119
+ );
120
+ for (const outcome of outcomes) {
121
+ assert(outcome.ok, "every poll call succeeds");
122
+ assert((outcome.result as { notModified: boolean }).notModified, "nothing changed");
123
+ }
124
+ },
125
+ },
126
+ {
127
+ id: "refs/unsupported",
128
+ title: "a ref on an endpoint without branches is Unsupported",
129
+ async run(ctx) {
130
+ const d = await ctx.describe();
131
+ if (d.refs !== null) return ctx.skip("the endpoint has branches");
132
+ await expectError(
133
+ ctx.client.blocksList({ ref: "main" }),
134
+ ErrorCode.Unsupported,
135
+ "blocks.list ref",
136
+ );
137
+ await expectError(
138
+ ctx.client.schemaGet({ ref: "main" }),
139
+ ErrorCode.Unsupported,
140
+ "schema.get ref",
141
+ );
142
+ if (!d.readOnly) {
143
+ await expectError(
144
+ ctx.client.blocksApply({ ref: "main", delete: [ctx.name()] }),
145
+ ErrorCode.Unsupported,
146
+ "blocks.apply ref",
147
+ );
148
+ }
149
+ },
150
+ },
151
+ {
152
+ id: "auth/token",
153
+ title: "a missing or wrong bearer token is HTTP 401 with Unauthorized",
154
+ async run(ctx) {
155
+ if (ctx.options.token === undefined) return ctx.skip("the endpoint has no token");
156
+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "describe" });
157
+ for (const authorization of ["", "Bearer wrong-token"]) {
158
+ const response = await ctx.raw(body, { headers: { authorization } });
159
+ assertEqual(response.status, 401, `HTTP status with "${authorization}"`);
160
+ assertEqual(
161
+ (response.body as { error?: { code: number } }).error?.code,
162
+ ErrorCode.Unauthorized,
163
+ "the error code",
164
+ );
165
+ }
166
+ },
167
+ },
168
+ ];
@@ -0,0 +1,9 @@
1
+ import type { ConformanceContext } from "../context";
2
+
3
+ /** One black-box check of a content-protocol endpoint. */
4
+ export interface ConformanceCase {
5
+ /** A stable id, such as `apply/atomic`. */
6
+ id: string;
7
+ title: string;
8
+ run(ctx: ConformanceContext): Promise<void>;
9
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The wire format: JSON-RPC 2.0 envelopes, batches, HTTP status codes, gzip.
3
+ */
4
+ import { ErrorCode } from "../../errors";
5
+ import { MAX_BATCH_CALLS } from "../../types";
6
+ import { assert, assertEqual, rawErrorCode } from "../context";
7
+ import type { ConformanceCase } from "./types";
8
+
9
+ const req = (id: unknown, method: string, params?: unknown) =>
10
+ params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
11
+
12
+ export const wireCases: ConformanceCase[] = [
13
+ {
14
+ id: "wire/ids-echoed",
15
+ title: "string and number ids are echoed back",
16
+ async run(ctx) {
17
+ const a = await ctx.rpc(req("abc", "describe", {}));
18
+ assert(a.status === 200, `HTTP ${a.status}`);
19
+ assertEqual((a.body as { id: unknown }).id, "abc", "the string id");
20
+ const b = await ctx.rpc(req(42, "describe"));
21
+ assertEqual((b.body as { id: unknown }).id, 42, "the number id");
22
+ assert("result" in (b.body as object), "describe without params succeeds");
23
+ },
24
+ },
25
+ {
26
+ id: "wire/id-required",
27
+ title: "a request without an id is rejected, not run",
28
+ async run(ctx) {
29
+ const response = await ctx.rpc({ jsonrpc: "2.0", method: "describe" });
30
+ assert(response.status === 200, `HTTP ${response.status}`);
31
+ assertEqual(rawErrorCode(response.body), ErrorCode.InvalidRequest, "the error code");
32
+ assertEqual((response.body as { id: unknown }).id, null, "the error id");
33
+ },
34
+ },
35
+ {
36
+ id: "wire/envelope",
37
+ title: "a bad envelope is Invalid Request; an unknown method is Method not found",
38
+ async run(ctx) {
39
+ const wrongVersion = await ctx.rpc({ jsonrpc: "1.0", id: 1, method: "describe" });
40
+ assertEqual(rawErrorCode(wrongVersion.body), ErrorCode.InvalidRequest, "jsonrpc 1.0");
41
+ const unknown = await ctx.rpc(req(1, "blocks.rename", {}));
42
+ assertEqual(rawErrorCode(unknown.body), ErrorCode.MethodNotFound, "an unknown method");
43
+ const arrayParams = await ctx.rpc(req(1, "describe", []));
44
+ assertEqual(rawErrorCode(arrayParams.body), ErrorCode.InvalidParams, "array params");
45
+ const unknownParam = await ctx.rpc(req(1, "blocks.list", { since: "x" }));
46
+ assertEqual(rawErrorCode(unknownParam.body), ErrorCode.InvalidParams, "an unknown parameter");
47
+ },
48
+ },
49
+ {
50
+ id: "wire/parse-error",
51
+ title: "malformed JSON is a Parse error",
52
+ async run(ctx) {
53
+ const response = await ctx.raw("{not json");
54
+ assert(response.status === 200, `HTTP ${response.status}`);
55
+ assertEqual(rawErrorCode(response.body), ErrorCode.ParseError, "the error code");
56
+ },
57
+ },
58
+ {
59
+ id: "wire/content-type",
60
+ title: "only JSON bodies and POST are accepted",
61
+ async run(ctx) {
62
+ const form = await ctx.raw("a=1", {
63
+ headers: { "content-type": "application/x-www-form-urlencoded" },
64
+ });
65
+ assert(form.status >= 400, `a form post answered HTTP ${form.status}`);
66
+ const get = await ctx.raw("", { method: "GET" });
67
+ assert(get.status >= 400, `a GET answered HTTP ${get.status}`);
68
+ },
69
+ },
70
+ {
71
+ id: "wire/batch-order",
72
+ title: "a batch runs in order and returns results in order",
73
+ async run(ctx) {
74
+ const response = await ctx.rpc([
75
+ req(1, "describe"),
76
+ req(2, "nope"),
77
+ req("three", "blocks.list", {}),
78
+ ]);
79
+ assert(Array.isArray(response.body), "a batch answers with an array");
80
+ const items = response.body as Array<{ id: unknown; error?: { code: number } }>;
81
+ assertEqual(
82
+ items.map((i) => i.id),
83
+ [1, 2, "three"],
84
+ "the response ids",
85
+ );
86
+ assert(!items[0].error, "the first call succeeds");
87
+ assertEqual(items[1].error?.code, ErrorCode.MethodNotFound, "the second call fails alone");
88
+ assert(!items[2].error, "the third call still runs");
89
+ },
90
+ },
91
+ {
92
+ id: "wire/batch-limits",
93
+ title: `an empty batch is invalid; more than ${MAX_BATCH_CALLS} calls is LimitExceeded`,
94
+ async run(ctx) {
95
+ const empty = await ctx.rpc([]);
96
+ assertEqual(rawErrorCode(empty.body), ErrorCode.InvalidRequest, "an empty batch");
97
+ const calls = Array.from({ length: MAX_BATCH_CALLS + 1 }, (_, i) => req(i + 1, "describe"));
98
+ const tooMany = await ctx.rpc(calls);
99
+ assertEqual(rawErrorCode(tooMany.body), ErrorCode.LimitExceeded, "an oversized batch");
100
+ const ok = await ctx.rpc(calls.slice(0, MAX_BATCH_CALLS));
101
+ assert(
102
+ Array.isArray(ok.body) && ok.body.length === MAX_BATCH_CALLS,
103
+ `a batch of ${MAX_BATCH_CALLS} runs`,
104
+ );
105
+ },
106
+ },
107
+ {
108
+ id: "wire/batch-not-atomic",
109
+ title: "a batch isn't atomic: a failed write doesn't undo an earlier one",
110
+ async run(ctx) {
111
+ const description = await ctx.describe();
112
+ if (description.readOnly) return ctx.skip("read-only endpoint");
113
+ const good = ctx.name("batch");
114
+ const response = await ctx.rpc([
115
+ req(1, "blocks.apply", { set: { [good]: { title: "kept" } } }),
116
+ req(2, "blocks.apply", { set: { [ctx.name("bad")]: [] } }),
117
+ ]);
118
+ const items = response.body as Array<{ error?: { code: number } }>;
119
+ assert(!items[0].error, "the first write succeeds");
120
+ assertEqual(items[1].error?.code, ErrorCode.InvalidBlock, "the second write fails");
121
+ const list = await ctx.client.blocksList();
122
+ assert(!list.notModified && good in list.blocks, "the first write landed");
123
+ },
124
+ },
125
+ {
126
+ id: "wire/gzip",
127
+ title: "responses are gzip-compressed when the request accepts it",
128
+ async run(ctx) {
129
+ const description = await ctx.describe();
130
+ if (description.readOnly) return ctx.skip("read-only endpoint");
131
+ const name = ctx.name("gzip");
132
+ await ctx.client.blocksApply({ set: { [name]: { text: "x".repeat(8 * 1024) } } });
133
+ const response = await ctx.rpc(req(1, "blocks.list", {}), { "accept-encoding": "gzip" });
134
+ assertEqual(response.headers.get("content-encoding"), "gzip", "Content-Encoding");
135
+ assert(rawErrorCode(response.body) === undefined, "the gzip body decodes to a result");
136
+ },
137
+ },
138
+ ];
@@ -0,0 +1,345 @@
1
+ /**
2
+ * `blocks.apply`: atomic set and delete, set precedence, validation, the
3
+ * file-name rule and preconditions.
4
+ */
5
+ import { ErrorCode, type InvalidBlockData } from "../../errors";
6
+ import type { BlocksListResult } from "../../types";
7
+ import { assert, assertEqual, type ConformanceContext, expectError } from "../context";
8
+ import type { ConformanceCase } from "./types";
9
+
10
+ type FullList = Extract<BlocksListResult, { notModified: false }>;
11
+
12
+ async function list(ctx: ConformanceContext): Promise<FullList> {
13
+ const result = await ctx.client.blocksList();
14
+ assert(!result.notModified, "an unconditional list returns the map");
15
+ return result;
16
+ }
17
+
18
+ async function writable(ctx: ConformanceContext) {
19
+ const d = await ctx.describe();
20
+ if (d.readOnly) return ctx.skip("read-only endpoint");
21
+ return d;
22
+ }
23
+
24
+ function violations(error: { data: unknown }): InvalidBlockData["violations"] {
25
+ const data = error.data as InvalidBlockData | undefined;
26
+ assert(Array.isArray(data?.violations), "InvalidBlock carries data.violations");
27
+ return data!.violations;
28
+ }
29
+
30
+ export const writeCases: ConformanceCase[] = [
31
+ {
32
+ id: "apply/create-and-read",
33
+ title: "a write returns versions and a revision that blocks.list then reports",
34
+ async run(ctx) {
35
+ await writable(ctx);
36
+ const name = ctx.name("create");
37
+ const value = { __resolveType: "hero", title: "Olá — 世界", items: [1, { a: null }] };
38
+ const result = await ctx.client.blocksApply({ set: { [name]: value } });
39
+ assert(typeof result.revision === "string", "a revision");
40
+ assert(typeof result.versions[name] === "string", "a version for the entry");
41
+ const after = await list(ctx);
42
+ assertEqual(after.blocks[name], value, "the stored entry");
43
+ assertEqual(after.versions[name], result.versions[name], "the listed version");
44
+ assertEqual(after.revision, result.revision, "the listed revision");
45
+ const poll = await ctx.client.blocksList({ ifNoneMatch: result.revision });
46
+ assert(poll.notModified, "polling with the returned revision is 'not modified'");
47
+ },
48
+ },
49
+ {
50
+ id: "apply/atomic-set-delete",
51
+ title: "set and delete land together",
52
+ async run(ctx) {
53
+ await writable(ctx);
54
+ const [a, b, c] = [ctx.name("a"), ctx.name("b"), ctx.name("c")];
55
+ await ctx.client.blocksApply({ set: { [a]: { v: 1 }, [b]: { v: 2 } } });
56
+ const result = await ctx.client.blocksApply({ set: { [c]: { v: 3 } }, delete: [a] });
57
+ assertEqual(result.versions[a], null, "a deleted entry's version is null");
58
+ const after = await list(ctx);
59
+ assert(!(a in after.blocks), "the deleted entry is gone");
60
+ assertEqual(after.blocks[b], { v: 2 }, "the untouched entry stays");
61
+ assertEqual(after.blocks[c], { v: 3 }, "the new entry exists");
62
+ },
63
+ },
64
+ {
65
+ id: "apply/set-wins",
66
+ title: "set wins when a name is in both set and delete",
67
+ async run(ctx) {
68
+ await writable(ctx);
69
+ const name = ctx.name("both");
70
+ const result = await ctx.client.blocksApply({
71
+ set: { [name]: { kept: true } },
72
+ delete: [name],
73
+ });
74
+ assert(typeof result.versions[name] === "string", "the entry has a version");
75
+ assertEqual((await list(ctx)).blocks[name], { kept: true }, "the entry exists");
76
+ },
77
+ },
78
+ {
79
+ id: "apply/delete-missing",
80
+ title: "deleting a missing name counts as deleted",
81
+ async run(ctx) {
82
+ await writable(ctx);
83
+ const name = ctx.name("missing");
84
+ const result = await ctx.client.blocksApply({ delete: [name] });
85
+ assertEqual(result.versions, { [name]: null }, "versions");
86
+ },
87
+ },
88
+ {
89
+ id: "apply/whole-entry-replace",
90
+ title: "set replaces the whole entry (no merge)",
91
+ async run(ctx) {
92
+ await writable(ctx);
93
+ const name = ctx.name("replace");
94
+ await ctx.client.blocksApply({ set: { [name]: { a: 1, b: 2 } } });
95
+ await ctx.client.blocksApply({ set: { [name]: { b: 3 } } });
96
+ assertEqual((await list(ctx)).blocks[name], { b: 3 }, "the entry");
97
+ },
98
+ },
99
+ {
100
+ id: "apply/all-or-nothing-validation",
101
+ title: "every violation is reported at once and nothing is written",
102
+ async run(ctx) {
103
+ await writable(ctx);
104
+ const good = ctx.name("good");
105
+ const error = await expectError(
106
+ ctx.client.blocksApply({
107
+ set: {
108
+ [good]: { ok: true },
109
+ [ctx.name("array")]: [] as never,
110
+ [ctx.name("null")]: null as never,
111
+ },
112
+ }),
113
+ ErrorCode.InvalidBlock,
114
+ "invalid values",
115
+ );
116
+ assertEqual(violations(error).length, 2, "one violation per invalid entry");
117
+ assert(!(good in (await list(ctx)).blocks), "the valid entry wasn't written");
118
+ },
119
+ },
120
+ {
121
+ id: "apply/name-rules",
122
+ title: "names the site editor can't save are refused",
123
+ async run(ctx) {
124
+ await writable(ctx);
125
+ const p = ctx.prefix;
126
+ const bad = [
127
+ "",
128
+ `${p}\\x`,
129
+ `${p}..x`,
130
+ "CON",
131
+ "con.backup",
132
+ "__proto__",
133
+ `${p}-mod.ts`,
134
+ `${p}-mod.tsx`,
135
+ `.${p}-hidden`,
136
+ ".",
137
+ ];
138
+ bad.push(`${p}-${"é".repeat(60)}`); // 360 encoded bytes
139
+ for (const name of bad) {
140
+ const error = await expectError(
141
+ ctx.client.blocksApply({ set: { [name]: { x: 1 } } }),
142
+ ErrorCode.InvalidBlock,
143
+ `the name ${JSON.stringify(name)}`,
144
+ );
145
+ assert(
146
+ violations(error).some((v) => v.name === name),
147
+ `a violation names ${JSON.stringify(name)}`,
148
+ );
149
+ }
150
+ // A name ending in a source extension can still be deleted.
151
+ const result = await ctx.client.blocksApply({ delete: [`${p}-mod.ts`] });
152
+ assertEqual(result.versions, { [`${p}-mod.ts`]: null }, "deleting a .ts name");
153
+ },
154
+ },
155
+ {
156
+ id: "apply/case-collision",
157
+ title: "a new name that differs from another entry's only in letter case is refused",
158
+ async run(ctx) {
159
+ await writable(ctx);
160
+ const name = ctx.name("CaseName");
161
+ await ctx.client.blocksApply({ set: { [name]: { v: 1 } } });
162
+ await expectError(
163
+ ctx.client.blocksApply({ set: { [name.toLowerCase()]: { v: 2 } } }),
164
+ ErrorCode.InvalidBlock,
165
+ "a case variant",
166
+ );
167
+ await ctx.client.blocksApply({ set: { [name]: { v: 3 } } });
168
+ assertEqual((await list(ctx)).blocks[name], { v: 3 }, "updating the existing name");
169
+ },
170
+ },
171
+ {
172
+ id: "apply/spellings",
173
+ title:
174
+ "two spellings of one name are one entry: guards see either, and a write keeps only the written spelling",
175
+ async run(ctx) {
176
+ await writable(ctx);
177
+ const encoded = `${ctx.prefix}-Home%20Page`;
178
+ const literal = `${ctx.prefix}-Home Page`;
179
+ ctx.track(encoded);
180
+ ctx.track(literal);
181
+ await expectError(
182
+ ctx.client.blocksApply({ set: { [encoded]: { v: 1 }, [literal]: { v: 2 } } }),
183
+ ErrorCode.InvalidBlock,
184
+ "both spellings in one write",
185
+ );
186
+ const created = await ctx.client.blocksApply({ set: { [encoded]: { v: 1 } } });
187
+ // Create-only under another spelling: the entry exists, so the guard fails.
188
+ const error = await expectError(
189
+ ctx.client.blocksApply({ set: { [literal]: { v: 2 } }, ifMatch: { [literal]: null } }),
190
+ ErrorCode.Conflict,
191
+ "create-only on another spelling of an existing entry",
192
+ );
193
+ assertEqual(
194
+ (error.data as { entries?: unknown }).entries,
195
+ { [literal]: { expected: null, actual: created.versions[encoded] } },
196
+ "the conflict reports the existing spelling's version",
197
+ );
198
+ assertEqual((await list(ctx)).blocks[encoded], { v: 1 }, "nothing was deleted");
199
+ // A guard on one spelling holds for the other.
200
+ const written = await ctx.client.blocksApply({
201
+ set: { [literal]: { v: 2 } },
202
+ ifMatch: { [literal]: created.versions[encoded]! },
203
+ });
204
+ assertEqual(
205
+ written.versions[encoded],
206
+ null,
207
+ "the result reports the deleted spelling as gone, so a client's map drops it",
208
+ );
209
+ assert(typeof written.versions[literal] === "string", "the written spelling has a version");
210
+ const after = await list(ctx);
211
+ assertEqual(after.blocks[literal], { v: 2 }, "the written spelling");
212
+ assert(!(encoded in after.blocks), "the other spelling was deleted in the same commit");
213
+ assert(
214
+ !after.diagnostics.some((d) => d.name === literal || d.name === encoded),
215
+ "no shadowed spelling is left",
216
+ );
217
+ },
218
+ },
219
+ {
220
+ id: "apply/if-match",
221
+ title: "ifMatch guards a write; a failed guard writes nothing and reports versions",
222
+ async run(ctx) {
223
+ await writable(ctx);
224
+ const name = ctx.name("guarded");
225
+ const other = ctx.name("other");
226
+ const created = await ctx.client.blocksApply({
227
+ set: { [name]: { v: 1 } },
228
+ ifMatch: { [name]: null },
229
+ });
230
+ const v1 = created.versions[name]!;
231
+ const error = await expectError(
232
+ ctx.client.blocksApply({
233
+ set: { [name]: { v: 2 }, [other]: { v: 2 } },
234
+ ifMatch: { [name]: `${v1}x` },
235
+ }),
236
+ ErrorCode.Conflict,
237
+ "a stale version",
238
+ );
239
+ assertEqual(
240
+ (error.data as { entries?: unknown }).entries,
241
+ { [name]: { expected: `${v1}x`, actual: v1 } },
242
+ "the conflict's versions",
243
+ );
244
+ const after = await list(ctx);
245
+ assertEqual(after.blocks[name], { v: 1 }, "the guarded entry is unchanged");
246
+ assert(!(other in after.blocks), "nothing else was written");
247
+ await expectError(
248
+ ctx.client.blocksApply({ set: { [name]: { v: 3 } }, ifMatch: { [name]: null } }),
249
+ ErrorCode.Conflict,
250
+ "create-only on an existing entry",
251
+ );
252
+ const updated = await ctx.client.blocksApply({
253
+ set: { [name]: { v: 4 } },
254
+ ifMatch: { [name]: v1 },
255
+ });
256
+ assert(updated.versions[name] !== v1, "a matching version writes");
257
+ },
258
+ },
259
+ {
260
+ id: "apply/rename-recipe",
261
+ title: "renaming is a set plus a delete, create-only on the new name",
262
+ async run(ctx) {
263
+ await writable(ctx);
264
+ const from = ctx.name("from");
265
+ const to = ctx.name("to");
266
+ const created = await ctx.client.blocksApply({ set: { [from]: { v: 1 } } });
267
+ await ctx.client.blocksApply({
268
+ set: { [to]: { v: 1 } },
269
+ delete: [from],
270
+ ifMatch: { [to]: null, [from]: created.versions[from]! },
271
+ });
272
+ const after = await list(ctx);
273
+ assert(!(from in after.blocks) && to in after.blocks, "the entry moved");
274
+ },
275
+ },
276
+ {
277
+ id: "apply/schema-precondition",
278
+ title: "ifSchemaMatch rejects a write when the schema changed",
279
+ async run(ctx) {
280
+ const d = await writable(ctx);
281
+ const name = ctx.name("schema-guarded");
282
+ if (!d.writes.schemaPreconditions) {
283
+ await expectError(
284
+ ctx.client.blocksApply({ set: { [name]: {} }, ifSchemaMatch: "x" }),
285
+ ErrorCode.Unsupported,
286
+ "an unadvertised guard",
287
+ );
288
+ return;
289
+ }
290
+ if (ctx.options.hasSchema === false) return ctx.skip("no schema");
291
+ const { version } = await ctx.client.schemaGet();
292
+ const error = await expectError(
293
+ ctx.client.blocksApply({ set: { [name]: {} }, ifSchemaMatch: `${version}-old` }),
294
+ ErrorCode.Conflict,
295
+ "a stale schema version",
296
+ );
297
+ assertEqual(
298
+ (error.data as { schema?: unknown }).schema,
299
+ { expected: `${version}-old`, actual: version },
300
+ "the conflict's schema versions",
301
+ );
302
+ assert(!(name in (await list(ctx)).blocks), "nothing was written");
303
+ await ctx.client.blocksApply({ set: { [name]: {} }, ifSchemaMatch: version });
304
+ },
305
+ },
306
+ {
307
+ id: "apply/unknown-params",
308
+ title: "an unknown parameter is refused, so an unknown guard never becomes an unguarded write",
309
+ async run(ctx) {
310
+ await writable(ctx);
311
+ const name = ctx.name("unknown-param");
312
+ await expectError(
313
+ ctx.client.call("blocks.apply", { set: { [name]: {} }, ifUnmodifiedSince: "x" } as never),
314
+ ErrorCode.InvalidParams,
315
+ "an unknown guard",
316
+ );
317
+ assert(!(name in (await list(ctx)).blocks), "nothing was written");
318
+ },
319
+ },
320
+ {
321
+ id: "apply/read-only",
322
+ title: "a write to a read-only endpoint is ReadOnly",
323
+ async run(ctx) {
324
+ const d = await ctx.describe();
325
+ if (!d.readOnly) return ctx.skip("the endpoint accepts writes");
326
+ await expectError(ctx.client.blocksApply({ delete: ["x"] }), ErrorCode.ReadOnly, "a write");
327
+ },
328
+ },
329
+ {
330
+ id: "apply/last-writer-wins",
331
+ title: "without guards, the later of two writes wins",
332
+ async run(ctx) {
333
+ await writable(ctx);
334
+ const name = ctx.name("lww");
335
+ await Promise.all([
336
+ ctx.client.blocksApply({ set: { [name]: { from: "a" } } }),
337
+ ctx.client.blocksApply({ set: { [name]: { from: "b" } } }),
338
+ ]);
339
+ const value = (await list(ctx)).blocks[name] as { from: string };
340
+ assert(value.from === "a" || value.from === "b", "one of the writes is stored whole");
341
+ await ctx.client.blocksApply({ set: { [name]: { from: "c" } } });
342
+ assertEqual((await list(ctx)).blocks[name], { from: "c" }, "the latest write");
343
+ },
344
+ },
345
+ ];