@decocms/blocks 7.72.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 (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
package/bin/deco.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ // The `deco` command (spec: internals › How the CLI ships). A small JavaScript
3
+ // file that loads the CLI's TypeScript sources: Bun runs them as they are;
4
+ // under Node, tsx's loader is registered first.
5
+ const entry = new URL("../src/v8/cli/main.ts", import.meta.url);
6
+
7
+ if (typeof globalThis.Bun !== "undefined") {
8
+ await import(entry.href);
9
+ } else {
10
+ const { register } = await import("tsx/esm/api");
11
+ register();
12
+ await import(entry.href);
13
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/blocks",
3
- "version": "7.72.0",
3
+ "version": "8.1.0-next.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24"
@@ -12,13 +12,38 @@
12
12
  "directory": "packages/blocks"
13
13
  },
14
14
  "main": "./src/index.ts",
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "!src/**/*.test.ts",
19
+ "!src/**/*.test.tsx",
20
+ "!src/**/__tests__",
21
+ "!src/**/__fixtures__",
22
+ "!src/**/__conformance__",
23
+ "!src/v8/testFixtures.ts"
24
+ ],
25
+ "bin": {
26
+ "deco": "./bin/deco.js"
27
+ },
15
28
  "exports": {
16
29
  ".": "./src/index.ts",
30
+ "./analytics": "./src/v8/analytics.ts",
17
31
  "./cms": "./src/cms/index.ts",
18
32
  "./cms/client": "./src/cms/client.ts",
19
33
  "./cms/loadDecofileDirectory": "./src/cms/loadDecofileDirectory.ts",
34
+ "./cli": "./src/v8/cli/index.ts",
35
+ "./fetch": "./src/v8/fetch.ts",
20
36
  "./hooks": "./src/hooks/index.ts",
21
37
  "./preview": "./src/preview/index.ts",
38
+ "./protocol": "./src/protocol/index.ts",
39
+ "./protocol/keys": "./src/protocol/keys.ts",
40
+ "./protocol/server": "./src/protocol/server/index.ts",
41
+ "./protocol/storage/fs": {
42
+ "node": "./src/protocol/storage/fs/index.ts",
43
+ "default": "./src/protocol/storage/fs/unsupported.ts"
44
+ },
45
+ "./protocol/conformance": "./src/protocol/conformance/index.ts",
46
+ "./secrets": "./src/v8/secrets.ts",
22
47
  "./types": "./src/types/index.ts",
23
48
  "./types/widgets": "./src/types/widgets.ts",
24
49
  "./setup": "./src/setup.ts",
@@ -103,13 +128,17 @@
103
128
  "@opentelemetry/api": "^1.9.1",
104
129
  "@opentelemetry/semantic-conventions": "^1.41.1",
105
130
  "@tanstack/store": "^0.9.1",
131
+ "ajv": "^8.20.0",
106
132
  "clsx": "^2.1.1",
107
133
  "fast-json-patch": "^3.1.0",
108
- "tailwind-merge": "^3.3.1"
134
+ "tailwind-merge": "^3.3.1",
135
+ "tsx": "^4.22.5",
136
+ "zod": "^4.4.3"
109
137
  },
110
138
  "peerDependencies": {
111
139
  "react": "^19.0.0",
112
- "react-dom": "^19.0.0"
140
+ "react-dom": "^19.0.0",
141
+ "typescript": "^5.0.0"
113
142
  },
