@decocms/blocks 8.0.0 → 8.1.0-next.1

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 (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The shared state of one content handler: its storage, options and caches.
3
+ */
4
+ import { ContentProtocolError, invalidBlock, notFound, unavailable, unsupported } from "../errors";
5
+ import { blockNameFromFile } from "../keys";
6
+ import {
7
+ type ContentStorage,
8
+ type StorageDescription,
9
+ StorageInvalidFileError,
10
+ StorageNotFoundError,
11
+ StorageUnavailableError,
12
+ } from "../storage";
13
+ import { DEFAULT_LIMITS, type DecoMeta, type Limits } from "../types";
14
+ import type { AuthOptions } from "./auth";
15
+ import { BodyCache } from "./bodyCache";
16
+
17
+ export interface ContentHandlerOptions extends AuthOptions {
18
+ /** Reported by `describe`, such as `{ name: "deco-cli", version: "8.0.0" }`. */
19
+ server?: { name: string; version: string };
20
+ /** Lowers the protocol's default limits. Higher values are ignored. */
21
+ limits?: Partial<Limits>;
22
+ /** Overrides the poll interval the storage suggests. */
23
+ pollIntervalMs?: number;
24
+ /** The app the site editor previews, reported by `describe` (`{ url }`). */
25
+ preview?: { url: string } | null;
26
+ /** How many times `blocks.apply` attempts a commit when storage moved meanwhile (default 3). */
27
+ maxCommitAttempts?: number;
28
+ /**
29
+ * The jittered wait before retrying a commit that found storage moved: a
30
+ * random delay in `[minMs, maxMs]`, times the attempt number (default
31
+ * 50–200 ms), so concurrent writers don't retry in lockstep.
32
+ */
33
+ commitRetryDelayMs?: { minMs: number; maxMs: number };
34
+ /** Bytes of parsed entries kept between requests (default 32 MiB). */
35
+ bodyCacheBytes?: number;
36
+ /** Called with errors that become an Internal error (-32603), for logging. */
37
+ onError?: (error: unknown) => void;
38
+ }
39
+
40
+ const DEFAULT_POLL_MS = { "working-tree": 2000, git: 30000 } as const;
41
+ const DEFAULT_RETRY_DELAY = { minMs: 50, maxMs: 200 };
42
+
43
+ export class Core {
44
+ readonly cache: BodyCache;
45
+ /** Requests in flight per scoped request key, so simultaneous duplicates commit once. */
46
+ readonly inflight = new Map<string, Promise<unknown>>();
47
+ /** The last parsed schema, by version: the secret guard reads it on every write. */
48
+ parsedSchema: { version: string; meta: DecoMeta } | null = null;
49
+
50
+ constructor(
51
+ readonly storage: ContentStorage,
52
+ readonly options: ContentHandlerOptions,
53
+ ) {
54
+ this.cache = new BodyCache(options.bodyCacheBytes ?? 32 * 1024 * 1024);
55
+ }
56
+
57
+ get maxCommitAttempts(): number {
58
+ return Math.max(1, this.options.maxCommitAttempts ?? 3);
59
+ }
60
+
61
+ /** Waits before commit attempt `attempt + 1`: jittered, growing with the attempt. */
62
+ async backoff(attempt: number): Promise<void> {
63
+ const { minMs, maxMs } = this.options.commitRetryDelayMs ?? DEFAULT_RETRY_DELAY;
64
+ const ms = (minMs + Math.random() * Math.max(0, maxMs - minMs)) * attempt;
65
+ if (ms > 0) await new Promise((resolve) => setTimeout(resolve, ms));
66
+ }
67
+
68
+ async description(): Promise<StorageDescription> {
69
+ return this.storage.describe();
70
+ }
71
+
72
+ /** The effective limits: the lowest of the defaults, the storage's and the options'. */
73
+ limits(description: StorageDescription): Limits {
74
+ const out = { ...DEFAULT_LIMITS };
75
+ for (const source of [description.limits, this.options.limits]) {
76
+ if (!source) continue;
77
+ for (const key of Object.keys(out) as (keyof Limits)[]) {
78
+ const value = source[key];
79
+ if (typeof value === "number" && value > 0 && value < out[key]) out[key] = value;
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ pollIntervalMs(description: StorageDescription): number {
86
+ return (
87
+ this.options.pollIntervalMs ?? description.pollIntervalMs ?? DEFAULT_POLL_MS[description.kind]
88
+ );
89
+ }
90
+
91
+ /** Refuses a `ref` on a storage without branches. */
92
+ checkRef(description: StorageDescription, ref: string | undefined): void {
93
+ if (ref !== undefined && description.refs === null) {
94
+ throw unsupported("this endpoint has no branches; omit ref");
95
+ }
96
+ }
97
+ }
98
+
99
+ /** Maps storage errors to protocol errors; anything unknown is rethrown. */
100
+ export function toProtocolError(error: unknown): ContentProtocolError | null {
101
+ if (error instanceof ContentProtocolError) return error;
102
+ if (error instanceof StorageNotFoundError) return notFound(error.message);
103
+ if (error instanceof StorageInvalidFileError) {
104
+ const name = blockNameFromFile(error.file);
105
+ return invalidBlock([
106
+ { name, rule: "unsupported-name", message: `this storage can't hold the entry "${name}"` },
107
+ ]);
108
+ }
109
+ if (error instanceof StorageUnavailableError)
110
+ return unavailable(error.message, error.retryAfterMs);
111
+ return null;
112
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `createContentHandler(storage)`: the content protocol as a fetch handler,
3
+ * `(Request) => Promise<Response>`.
4
+ *
5
+ * `POST <endpoint>` with `Content-Type: application/json` and a body that's
6
+ * one request object or a batch array. Errors come back in the JSON-RPC
7
+ * `error` object with HTTP 200, except a missing or invalid bearer token (401)
8
+ * and a body over the size limit (413), which apply to the whole batch, and
9
+ * requests that aren't the protocol at all: a method other than POST (405),
10
+ * or a body that isn't JSON or uses an unsupported encoding (415). Those carry
11
+ * a JSON-RPC error body too, with a `null` id.
12
+ * Responses are gzip-compressed when the request accepts it.
13
+ *
14
+ * The handler is path-agnostic: mount it where the endpoint lives (`/rpc` on
15
+ * the local server). Transport security that depends on where it runs — CORS,
16
+ * `Host` checks, Chrome's local-network preflight — belongs to the server
17
+ * that mounts it (`deco serve`).
18
+ */
19
+ import {
20
+ type ContentProtocolError,
21
+ forbidden,
22
+ invalidRequest,
23
+ limitExceeded,
24
+ parseError,
25
+ unauthorized,
26
+ } from "../errors";
27
+ import type { ContentStorage } from "../storage";
28
+ import { assertAuthOptions, authenticate } from "./auth";
29
+ import { type ContentHandlerOptions, Core } from "./core";
30
+ import {
31
+ BodyEncodingError,
32
+ BodyTooLargeError,
33
+ isJsonContentType,
34
+ jsonResponse,
35
+ readBody,
36
+ } from "./http";
37
+ import { dispatch } from "./rpc";
38
+
39
+ export type ContentHandler = (request: Request) => Promise<Response>;
40
+
41
+ const errorBody = (error: ContentProtocolError) =>
42
+ JSON.stringify({ jsonrpc: "2.0", id: null, error: error.toJSON() });
43
+
44
+ export function createContentHandler(
45
+ storage: ContentStorage,
46
+ options: ContentHandlerOptions = {},
47
+ ): ContentHandler {
48
+ assertAuthOptions(options);
49
+ const core = new Core(storage, options);
50
+
51
+ return async (request) => {
52
+ if (request.method !== "POST") {
53
+ return jsonResponse(request, errorBody(invalidRequest("use POST")), 405, { allow: "POST" });
54
+ }
55
+ const auth = await authenticate(request, options);
56
+ if (!auth.ok) {
57
+ return auth.reason === "unauthorized"
58
+ ? jsonResponse(request, errorBody(unauthorized()), 401, {
59
+ "www-authenticate": 'Bearer realm="deco-content"',
60
+ })
61
+ : jsonResponse(request, errorBody(forbidden()));
62
+ }
63
+ if (!isJsonContentType(request)) {
64
+ return jsonResponse(
65
+ request,
66
+ errorBody(invalidRequest("Content-Type must be application/json")),
67
+ 415,
68
+ );
69
+ }
70
+
71
+ const limits = core.limits(await core.description());
72
+ let bytes: Uint8Array;
73
+ try {
74
+ bytes = await readBody(request, limits.maxRequestBytes);
75
+ } catch (error) {
76
+ if (error instanceof BodyTooLargeError) {
77
+ return jsonResponse(
78
+ request,
79
+ errorBody(
80
+ limitExceeded(`the request body is over ${limits.maxRequestBytes} bytes`, {
81
+ limit: "maxRequestBytes",
82
+ }),
83
+ ),
84
+ 413,
85
+ );
86
+ }
87
+ if (error instanceof BodyEncodingError) {
88
+ return jsonResponse(request, errorBody(invalidRequest(error.message)), 415);
89
+ }
90
+ throw error;
91
+ }
92
+
93
+ let body: unknown;
94
+ try {
95
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
96
+ } catch {
97
+ return jsonResponse(request, errorBody(parseError()));
98
+ }
99
+ const response = await dispatch(core, body, auth.scope, limits.maxBatchResponseBytes);
100
+ return jsonResponse(request, response);
101
+ };
102
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * HTTP plumbing for the content handler: bounded body reads (gzip request
3
+ * bodies included), gzip responses and bearer-token checks. Web-standard APIs
4
+ * only (Request, Response, CompressionStream), so it runs on Node, Bun,
5
+ * Workers and Deno.
6
+ */
7
+ import { sha256Hex } from "../canonical";
8
+
9
+ /** The body was larger than allowed (after decompression). */
10
+ export class BodyTooLargeError extends Error {
11
+ constructor(readonly limit: number) {
12
+ super(`the request body is over ${limit} bytes`);
13
+ this.name = "BodyTooLargeError";
14
+ }
15
+ }
16
+
17
+ /** The body claimed an encoding it doesn't have, or one we don't decode. */
18
+ export class BodyEncodingError extends Error {
19
+ constructor(message: string) {
20
+ super(message);
21
+ this.name = "BodyEncodingError";
22
+ }
23
+ }
24
+
25
+ async function readLimited(stream: ReadableStream<Uint8Array>, limit: number): Promise<Uint8Array> {
26
+ const reader = stream.getReader();
27
+ const chunks: Uint8Array[] = [];
28
+ let total = 0;
29
+ try {
30
+ for (;;) {
31
+ const { done, value } = await reader.read();
32
+ if (done) break;
33
+ total += value.byteLength;
34
+ if (total > limit) {
35
+ await reader.cancel().catch(() => {});
36
+ throw new BodyTooLargeError(limit);
37
+ }
38
+ chunks.push(value);
39
+ }
40
+ } finally {
41
+ reader.releaseLock();
42
+ }
43
+ const out = new Uint8Array(total);
44
+ let offset = 0;
45
+ for (const chunk of chunks) {
46
+ out.set(chunk, offset);
47
+ offset += chunk.byteLength;
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /**
53
+ * Reads the request body as bytes, refusing more than `limit` bytes. A
54
+ * `Content-Encoding: gzip` body is decompressed, and the limit applies to the
55
+ * decompressed bytes too, so gzip can't bypass it.
56
+ */
57
+ export async function readBody(request: Request, limit: number): Promise<Uint8Array> {
58
+ const declared = Number(request.headers.get("content-length"));
59
+ const encoding = (request.headers.get("content-encoding") ?? "identity").trim().toLowerCase();
60
+ if (encoding === "identity" && Number.isFinite(declared) && declared > limit) {
61
+ throw new BodyTooLargeError(limit);
62
+ }
63
+ if (!request.body) return new Uint8Array(0);
64
+ if (encoding === "identity") return readLimited(request.body, limit);
65
+ if (encoding !== "gzip")
66
+ throw new BodyEncodingError(`unsupported Content-Encoding "${encoding}"`);
67
+ const decompressed = request.body.pipeThrough(
68
+ new DecompressionStream("gzip") as unknown as ReadableWritablePair<Uint8Array, Uint8Array>,
69
+ );
70
+ try {
71
+ return await readLimited(decompressed, limit);
72
+ } catch (error) {
73
+ if (error instanceof BodyTooLargeError) throw error;
74
+ throw new BodyEncodingError("the gzip body is corrupt");
75
+ }
76
+ }
77
+
78
+ /** True when the request's `Accept-Encoding` accepts gzip. */
79
+ function acceptsGzip(request: Request): boolean {
80
+ const header = request.headers.get("accept-encoding");
81
+ if (!header) return false;
82
+ return header.split(",").some((part) => {
83
+ const [coding = "", ...params] = part.trim().toLowerCase().split(";");
84
+ if (coding.trim() !== "gzip" && coding.trim() !== "*") return false;
85
+ const q = params.map((p) => p.trim()).find((p) => p.startsWith("q="));
86
+ return q === undefined || Number(q.slice(2)) > 0;
87
+ });
88
+ }
89
+
90
+ /** Bodies smaller than this aren't worth compressing. */
91
+ const GZIP_THRESHOLD_BYTES = 1024;
92
+
93
+ /** A JSON response, gzip-compressed when the request accepts it. */
94
+ export function jsonResponse(
95
+ request: Request,
96
+ body: string,
97
+ status = 200,
98
+ headers: Record<string, string> = {},
99
+ ): Response {
100
+ const responseHeaders = new Headers({
101
+ "content-type": "application/json; charset=utf-8",
102
+ "cache-control": "no-store",
103
+ vary: "Accept-Encoding",
104
+ ...headers,
105
+ });
106
+ const bytes = new TextEncoder().encode(body);
107
+ if (bytes.byteLength < GZIP_THRESHOLD_BYTES || !acceptsGzip(request)) {
108
+ return new Response(bytes, { status, headers: responseHeaders });
109
+ }
110
+ responseHeaders.set("content-encoding", "gzip");
111
+ const stream = new Blob([bytes as BlobPart])
112
+ .stream()
113
+ .pipeThrough(
114
+ new CompressionStream("gzip") as unknown as ReadableWritablePair<Uint8Array, Uint8Array>,
115
+ );
116
+ return new Response(stream, { status, headers: responseHeaders });
117
+ }
118
+
119
+ /** True when the request's `Content-Type` is JSON (`application/json`, any parameters). */
120
+ export function isJsonContentType(request: Request): boolean {
121
+ const type = request.headers.get("content-type");
122
+ return type !== null && type.split(";")[0]!.trim().toLowerCase() === "application/json";
123
+ }
124
+
125
+ /** The bearer token of the request, or `null` without one. */
126
+ export function bearerToken(request: Request): string | null {
127
+ const header = request.headers.get("authorization");
128
+ if (!header) return null;
129
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(header);
130
+ return match?.[1] ?? null;
131
+ }
132
+
133
+ /** Compares two strings in time independent of where they differ. */
134
+ export async function timingSafeEqualStrings(a: string, b: string): Promise<boolean> {
135
+ const [ha, hb] = await Promise.all([sha256Hex(a), sha256Hex(b)]);
136
+ let diff = 0;
137
+ for (let i = 0; i < ha.length; i++) diff |= ha.charCodeAt(i) ^ hb.charCodeAt(i);
138
+ return diff === 0;
139
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@decocms/blocks/protocol/server`: the content protocol's server core.
3
+ *
4
+ * `createContentHandler(storage)` serves the four methods over any
5
+ * `ContentStorage`. Web-standard APIs only, so it runs on Node, Bun, Workers
6
+ * and Deno. (`deco serve`'s asset uploads use `./assets`, which isn't public.)
7
+ */
8
+
9
+ export type { AuthOptions, AuthorizeResult } from "./auth";
10
+ export type { ContentHandlerOptions } from "./core";
11
+ export { type ContentHandler, createContentHandler } from "./handler";