114
143
  "devDependencies": {
115
144
  "@types/react": "^19.0.0",
package/src/cms/schema.ts CHANGED
@@ -1145,7 +1145,7 @@ export function composeMeta(siteMeta: MetaResponse, options?: ComposeMetaOptions
1145
1145
  const seenLoaderRefs = new Set<string>(loaders.loaderAnyOf.map((r: any) => r.$ref));
1146
1146
  const loaderUnion = [
1147
1147
  ...loaders.loaderAnyOf,
1148
- ...siteLoaderRefs.filter((r) => !seenLoaderRefs.has(r.$ref)),
1148
+ ...siteLoaderRefs.filter((r: { $ref: string }) => !seenLoaderRefs.has(r.$ref)),
1149
1149
  ];
1150
1150
 
1151
1151
  const fwSections = buildFrameworkSections(siteAnyOf, loaderUnion);
@@ -1,3 +1,5 @@
1
+ "use client";
2
+
1
3
  import React, { useEffect } from "react";
2
4
  import { getRequestNonce } from "../sdk/nonce";
3
5
 
@@ -1,3 +1,5 @@
1
+ "use client";
2
+
1
3
  import { useState, useEffect, useCallback, useRef } from "react";
2
4
 
3
5
  /**
package/src/index.ts CHANGED
@@ -6,3 +6,40 @@ export * from "./middleware/index";
6
6
  // granular imports too (see `@decocms/blocks/sdk/logger`, `.../observability`).
7
7
  export { type Logger, type LogLevel, logger, setLogLevel } from "./sdk/logger";
8
8
  export * from "./types/index";
9
+
10
+ // Next major (v8) core SDK. Explicit re-exports shadow the star exports above,
11
+ // so where v7 and v8 share a name (`DraftPointer`, `parseDraftPointer`) the
12
+ // root serves the v8 one; v7's stays reachable at `@decocms/blocks/cms`.
13
+ export {
14
+ type Analytics,
15
+ type Block,
16
+ type BlockFunction,
17
+ type Blocks,
18
+ type Client,
19
+ type CMS,
20
+ type CMSError,
21
+ createCMS,
22
+ DRAFT_COOKIE,
23
+ type DraftPointer,
24
+ draftCookie,
25
+ draftPointer,
26
+ formatDraftPointer,
27
+ type Lazy,
28
+ type ListOptions,
29
+ type Loader,
30
+ type Match,
31
+ matchRoute,
32
+ type Page,
33
+ parseDraftPointer,
34
+ type Redirect,
35
+ type Result,
36
+ type Route,
37
+ remoteLoader,
38
+ resetForTests,
39
+ type Secret,
40
+ type Seo,
41
+ type Snapshot,
42
+ type Telemetry,
43
+ type TelemetryConfig,
44
+ type Variant,
45
+ } from "./v8/index";
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Asset-upload naming rules shared by the asset handler and the storages.
3
+ * Browser-safe.
4
+ */
5
+
6
+ /**
7
+ * Every content type the asset endpoint accepts, with the file extensions a
8
+ * file of that type may have (the first is the one appended to a name
9
+ * without an extension). The stored file's extension decides the type it's
10
+ * served with, so an upload can never pick one the browser would run, such
11
+ * as `.html` or `.js`.
12
+ */
13
+ export const ASSET_TYPES: Readonly<Record<string, readonly string[]>> = {
14
+ "image/png": [".png"],
15
+ "image/jpeg": [".jpg", ".jpeg"],
16
+ "image/webp": [".webp"],
17
+ "image/avif": [".avif"],
18
+ "image/gif": [".gif"],
19
+ "image/x-icon": [".ico"],
20
+ "image/vnd.microsoft.icon": [".ico"],
21
+ "video/mp4": [".mp4"],
22
+ "video/webm": [".webm"],
23
+ "font/woff2": [".woff2"],
24
+ "font/woff": [".woff"],
25
+ "font/ttf": [".ttf"],
26
+ "font/otf": [".otf"],
27
+ "application/font-woff": [".woff"],
28
+ "application/x-font-ttf": [".ttf"],
29
+ "application/vnd.ms-fontobject": [".eot"],
30
+ "application/pdf": [".pdf"],
31
+ };
32
+
33
+ /**
34
+ * SVG can carry scripts, so it runs on the site's origin like HTML would.
35
+ * Accepted only with `allowSvg`.
36
+ */
37
+ export const SVG_ASSET_TYPE = { "image/svg+xml": [".svg"] } as const;
38
+
39
+ export interface AssetTypeOptions {
40
+ /** Accept `image/svg+xml` uploads (default false: SVG can carry scripts). */
41
+ allowSvg?: boolean;
42
+ }
43
+
44
+ const mediaType = (contentType: string | null) =>
45
+ contentType ? contentType.split(";")[0]!.trim().toLowerCase() : "";
46
+
47
+ /** The extensions an upload of `contentType` may have; `null` when the type isn't accepted. */
48
+ export function assetExtensions(
49
+ contentType: string | null,
50
+ options: AssetTypeOptions = {},
51
+ ): readonly string[] | null {
52
+ const type = mediaType(contentType);
53
+ if (Object.hasOwn(ASSET_TYPES, type)) return ASSET_TYPES[type] ?? null;
54
+ if (options.allowSvg && type === "image/svg+xml") return SVG_ASSET_TYPE[type] ?? null;
55
+ return null;
56
+ }
57
+
58
+ /** True when the asset endpoint accepts `contentType`. */
59
+ export function isAcceptedAssetType(
60
+ contentType: string | null,
61
+ options: AssetTypeOptions = {},
62
+ ): boolean {
63
+ return assetExtensions(contentType, options) !== null;
64
+ }
65
+
66
+ /**
67
+ * Fits a sanitized file name to its content type: a name without an
68
+ * extension gets the type's, and the extension is lowercased. Returns `null`
69
+ * when the name's extension doesn't match the type (`evil.html` sent as
70
+ * `image/png`), or the type isn't accepted.
71
+ */
72
+ export function assetNameForType(
73
+ name: string,
74
+ contentType: string | null,
75
+ options: AssetTypeOptions = {},
76
+ ): string | null {
77
+ const extensions = assetExtensions(contentType, options);
78
+ if (!extensions) return null;
79
+ const dot = name.lastIndexOf(".");
80
+ if (dot <= 0) return `${name}${extensions[0]}`;
81
+ const extension = name.slice(dot).toLowerCase();
82
+ return extensions.includes(extension) ? name.slice(0, dot) + extension : null;
83
+ }
84
+
85
+ /**
86
+ * Normalizes an upload's file name: its last path segment, lowercased
87
+ * extension, with anything but letters, digits, `.`, `_` and `-` replaced.
88
+ * Returns `null` when nothing usable is left.
89
+ */
90
+ export function sanitizeAssetName(raw: string): string | null {
91
+ let name: string;
92
+ try {
93
+ name = decodeURIComponent(raw);
94
+ } catch {
95
+ name = raw;
96
+ }
97
+ name = name.split(/[\\/]/).pop() ?? "";
98
+ name = name
99
+ .normalize("NFKD")
100
+ .replace(/[̀-ͯ]/g, "")
101
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
102
+ .replace(/-{2,}/g, "-")
103
+ .replace(/^[.-]+/, "")
104
+ .replace(/-+(\.|$)/g, "$1");
105
+ if (!name || name === "." || name === "..") return null;
106
+ if (name.length > 200) {
107
+ const dot = name.lastIndexOf(".");
108
+ const ext = dot > 0 ? name.slice(dot).slice(0, 16) : "";
109
+ name = name.slice(0, 200 - ext.length) + ext;
110
+ }
111
+ return name;
112
+ }
113
+
114
+ /**
115
+ * The name to try when `name` is taken: a short random suffix before the
116
+ * extension, such as `banner-3f9a2c.jpg`.
117
+ */
118
+ export function suffixedAssetName(name: string): string {
119
+ const suffix = Array.from(crypto.getRandomValues(new Uint8Array(3)), (b) =>
120
+ b.toString(16).padStart(2, "0"),
121
+ ).join("");
122
+ const dot = name.lastIndexOf(".");
123
+ return dot > 0 ? `${name.slice(0, dot)}-${suffix}${name.slice(dot)}` : `${name}-${suffix}`;
124
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Canonical JSON and content hashing. The implementation is a dependency-free
3
+ * leaf module of the SDK (`src/v8/canonical.ts`), because the runtime checks
4
+ * content revisions too; the protocol re-exports it so the CLI, the server
5
+ * and the site editor share one definition.
6
+ */
7
+ export * from "../v8/canonical";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The secret ciphertext format. The implementation is a dependency-free leaf
3
+ * module of the SDK (`src/v8/ciphertext.ts`), where the `secret` built-in
4
+ * decrypts it; the protocol re-exports it for its secret guard.
5
+ */
6
+ export * from "../v8/ciphertext";
@@ -0,0 +1,170 @@
1
+ /**
2
+ * A small content-protocol client: one method per protocol method, plus
3
+ * batches. Uses `fetch`, so it runs in browsers, on Workers and on Node.
4
+ */
5
+ import { ContentProtocolError, ErrorCode, type RpcErrorObject } from "./errors";
6
+ import {
7
+ type DescribeResult,
8
+ type MethodName,
9
+ type Methods,
10
+ PROTOCOL_NAME,
11
+ PROTOCOL_VERSION,
12
+ type RpcId,
13
+ } from "./types";
14
+
15
+ export interface ContentClientOptions {
16
+ /** The endpoint URL, such as `http://127.0.0.1:4545/rpc`. */
17
+ endpoint: string | URL;
18
+ /** Sent as `Authorization: Bearer <token>`. */
19
+ token?: string;
20
+ /** Extra headers on every request. */
21
+ headers?: Record<string, string>;
22
+ /** A fetch implementation (defaults to the global one). */
23
+ fetch?: (input: Request) => Promise<Response>;
24
+ }
25
+
26
+ /** One call of a batch. */
27
+ export type BatchCall = {
28
+ [M in MethodName]: { method: M; params?: Methods[M]["params"] };
29
+ }[MethodName];
30
+
31
+ /** The outcome of one batch call: its result or its error. */
32
+ export type BatchOutcome =
33
+ | { ok: true; result: unknown }
34
+ | { ok: false; error: ContentProtocolError };
35
+
36
+ export interface ContentClient {
37
+ /** Throws Unsupported when the endpoint speaks another protocol or major version. */
38
+ describe(): Promise<Methods["describe"]["result"]>;
39
+ schemaGet(params?: Methods["schema.get"]["params"]): Promise<Methods["schema.get"]["result"]>;
40
+ blocksList(params?: Methods["blocks.list"]["params"]): Promise<Methods["blocks.list"]["result"]>;
41
+ blocksApply(
42
+ params: Methods["blocks.apply"]["params"],
43
+ ): Promise<Methods["blocks.apply"]["result"]>;
44
+ /** Calls one method by name. Throws `ContentProtocolError` on an error response. */
45
+ call<M extends MethodName>(
46
+ method: M,
47
+ params?: Methods[M]["params"],
48
+ ): Promise<Methods[M]["result"]>;
49
+ /** Runs several calls in one request; outcomes come back in order. */
50
+ batch(calls: BatchCall[]): Promise<BatchOutcome[]>;
51
+ }
52
+
53
+ type WireResponse = { id: RpcId | null; result?: unknown; error?: RpcErrorObject };
54
+
55
+ /**
56
+ * Decodes a JSON response body, gunzipping it when a custom fetch (such as an
57
+ * in-process handler) handed back the raw gzip bytes.
58
+ */
59
+ export async function readResponseJson(response: Response): Promise<unknown> {
60
+ let bytes = new Uint8Array(await response.arrayBuffer());
61
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
62
+ const stream = new Blob([bytes as BlobPart])
63
+ .stream()
64
+ .pipeThrough(
65
+ new DecompressionStream("gzip") as unknown as ReadableWritablePair<Uint8Array, Uint8Array>,
66
+ );
67
+ bytes = new Uint8Array(await new Response(stream).arrayBuffer());
68
+ }
69
+ return JSON.parse(new TextDecoder().decode(bytes));
70
+ }
71
+
72
+ /**
73
+ * Refuses an endpoint this client can't speak to: another protocol, or
74
+ * another major version (minors only add, so any minor is fine).
75
+ */
76
+ export function assertSupportedEndpoint(description: DescribeResult): DescribeResult {
77
+ const { protocol, version } = (description ?? {}) as Partial<DescribeResult>;
78
+ if (protocol !== PROTOCOL_NAME) {
79
+ throw new ContentProtocolError(
80
+ ErrorCode.Unsupported,
81
+ `the endpoint speaks ${JSON.stringify(protocol)}, not ${PROTOCOL_NAME}`,
82
+ );
83
+ }
84
+ if (version?.major !== PROTOCOL_VERSION.major) {
85
+ throw new ContentProtocolError(
86
+ ErrorCode.Unsupported,
87
+ `the endpoint speaks ${PROTOCOL_NAME} ${String(version?.major)}.x; this client speaks ${PROTOCOL_VERSION.major}.x`,
88
+ );
89
+ }
90
+ return description;
91
+ }
92
+
93
+ export function createContentClient(options: ContentClientOptions): ContentClient {
94
+ const doFetch = options.fetch ?? ((request: Request) => fetch(request));
95
+ let nextId = 1;
96
+
97
+ async function post(body: unknown): Promise<unknown> {
98
+ const headers: Record<string, string> = {
99
+ "content-type": "application/json",
100
+ accept: "application/json",
101
+ ...options.headers,
102
+ };
103
+ if (options.token !== undefined) headers.authorization = `Bearer ${options.token}`;
104
+ const response = await doFetch(
105
+ new Request(options.endpoint, { method: "POST", headers, body: JSON.stringify(body) }),
106
+ );
107
+ let payload: unknown;
108
+ try {
109
+ payload = await readResponseJson(response);
110
+ } catch {
111
+ throw new ContentProtocolError(
112
+ ErrorCode.Unavailable,
113
+ `the endpoint answered HTTP ${response.status} without a JSON-RPC body`,
114
+ );
115
+ }
116
+ if (!response.ok || (!Array.isArray(payload) && (payload as WireResponse)?.id === null)) {
117
+ const error = (payload as WireResponse)?.error;
118
+ if (error) throw ContentProtocolError.from(error);
119
+ throw new ContentProtocolError(
120
+ ErrorCode.Unavailable,
121
+ `the endpoint answered HTTP ${response.status}`,
122
+ );
123
+ }
124
+ return payload;
125
+ }
126
+
127
+ const call = async <M extends MethodName>(method: M, params?: Methods[M]["params"]) => {
128
+ const id = nextId++;
129
+ const response = (await post({
130
+ jsonrpc: "2.0",
131
+ id,
132
+ method,
133
+ params: params ?? {},
134
+ })) as WireResponse;
135
+ if (response.error) throw ContentProtocolError.from(response.error);
136
+ return response.result as Methods[M]["result"];
137
+ };
138
+
139
+ return {
140
+ call,
141
+ describe: async () => assertSupportedEndpoint(await call("describe")),
142
+ schemaGet: (params) => call("schema.get", params),
143
+ blocksList: (params) => call("blocks.list", params),
144
+ blocksApply: (params) => call("blocks.apply", params),
145
+ async batch(calls) {
146
+ const ids = calls.map(() => nextId++);
147
+ const responses = (await post(
148
+ calls.map((c, i) => ({
149
+ jsonrpc: "2.0",
150
+ id: ids[i],
151
+ method: c.method,
152
+ params: c.params ?? {},
153
+ })),
154
+ )) as WireResponse[];
155
+ const byId = new Map(responses.map((r) => [r.id, r]));
156
+ return ids.map((id): BatchOutcome => {
157
+ const response = byId.get(id);
158
+ if (!response) {
159
+ return {
160
+ ok: false,
161
+ error: new ContentProtocolError(ErrorCode.InternalError, "no response for this call"),
162
+ };
163
+ }
164
+ return response.error
165
+ ? { ok: false, error: ContentProtocolError.from(response.error) }
166
+ : { ok: true, result: response.result };
167
+ });
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Uploads beside the protocol: `PUT /assets/<name>`. These cases run only
3
+ * when the harness passes `assetsEndpoint`.
4
+ */
5
+ import { ErrorCode } from "../../errors";
6
+ import { assert, assertEqual, type ConformanceContext, rawErrorCode } from "../context";
7
+ import type { ConformanceCase } from "./types";
8
+
9
+ /** The smallest PNG header: enough bytes for an upload, never executed. */
10
+ const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
11
+
12
+ async function uploadsAccepted(ctx: ConformanceContext) {
13
+ if (ctx.options.assetsEndpoint === undefined) return ctx.skip("no assetsEndpoint");
14
+ const d = await ctx.describe();
15
+ if (d.readOnly || d.assets === null) return ctx.skip("the endpoint doesn't accept uploads");
16
+ return d;
17
+ }
18
+
19
+ const pathOf = (body: unknown) => (body as { path?: unknown } | null)?.path;
20
+
21
+ export const assetCases: ConformanceCase[] = [
22
+ {
23
+ id: "assets/upload",
24
+ title:
25
+ "an upload answers 201 with /assets/<name>; a taken name gets a suffix, never an overwrite",
26
+ async run(ctx) {
27
+ await uploadsAccepted(ctx);
28
+ const name = `${ctx.prefix}-banner.png`;
29
+ const first = await ctx.upload(name, PNG, "image/png");
30
+ assertEqual(first.status, 201, "HTTP status");
31
+ assertEqual(pathOf(first.body), `/assets/${name}`, "the stored path");
32
+ const second = await ctx.upload(name, PNG, "image/png");
33
+ assertEqual(second.status, 201, "HTTP status of the second upload");
34
+ const path = pathOf(second.body);
35
+ assert(
36
+ typeof path === "string" && path.startsWith("/assets/") && path !== `/assets/${name}`,
37
+ `a taken name gets another name, got ${String(path)}`,
38
+ );
39
+ assert(path.endsWith(".png"), "the suffix goes before the extension");
40
+ },
41
+ },
42
+ {
43
+ id: "assets/content-types",
44
+ title: "uploads refuse non-media types, SVG and an extension that doesn't match the type (415)",
45
+ async run(ctx) {
46
+ await uploadsAccepted(ctx);
47
+ const script = "<script>alert(document.cookie)</script>";
48
+ const refused: Array<[name: string, type: string]> = [
49
+ [`${ctx.prefix}-page.html`, "text/html"],
50
+ [`${ctx.prefix}-evil.html`, "image/png"],
51
+ [`${ctx.prefix}-evil.js`, "image/jpeg"],
52
+ [`${ctx.prefix}-logo.svg`, "image/svg+xml"],
53
+ [`${ctx.prefix}-data.json`, "application/json"],
54
+ ];
55
+ for (const [name, type] of refused) {
56
+ const response = await ctx.upload(name, script, type);
57
+ assertEqual(response.status, 415, `HTTP status of ${name} as ${type}`);
58
+ assertEqual(rawErrorCode(response.body), ErrorCode.InvalidRequest, "the error code");
59
+ }
60
+ },
61
+ },
62
+ {
63
+ id: "assets/read-only",
64
+ title: "an endpoint without uploads refuses them",
65
+ async run(ctx) {
66
+ if (ctx.options.assetsEndpoint === undefined) return ctx.skip("no assetsEndpoint");
67
+ const d = await ctx.describe();
68
+ if (!d.readOnly && d.assets !== null) return ctx.skip("the endpoint accepts uploads");
69
+ const response = await ctx.upload(`${ctx.prefix}-x.png`, PNG, "image/png");
70
+ assert(
71
+ response.status === 403 || response.status === 404,
72
+ `HTTP ${response.status} (expected 403 or 404)`,
73
+ );
74
+ const code = rawErrorCode(response.body);
75
+ assert(
76
+ code === ErrorCode.ReadOnly || code === ErrorCode.Unsupported,
77
+ `error ${String(code)} (expected ReadOnly or Unsupported)`,
78
+ );
79
+ },
80
+ },
81
+ ];