@orkestrel/server 0.0.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.
@@ -0,0 +1,1728 @@
1
+ //#region src/core/constants.ts
2
+ /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
3
+ var DEFAULT_DRAIN_MS = 1e4;
4
+ /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
5
+ var DEFAULT_BODY_LIMIT = 1048576;
6
+ /**
7
+ * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
8
+ * the body pipeline's byte-counting `TransformStream` enforces when
9
+ * transparently decompressing a `Content-Encoding` request body.
10
+ *
11
+ * @remarks
12
+ * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
13
+ * can inflate by many orders of magnitude — a classic decompression bomb.
14
+ * Capping the decompressed byte count makes the pipe ABORT the moment the
15
+ * output would exceed this, BEFORE the full bomb is materialized, so the
16
+ * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
17
+ * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
18
+ * consumer raises it via {@link import('./types.js').BodyOptions}
19
+ * `decompression` for a workload that genuinely ships larger decompressed
20
+ * bodies.
21
+ */
22
+ var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
23
+ /**
24
+ * The SSE response headers the `openStream` seam always sets.
25
+ *
26
+ * @remarks
27
+ * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
28
+ * keeps a proxy from caching the stream; `keep-alive` holds the connection
29
+ * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
30
+ * events flush promptly rather than batching. Frozen so a consumer can read
31
+ * but never mutate the shared default; `openStream` merges any
32
+ * {@link import('./types.js').StreamOptions.headers} UNDER these.
33
+ */
34
+ var SSE_HEADERS = Object.freeze({
35
+ "Content-Type": "text/event-stream; charset=utf-8",
36
+ "Cache-Control": "no-cache",
37
+ Connection: "keep-alive",
38
+ "X-Accel-Buffering": "no"
39
+ });
40
+ /**
41
+ * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
42
+ * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
43
+ * / control-char-bearing incoming id is REJECTED (a fresh id is minted
44
+ * instead) rather than ever riding into a response header or `context.state`
45
+ * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
46
+ * shared default.
47
+ */
48
+ var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
49
+ /**
50
+ * The set of bare `Content-Type`s `isCompressibleType` treats as
51
+ * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
52
+ * `+xml`) rules that helper also applies.
53
+ *
54
+ * @remarks
55
+ * The text-shaped application types worth compressing (JSON / JavaScript /
56
+ * XML / SVG / WASM / a few document formats) — NOT already-compressed
57
+ * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
58
+ * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
59
+ * but never mutates the shared default.
60
+ */
61
+ var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
62
+ "application/json",
63
+ "application/javascript",
64
+ "application/xml",
65
+ "application/xhtml+xml",
66
+ "application/rss+xml",
67
+ "application/atom+xml",
68
+ "application/ld+json",
69
+ "application/manifest+json",
70
+ "application/vnd.api+json",
71
+ "application/wasm",
72
+ "image/svg+xml",
73
+ "application/pdf"
74
+ ]);
75
+ /**
76
+ * The default {@link Encoding} content-codings the substrate offers, in
77
+ * PREFERENCE order — `gzip` / `deflate`.
78
+ *
79
+ * @remarks
80
+ * `identity` (no compression) is always implicitly acceptable and is NOT
81
+ * listed here — it is the fall-through when a client accepts none of these.
82
+ * Brotli is omitted per the core's `CompressionStream`-only decision (see
83
+ * {@link Encoding}). Frozen so a consumer can read but never mutate the
84
+ * shared default.
85
+ */
86
+ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
87
+ //#endregion
88
+ //#region src/core/errors.ts
89
+ /**
90
+ * An error a handler (or middleware) throws to produce an HTTP response of a
91
+ * specific status.
92
+ *
93
+ * @remarks
94
+ * Carries the HTTP `status` to send and an optional `context` record (the
95
+ * offending field / value). The server's built-in error boundary catches it
96
+ * and renders a response of `status` with the error's `message` as the body
97
+ * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
98
+ * deliberate signal), unlike a generic throw whose message is hidden unless
99
+ * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
100
+ * specific statuses, or throw it directly. Narrow a caught value with
101
+ * {@link isHTTPError}.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * import { HTTPError } from '@src/core'
106
+ *
107
+ * const handler = async (request: Request): Promise<Response> => {
108
+ * const user = await find(new URL(request.url).searchParams.get('id'))
109
+ * if (user === undefined) throw new HTTPError(404, 'user not found')
110
+ * return Response.json(user)
111
+ * }
112
+ * ```
113
+ */
114
+ var HTTPError = class extends Error {
115
+ status;
116
+ context;
117
+ constructor(status, message, context) {
118
+ super(message);
119
+ this.name = "HTTPError";
120
+ this.status = status;
121
+ this.context = context;
122
+ }
123
+ };
124
+ /**
125
+ * The {@link HTTPError} thrown when a request body exceeds the body
126
+ * pipeline's size limit — a `413 Content Too Large`.
127
+ *
128
+ * @remarks
129
+ * Thrown by `readBody` (and the middleware context's cached `body()`) when
130
+ * the received bytes exceed the configured {@link
131
+ * import('./types.js').BodyOptions.limit}, carrying the `limit` in its
132
+ * `context`. The server's error boundary renders it as a 413.
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * import { ContentTooLargeError, isHTTPError } from '@src/core'
137
+ *
138
+ * try {
139
+ * await readBody(request, { limit: 1024 })
140
+ * } catch (error) {
141
+ * if (isHTTPError(error)) console.log(error.status) // 413
142
+ * }
143
+ * ```
144
+ */
145
+ var ContentTooLargeError = class extends HTTPError {
146
+ constructor(limit) {
147
+ super(413, `request body exceeds the ${limit}-byte limit`, { limit });
148
+ this.name = "ContentTooLargeError";
149
+ }
150
+ };
151
+ /**
152
+ * Narrow an unknown caught value to an {@link HTTPError} (including its
153
+ * subclasses, e.g. {@link ContentTooLargeError}).
154
+ *
155
+ * @param value - The value to test (typically a `catch` binding)
156
+ * @returns `true` when `value` is an {@link HTTPError}
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * import { isHTTPError } from '@src/core'
161
+ *
162
+ * try {
163
+ * await handle(request)
164
+ * } catch (error) {
165
+ * if (isHTTPError(error)) console.log(error.status, error.message)
166
+ * }
167
+ * ```
168
+ */
169
+ function isHTTPError(value) {
170
+ return value instanceof HTTPError;
171
+ }
172
+ Object.freeze([
173
+ "null",
174
+ "boolean",
175
+ "object",
176
+ "array",
177
+ "number",
178
+ "integer",
179
+ "string"
180
+ ]);
181
+ /** Determine whether a value is a string. */
182
+ function isString(value) {
183
+ return typeof value === "string";
184
+ }
185
+ /**
186
+ * Determine whether a value is a non-null object.
187
+ *
188
+ * @remarks
189
+ * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use
190
+ * {@link isRecord} when you need a plain-record check.
191
+ */
192
+ function isObject(value) {
193
+ return typeof value === "object" && value !== null;
194
+ }
195
+ /**
196
+ * Determine whether a value is a plain record (object literal or null-prototype),
197
+ * not an array or class instance.
198
+ *
199
+ * @remarks
200
+ * Use instead of {@link isObject} to distinguish a plain `{}` /
201
+ * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
202
+ * test is realm-agnostic: rather than comparing against the current realm's
203
+ * `Object.prototype` (which a plain object from another `vm.Context`, iframe,
204
+ * or worker would fail), it accepts any value whose prototype is `null`, OR
205
+ * whose prototype's own prototype is `null` — the shape every plain object
206
+ * has in every realm, since `Object.prototype` itself always sits one step
207
+ * above `null`. Arrays and class instances are still rejected: an array's
208
+ * prototype chain runs through `Array.prototype` before `null`, and a class
209
+ * instance's runs through the class's own prototype. The whole body runs
210
+ * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
211
+ * `getPrototypeOf` trap cannot escape as a thrown error.
212
+ */
213
+ function isRecord(value) {
214
+ const outcome = attempt(() => {
215
+ if (!isObject(value) || isArray(value)) return false;
216
+ const prototype = Object.getPrototypeOf(value);
217
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
218
+ });
219
+ return outcome.success && outcome.value;
220
+ }
221
+ /** Determine whether a value is an array. */
222
+ function isArray(value) {
223
+ return Array.isArray(value);
224
+ }
225
+ /**
226
+ * Invoke a callback and capture its outcome as a {@link Result}, never letting
227
+ * a throw escape.
228
+ *
229
+ * @remarks
230
+ * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
231
+ * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
232
+ * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
233
+ * `boolean`. This converts a throwing callback into a `Failure` so the
234
+ * surrounding guard can treat it as a non-match instead of propagating the
235
+ * exception, written once and shared rather than copy-pasted as ad-hoc
236
+ * `try`/`catch`.
237
+ *
238
+ * @param callback - The callback to invoke with no arguments
239
+ * @returns A `Success` carrying the return value, or a `Failure` carrying the
240
+ * thrown reason normalised to an `Error`
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * const outcome = attempt(() => predicate(value))
245
+ * return outcome.success && outcome.value
246
+ * ```
247
+ */
248
+ function attempt(callback) {
249
+ try {
250
+ return {
251
+ success: true,
252
+ value: callback()
253
+ };
254
+ } catch (reason) {
255
+ if (reason instanceof Error) return {
256
+ success: false,
257
+ error: reason
258
+ };
259
+ let message = "Unknown thrown value";
260
+ try {
261
+ message = String(reason);
262
+ } catch {}
263
+ return {
264
+ success: false,
265
+ error: new Error(message)
266
+ };
267
+ }
268
+ }
269
+ /**
270
+ * Parse a JSON string, returning `undefined` instead of throwing.
271
+ *
272
+ * @remarks
273
+ * The safe boundary for untrusted JSON text: a malformed string yields
274
+ * `undefined`, never an exception. Returns `unknown` — a successful parse proves
275
+ * nothing about shape, so narrow the result with a guard (or use
276
+ * {@link parseJSONAs}). A large document is not walked here; parsing is shallow
277
+ * and lazy validation is the caller's to compose.
278
+ *
279
+ * @param value - The JSON string to parse
280
+ * @returns The parsed value, or `undefined` when `value` is not valid JSON
281
+ */
282
+ function parseJSON(value) {
283
+ try {
284
+ return JSON.parse(value);
285
+ } catch {
286
+ return;
287
+ }
288
+ }
289
+ //#endregion
290
+ //#region src/core/helpers.ts
291
+ /**
292
+ * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
293
+ * handler into one request handler — the frozen middleware seam (§5.1).
294
+ *
295
+ * @remarks
296
+ * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
297
+ * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
298
+ * `terminal`. Each middleware's `next` may be called with a substituted
299
+ * `Request` (the downstream chain then sees that request instead of the
300
+ * original), called with no argument (the original request continues
301
+ * downstream), or NOT called at all (a short-circuit — the middleware's own
302
+ * returned `Response` is sent, and everything downstream never runs). A
303
+ * SECOND call to the same `next` within one middleware invocation REJECTS —
304
+ * each link runs the chain at most once, so a middleware cannot fork the
305
+ * request into two divergent downstream runs.
306
+ *
307
+ * @typeParam TState - The consumer's opaque per-request state type
308
+ * @param middleware - The ordered chain, outermost first
309
+ * @param terminal - The innermost handler the chain ultimately reaches
310
+ * @returns A single `(request, context) => Promise<Response>` handler running the whole onion
311
+ *
312
+ * @example
313
+ * ```ts
314
+ * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {
315
+ * const response = await next()
316
+ * response.headers.set('X-Powered-By', 'orkestrel')
317
+ * return response
318
+ * }
319
+ *
320
+ * const handle = compose([withHeader], async () => new Response('ok'))
321
+ * ```
322
+ */
323
+ function compose(middleware, terminal) {
324
+ return async (request, context) => {
325
+ const dispatch = (index, currentRequest) => {
326
+ const layer = middleware[index];
327
+ if (layer === void 0) return terminal(currentRequest, context);
328
+ let called = false;
329
+ const next = (nextRequest) => {
330
+ if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
331
+ called = true;
332
+ return dispatch(index + 1, nextRequest ?? currentRequest);
333
+ };
334
+ return Promise.resolve(layer(currentRequest, context, next));
335
+ };
336
+ return dispatch(0, request);
337
+ };
338
+ }
339
+ /**
340
+ * Parse a raw `Cookie:` request header into a `name → value` lookup.
341
+ *
342
+ * @remarks
343
+ * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
344
+ * cookie-pair separator never precedes it), while every later segment has its
345
+ * inter-pair separator (ASCII space/tab) stripped before parsing — so a
346
+ * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
347
+ * {@link isCookieName} rather than silently reconciling into a
348
+ * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
349
+ * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
350
+ * malformed header yields an empty record, never throws (AGENTS §14).
351
+ *
352
+ * @param header - The raw `Cookie` header value (possibly `undefined`)
353
+ * @returns A record of every parsed cookie, `name → decoded value`
354
+ *
355
+ * @example
356
+ * ```ts
357
+ * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }
358
+ * ```
359
+ */
360
+ function parseCookies(header) {
361
+ const out = {};
362
+ if (header === void 0) return out;
363
+ const segments = header.split(";");
364
+ for (let index = 0; index < segments.length; index += 1) {
365
+ const raw = segments[index] ?? "";
366
+ const segment = index === 0 ? raw : raw.replace(/^[ \t]+/, "");
367
+ const eq = segment.indexOf("=");
368
+ if (eq < 0) continue;
369
+ const name = segment.slice(0, eq);
370
+ if (!isCookieName(name)) continue;
371
+ out[name] = decodeCookieValue(segment.slice(eq + 1).trim());
372
+ }
373
+ return out;
374
+ }
375
+ /**
376
+ * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
377
+ * cookie-token chars with NO surrounding (or interior) whitespace.
378
+ *
379
+ * @remarks
380
+ * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
381
+ * which excludes every whitespace char (ASCII and Unicode) plus controls,
382
+ * separators, and `=`. The {@link parseCookies} hardening that stops a
383
+ * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
384
+ *
385
+ * @param value - The candidate cookie name
386
+ * @returns `true` when `value` is a valid, whitespace-free cookie token
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * isCookieName('__Host-session') // true
391
+ * isCookieName(' __Host-session') // false — whitespace-padded
392
+ * ```
393
+ */
394
+ function isCookieName(value) {
395
+ return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
396
+ }
397
+ /**
398
+ * Decode a cookie value with `decodeURIComponent`, falling back to the raw
399
+ * text when the value is not valid percent-encoding.
400
+ *
401
+ * @param raw - The raw (trimmed) cookie value
402
+ * @returns The URL-decoded value, or the raw value when decoding would throw
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * decodeCookieValue('a%20b') // 'a b'
407
+ * decodeCookieValue('%') // '%' — malformed escape stays literal
408
+ * ```
409
+ */
410
+ function decodeCookieValue(raw) {
411
+ try {
412
+ return decodeURIComponent(raw);
413
+ } catch {
414
+ return raw;
415
+ }
416
+ }
417
+ /**
418
+ * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
419
+ * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
420
+ * attributes with before emitting them.
421
+ *
422
+ * @remarks
423
+ * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
424
+ * folded header), ASCII/Unicode whitespace, or a C0/DEL control char
425
+ * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`
426
+ * directive. Total — never throws (a bad value returns `false`).
427
+ *
428
+ * @param value - The candidate attribute value (a `Domain` or `Path`)
429
+ * @returns `true` when `value` carries no separator / whitespace / control char
430
+ *
431
+ * @example
432
+ * ```ts
433
+ * isCookieAttribute('/app') // true
434
+ * isCookieAttribute('/a\r\nSet-Cookie: x=y') // false
435
+ * ```
436
+ */
437
+ function isCookieAttribute(value) {
438
+ for (const char of value) {
439
+ if (char === ";" || char === "," || /\s/.test(char)) return false;
440
+ const code = char.codePointAt(0);
441
+ if (code !== void 0 && (code < 32 || code === 127)) return false;
442
+ }
443
+ return true;
444
+ }
445
+ /**
446
+ * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
447
+ *
448
+ * @remarks
449
+ * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
450
+ * appends the present {@link CookieOptions} attributes in canonical order:
451
+ * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
452
+ * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
453
+ * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
454
+ * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
455
+ * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
456
+ * the `secure` option (the spec requires it); an un-resolved `undefined`
457
+ * `secure` here falls to OFF — request-aware callers resolve it first via
458
+ * {@link resolveSecure}.
459
+ *
460
+ * @param name - The cookie name
461
+ * @param value - The cookie value (URL-encoded into the output)
462
+ * @param options - The {@link CookieOptions} attributes; see its fields for defaults
463
+ * @returns The `Set-Cookie` header value
464
+ * @throws {HTTPError} When `domain` or `path` carries an injection char
465
+ *
466
+ * @example
467
+ * ```ts
468
+ * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'
469
+ * ```
470
+ */
471
+ function serializeCookie(name, value, options) {
472
+ const sameSite = options?.sameSite ?? "Lax";
473
+ const domain = options?.domain;
474
+ if (domain !== void 0 && !isCookieAttribute(domain)) throw new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`);
475
+ const path = options?.path ?? "/";
476
+ if (!isCookieAttribute(path)) throw new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`);
477
+ const secure = sameSite === "None" || options?.secure === true;
478
+ const parts = [`${name}=${encodeURIComponent(value)}`];
479
+ if (domain !== void 0) parts.push(`Domain=${domain}`);
480
+ parts.push(`Path=${path}`);
481
+ if (options?.maxAge !== void 0) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`);
482
+ if (options?.httpOnly !== false) parts.push("HttpOnly");
483
+ if (secure) parts.push("Secure");
484
+ parts.push(`SameSite=${sameSite}`);
485
+ return parts.join("; ");
486
+ }
487
+ /**
488
+ * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
489
+ * `secure` setting and whether the request arrived over TLS.
490
+ *
491
+ * @remarks
492
+ * `true` / `false` are explicit overrides. `undefined` (the secure default —
493
+ * the option omitted) resolves to `encrypted` — `Secure` on a TLS
494
+ * connection, off over plaintext HTTP — so a production HTTPS deployment
495
+ * gets `Secure` automatically while local-dev HTTP still works.
496
+ *
497
+ * @param secure - The {@link CookieOptions} `secure` setting
498
+ * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
499
+ * @returns The concrete `Secure` flag to emit
500
+ *
501
+ * @example
502
+ * ```ts
503
+ * resolveSecure(undefined, true) // true
504
+ * resolveSecure(undefined, false) // false
505
+ * resolveSecure(false, true) // false — explicit override wins
506
+ * ```
507
+ */
508
+ function resolveSecure(secure, encrypted) {
509
+ if (secure === true || secure === false) return secure;
510
+ return encrypted;
511
+ }
512
+ /**
513
+ * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
514
+ * clobbering a prior one.
515
+ *
516
+ * @remarks
517
+ * `Headers.append` already accumulates repeated headers (unlike node's
518
+ * `setHeader`), so this is a thin, self-documenting wrapper naming the
519
+ * cookie-append intent — the primitive {@link writeSignedCookie} /
520
+ * {@link clearCookie} use.
521
+ *
522
+ * @param headers - The response `Headers` to write into
523
+ * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
524
+ *
525
+ * @example
526
+ * ```ts
527
+ * const headers = new Headers()
528
+ * appendCookie(headers, serializeCookie('a', '1'))
529
+ * appendCookie(headers, serializeCookie('b', '2'))
530
+ * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
531
+ * ```
532
+ */
533
+ function appendCookie(headers, cookie) {
534
+ headers.append("set-cookie", cookie);
535
+ }
536
+ /**
537
+ * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
538
+ * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
539
+ *
540
+ * @remarks
541
+ * The cookie value is `await signToken(value, { secret })`
542
+ * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
543
+ * cookie — the same secret rotation and tamper rejection, no second HMAC
544
+ * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
545
+ * signing is asynchronous (§3 of the proposal).
546
+ *
547
+ * @param headers - The response `Headers` to write into
548
+ * @param name - The cookie name
549
+ * @param value - The opaque value to sign into the cookie
550
+ * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
551
+ * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
552
+ *
553
+ * @example
554
+ * ```ts
555
+ * const headers = new Headers()
556
+ * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
557
+ * ```
558
+ */
559
+ async function writeSignedCookie(headers, name, value, secret, options) {
560
+ appendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options));
561
+ }
562
+ /**
563
+ * Read + verify a SIGNED cookie off a request — TOTAL, returning the
564
+ * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
565
+ *
566
+ * @remarks
567
+ * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
568
+ * and verifies it with {@link verifyToken} against `secret` (a rotation list
569
+ * accepts a cookie signed by any of its secrets). ANY failure — an absent
570
+ * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
571
+ *
572
+ * @param request - The `Request` to read the `Cookie` header from
573
+ * @param name - The cookie name to read
574
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
575
+ * @returns The embedded value when the cookie is present + valid, else `undefined`
576
+ *
577
+ * @example
578
+ * ```ts
579
+ * const value = await readSignedCookie(request, 'session', 'secret')
580
+ * ```
581
+ */
582
+ async function readSignedCookie(request, name, secret) {
583
+ const cookie = parseCookies(request.headers.get("cookie") ?? void 0)[name];
584
+ return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
585
+ }
586
+ /**
587
+ * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
588
+ *
589
+ * @remarks
590
+ * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
591
+ * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
592
+ * a cookie when those MATCH the one it set).
593
+ *
594
+ * @param headers - The response `Headers` to write into
595
+ * @param name - The cookie name to clear
596
+ * @param options - The {@link CookieOptions} that must match the original cookie
597
+ *
598
+ * @example
599
+ * ```ts
600
+ * const headers = new Headers()
601
+ * clearCookie(headers, 'session')
602
+ * ```
603
+ */
604
+ function clearCookie(headers, name, options) {
605
+ appendCookie(headers, serializeCookie(name, "", {
606
+ ...options,
607
+ maxAge: 0
608
+ }));
609
+ }
610
+ /**
611
+ * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
612
+ * {@link verifyToken} use, and the signature encoding for the HMAC.
613
+ *
614
+ * @param bytes - The bytes to encode
615
+ * @returns The base64url string (no padding)
616
+ *
617
+ * @example
618
+ * ```ts
619
+ * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
620
+ * ```
621
+ */
622
+ function encodeBase64Url(bytes) {
623
+ let binary = "";
624
+ for (const byte of bytes) binary += String.fromCharCode(byte);
625
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
626
+ }
627
+ /**
628
+ * Decode a base64url string back into its bytes — the inverse of
629
+ * {@link encodeBase64Url}.
630
+ *
631
+ * @remarks
632
+ * Restores the standard base64 alphabet + padding before decoding with
633
+ * `atob`. THROWS `DOMException` on a malformed input — callers on the
634
+ * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
635
+ *
636
+ * @param value - The base64url string to decode
637
+ * @returns The decoded bytes
638
+ * @throws {DOMException} When `value` is not valid base64url
639
+ *
640
+ * @example
641
+ * ```ts
642
+ * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
643
+ * ```
644
+ */
645
+ function decodeBase64Url(value) {
646
+ const restored = value.replace(/-/g, "+").replace(/_/g, "/");
647
+ const padding = restored.length % 4 === 0 ? "" : "=".repeat(4 - restored.length % 4);
648
+ const binary = atob(restored + padding);
649
+ const bytes = new Uint8Array(binary.length);
650
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
651
+ return bytes;
652
+ }
653
+ /**
654
+ * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
655
+ *
656
+ * @remarks
657
+ * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
658
+ * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
659
+ * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
660
+ * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
661
+ * {@link TokenSecret} (the current secret, or the head of a rotation list).
662
+ * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
663
+ * misconfigured secret with no usable entry THROWS an {@link HTTPError}
664
+ * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
665
+ * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
666
+ *
667
+ * @param value - The opaque value to embed (a session id, a deployment marker)
668
+ * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
669
+ * @returns The signed `<payload>.<signature>` token string
670
+ * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
671
+ *
672
+ * @example
673
+ * ```ts
674
+ * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
675
+ * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
676
+ * ```
677
+ */
678
+ async function signToken(value, options) {
679
+ const secret = normalizeSecret(options.secret)[0];
680
+ if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
681
+ const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
682
+ const encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({
683
+ value,
684
+ exp
685
+ })));
686
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
687
+ name: "HMAC",
688
+ hash: "SHA-256"
689
+ }, false, ["sign"]);
690
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
691
+ return `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`;
692
+ }
693
+ /**
694
+ * Verify a stateless token and return its embedded value — TOTAL, never throws.
695
+ *
696
+ * @remarks
697
+ * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
698
+ * value containing dots survives), and checks the payload's HMAC-SHA256
699
+ * signature against EACH {@link TokenSecret} candidate via
700
+ * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
701
+ * retired, §3 of the proposal), accepting the token on the first match (the
702
+ * rotation path). It then decodes + narrows the payload (`isRecord` +
703
+ * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
704
+ * rejects an expired token. ANY failure — a malformed token, a bad signature,
705
+ * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
706
+ * yields `undefined` rather than throwing.
707
+ *
708
+ * @param token - The candidate token string (from a request header/cookie)
709
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
710
+ * @returns The embedded value when the token is valid + unexpired, else `undefined`
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * await verifyToken('bad.token', 'shh') // undefined — never throws
715
+ * ```
716
+ */
717
+ async function verifyToken(token, secret) {
718
+ const secrets = normalizeSecret(secret);
719
+ if (secrets.length === 0) return void 0;
720
+ const dot = token.lastIndexOf(".");
721
+ if (dot < 0) return void 0;
722
+ const encoded = token.slice(0, dot);
723
+ const signatureText = token.slice(dot + 1);
724
+ try {
725
+ const signature = decodeBase64Url(signatureText);
726
+ const data = new TextEncoder().encode(encoded);
727
+ for (const candidate of secrets) {
728
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
729
+ name: "HMAC",
730
+ hash: "SHA-256"
731
+ }, false, ["verify"]);
732
+ if (await crypto.subtle.verify("HMAC", key, signature, data)) return decodeTokenPayload(encoded);
733
+ }
734
+ return;
735
+ } catch {
736
+ return;
737
+ }
738
+ }
739
+ /**
740
+ * Decode + narrow a signed token's base64url JSON payload, honoring its
741
+ * expiry — the shared decode step {@link verifyToken} applies after a
742
+ * signature match.
743
+ *
744
+ * @remarks
745
+ * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
746
+ * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
747
+ * TOTAL — any decode/shape/expiry failure yields `undefined`.
748
+ *
749
+ * @param encoded - The base64url-encoded payload segment (before the last `.`)
750
+ * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
751
+ */
752
+ function decodeTokenPayload(encoded) {
753
+ try {
754
+ const text = new TextDecoder().decode(decodeBase64Url(encoded));
755
+ const payload = JSON.parse(text);
756
+ if (!isRecord(payload)) return void 0;
757
+ if (typeof payload.value !== "string") return void 0;
758
+ if (payload.exp !== void 0 && typeof payload.exp !== "number") return void 0;
759
+ if (payload.exp !== void 0 && Date.now() >= payload.exp) return void 0;
760
+ return payload.value;
761
+ } catch {
762
+ return;
763
+ }
764
+ }
765
+ /**
766
+ * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
767
+ * backs both {@link signToken} and {@link verifyToken}.
768
+ *
769
+ * @remarks
770
+ * A single string becomes a one-element list; a rotation list is copied. Any
771
+ * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
772
+ * emptiness test; each kept secret is stored VERBATIM). The first kept
773
+ * element is the signing secret; all kept are accepted on verify.
774
+ *
775
+ * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
776
+ * @returns The kept (non-blank) secrets, in order — empty when none is usable
777
+ *
778
+ * @example
779
+ * ```ts
780
+ * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
781
+ * ```
782
+ */
783
+ function normalizeSecret(secret) {
784
+ return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
785
+ }
786
+ /**
787
+ * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
788
+ * into its q-sorted entries.
789
+ *
790
+ * @remarks
791
+ * Splits on `,`; for each part takes the token before the first `;`
792
+ * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
793
+ * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
794
+ * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
795
+ * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
796
+ * the header's own order within a tie — a single pass with no backtracking,
797
+ * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
798
+ * empty/malformed header yields `[]`/best-effort entries, never throws.
799
+ *
800
+ * @param header - The raw weighted header value
801
+ * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending
802
+ *
803
+ * @example
804
+ * ```ts
805
+ * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')
806
+ * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]
807
+ * ```
808
+ */
809
+ function parseAcceptHeader(header) {
810
+ const entries = [];
811
+ for (const part of header.split(",")) {
812
+ const trimmed = part.trim();
813
+ if (trimmed.length === 0) continue;
814
+ const semicolon = trimmed.indexOf(";");
815
+ const value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase();
816
+ if (value.length === 0) continue;
817
+ let q = 1;
818
+ if (semicolon !== -1) {
819
+ const match = /;\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon));
820
+ if (match !== null) {
821
+ const parsed = Number(match[1]);
822
+ if (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed));
823
+ }
824
+ }
825
+ entries.push({
826
+ value,
827
+ q
828
+ });
829
+ }
830
+ return entries.map((entry, index) => ({
831
+ entry,
832
+ index
833
+ })).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
834
+ }
835
+ /**
836
+ * The client's quality (q) for one content-coding from the parsed
837
+ * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
838
+ * server-preference selection.
839
+ *
840
+ * @remarks
841
+ * Prefers an EXACT named match (including an explicit `;q=0` rejection);
842
+ * failing that, a bare `*` wildcard's q applies. A coding that is neither
843
+ * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
844
+ * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
845
+ *
846
+ * @param entries - The parsed {@link AcceptEntry} list
847
+ * @param coding - The candidate coding to score
848
+ * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
849
+ *
850
+ * @example
851
+ * ```ts
852
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
853
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
854
+ * ```
855
+ */
856
+ function codingQuality(entries, coding) {
857
+ const named = entries.find((entry) => entry.value === coding);
858
+ if (named !== void 0) return named.q;
859
+ return entries.find((entry) => entry.value === "*")?.q ?? 0;
860
+ }
861
+ /**
862
+ * Select the best content-coding for an `Accept-Encoding` header from the
863
+ * codings the server offers.
864
+ *
865
+ * @remarks
866
+ * Parses the header ({@link parseAcceptHeader}) and scores each `available`
867
+ * coding in the SERVER's preference order ({@link codingQuality}), keeping
868
+ * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
869
+ * client-side tie). Returns `undefined` when the client accepts none of
870
+ * `available` (identity — no compression). TOTAL on hostile input.
871
+ *
872
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
873
+ * @param header - The raw `Accept-Encoding` header value
874
+ * @param available - The codings the server offers, in preference (tie-break) order
875
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
876
+ *
877
+ * @example
878
+ * ```ts
879
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
880
+ * ```
881
+ */
882
+ function negotiateEncoding(header, available) {
883
+ if (available.length === 0) return void 0;
884
+ const entries = parseAcceptHeader(header);
885
+ let best;
886
+ let bestQuality = 0;
887
+ for (const coding of available) {
888
+ const quality = codingQuality(entries, coding);
889
+ if (quality > bestQuality) {
890
+ best = coding;
891
+ bestQuality = quality;
892
+ }
893
+ }
894
+ return best;
895
+ }
896
+ /**
897
+ * Rank + quality of one `candidate` media type against the parsed `Accept`
898
+ * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
899
+ * uses to score each `available` candidate.
900
+ *
901
+ * @remarks
902
+ * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the
903
+ * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact
904
+ * `;q=0` entry explicitly rejects the candidate outright (returns
905
+ * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
906
+ * (less specific) coverage, so a later more-specific match can still allow
907
+ * it. Among multiple matching entries, the lowest `rank` wins, and among a
908
+ * rank tie the highest `q` wins.
909
+ *
910
+ * @param entries - The parsed {@link AcceptEntry} list
911
+ * @param candidate - The candidate media type to score (e.g. `'text/html'`)
912
+ * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
913
+ *
914
+ * @example
915
+ * ```ts
916
+ * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')
917
+ * // { q: 1, rank: 0 }
918
+ * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }
919
+ * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
920
+ * ```
921
+ */
922
+ function matchMediaType(entries, candidate) {
923
+ const slash = candidate.indexOf("/");
924
+ const type = slash === -1 ? candidate : candidate.slice(0, slash);
925
+ let best;
926
+ for (const entry of entries) {
927
+ let rank;
928
+ if (entry.value === candidate) rank = 0;
929
+ else if (entry.value === `${type}/*`) rank = 1;
930
+ else if (entry.value === "*/*") rank = 2;
931
+ if (rank === void 0) continue;
932
+ if (entry.q === 0) {
933
+ if (rank === 0) return void 0;
934
+ continue;
935
+ }
936
+ if (best === void 0 || rank < best.rank || rank === best.rank && entry.q > best.q) best = {
937
+ q: entry.q,
938
+ rank
939
+ };
940
+ }
941
+ return best;
942
+ }
943
+ /**
944
+ * The client's quality for one `candidate` language from the parsed
945
+ * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
946
+ *
947
+ * @remarks
948
+ * Prefers an exact match, then a primary-tag prefix match (`en` accepts
949
+ * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
950
+ * is an explicit rejection).
951
+ *
952
+ * @param entries - The parsed {@link AcceptEntry} list
953
+ * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
954
+ * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
955
+ *
956
+ * @example
957
+ * ```ts
958
+ * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
959
+ * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
960
+ * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
961
+ * ```
962
+ */
963
+ function languageQuality(entries, candidate) {
964
+ const lower = candidate.toLowerCase();
965
+ const primary = lower.split("-")[0];
966
+ let named;
967
+ let prefixed;
968
+ let wildcard;
969
+ for (const entry of entries) {
970
+ const entryPrimary = entry.value.split("-")[0];
971
+ if (entry.value === lower) named = entry.q;
972
+ else if (entryPrimary === primary) {
973
+ if (prefixed === void 0) prefixed = entry.q;
974
+ } else if (entry.value === "*") wildcard = entry.q;
975
+ }
976
+ if (named !== void 0) return named;
977
+ if (prefixed !== void 0) return prefixed;
978
+ return wildcard ?? 0;
979
+ }
980
+ /**
981
+ * Whether a `Content-Type` is worth compressing.
982
+ *
983
+ * @remarks
984
+ * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
985
+ * type, a `+json`/`+xml` structured suffix, or one of the explicit
986
+ * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
987
+ * binary (`image/png`, `application/zip`) is NOT compressible. An
988
+ * absent/empty type is not compressible. TOTAL.
989
+ *
990
+ * @param type - The response `Content-Type` header value (with or without parameters)
991
+ * @returns `true` when the type is text-shaped and worth compressing
992
+ *
993
+ * @example
994
+ * ```ts
995
+ * isCompressibleType('application/json; charset=utf-8') // true
996
+ * isCompressibleType('image/png') // false
997
+ * ```
998
+ */
999
+ function isCompressibleType(type) {
1000
+ const semicolon = type.indexOf(";");
1001
+ const bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase();
1002
+ if (bare.length === 0) return false;
1003
+ if (bare.startsWith("text/")) return true;
1004
+ if (bare.endsWith("+json") || bare.endsWith("+xml")) return true;
1005
+ return COMPRESSIBLE_TYPES.has(bare);
1006
+ }
1007
+ /**
1008
+ * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
1009
+ *
1010
+ * @remarks
1011
+ * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
1012
+ * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
1013
+ * default, encoding-AGNOSTIC, so the tag survives a downstream content
1014
+ * re-encoding (gzip) and still matches on revalidation — or a STRONG one
1015
+ * (`"<hash>"`, byte-identity) when `weak` is `false`.
1016
+ *
1017
+ * @param body - The full (uncompressed) response body to hash
1018
+ * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
1019
+ * @returns The `ETag` header value
1020
+ *
1021
+ * @example
1022
+ * ```ts
1023
+ * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/"…sha256-hex…"'
1024
+ * ```
1025
+ */
1026
+ async function computeBodyETag(body, weak = true) {
1027
+ const digest = await crypto.subtle.digest("SHA-256", body);
1028
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1029
+ return weak ? `W/"${hex}"` : `"${hex}"`;
1030
+ }
1031
+ /**
1032
+ * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
1033
+ * comparison body — the reduction {@link matchesETag} applies to both sides
1034
+ * before the RFC 7232 §2.3.2 weak comparison.
1035
+ *
1036
+ * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
1037
+ * @returns The tag with any leading `W/` removed (the quotes preserved)
1038
+ *
1039
+ * @example
1040
+ * ```ts
1041
+ * unwrapETag('W/"abc"') // '"abc"'
1042
+ * ```
1043
+ */
1044
+ function unwrapETag(tag) {
1045
+ const trimmed = tag.trim();
1046
+ return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
1047
+ }
1048
+ /**
1049
+ * Whether a request's `If-None-Match` header matches a resource's current
1050
+ * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
1051
+ *
1052
+ * @remarks
1053
+ * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
1054
+ * listed tag matches), or the `*` wildcard (matches ANY current
1055
+ * representation — only a list of exactly `*` is the wildcard). Comparison is
1056
+ * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
1057
+ * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
1058
+ * malformed/empty header matches nothing, never throws.
1059
+ *
1060
+ * @param header - The raw `If-None-Match` header value
1061
+ * @param etag - The resource's current `ETag`
1062
+ * @returns `true` when the conditional matches (the caller answers `304`)
1063
+ *
1064
+ * @example
1065
+ * ```ts
1066
+ * matchesETag('"abc", W/"def"', 'W/"abc"') // true — weak comparison
1067
+ * matchesETag('*', 'W/"anything"') // true — wildcard
1068
+ * ```
1069
+ */
1070
+ function matchesETag(header, etag) {
1071
+ const trimmed = header.trim();
1072
+ if (trimmed === "*") return true;
1073
+ const target = unwrapETag(etag);
1074
+ for (const member of trimmed.split(",")) {
1075
+ const candidate = member.trim();
1076
+ if (candidate.length === 0) continue;
1077
+ if (unwrapETag(candidate) === target) return true;
1078
+ }
1079
+ return false;
1080
+ }
1081
+ /**
1082
+ * Parse an HTTP `Range` request header against a known resource `size` —
1083
+ * TOTAL, returning a {@link RangeSpec} or `undefined`.
1084
+ *
1085
+ * @remarks
1086
+ * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1087
+ * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1088
+ * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1089
+ * `{ satisfiable: true, start, end }` for an overlapping range,
1090
+ * `{ satisfiable: false }` for a range wholly past the resource, and
1091
+ * `undefined` for the "serve the whole resource" case: an ABSENT header, a
1092
+ * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
1093
+ * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1094
+ * header.
1095
+ *
1096
+ * @param header - The raw `Range` header value
1097
+ * @param size - The resource's total byte length
1098
+ * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource
1099
+ *
1100
+ * @example
1101
+ * ```ts
1102
+ * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
1103
+ * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
1104
+ * ```
1105
+ */
1106
+ function parseRange(header, size) {
1107
+ if (header === void 0) return void 0;
1108
+ const match = /^bytes=(.*)$/.exec(header.trim());
1109
+ if (match === null) return void 0;
1110
+ const spec = match[1].trim();
1111
+ if (spec.includes(",")) return void 0;
1112
+ const dash = spec.indexOf("-");
1113
+ if (dash < 0) return void 0;
1114
+ const startText = spec.slice(0, dash).trim();
1115
+ const endText = spec.slice(dash + 1).trim();
1116
+ if (startText === "") {
1117
+ const suffix = Number(endText);
1118
+ if (endText === "" || !Number.isInteger(suffix) || suffix <= 0) return void 0;
1119
+ if (size === 0) return { satisfiable: false };
1120
+ return {
1121
+ satisfiable: true,
1122
+ start: Math.max(0, size - suffix),
1123
+ end: size - 1
1124
+ };
1125
+ }
1126
+ const start = Number(startText);
1127
+ if (!Number.isInteger(start) || start < 0) return void 0;
1128
+ if (start >= size) return { satisfiable: false };
1129
+ if (endText === "") return {
1130
+ satisfiable: true,
1131
+ start,
1132
+ end: size - 1
1133
+ };
1134
+ const end = Number(endText);
1135
+ if (!Number.isInteger(end) || end < start) return void 0;
1136
+ return {
1137
+ satisfiable: true,
1138
+ start,
1139
+ end: Math.min(end, size - 1)
1140
+ };
1141
+ }
1142
+ /**
1143
+ * Resolve the `Access-Control-Allow-Origin` value for a request.
1144
+ *
1145
+ * @remarks
1146
+ * `'*'` and a single origin string pass straight through. An allow-list
1147
+ * echoes the request's `Origin` only when it is present in the list, else
1148
+ * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1149
+ * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1150
+ * NEVER reflected even if `'null'` were listed, closing the hostile-context
1151
+ * cross-origin-access hole.
1152
+ *
1153
+ * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
1154
+ * @param requestOrigin - The request's `Origin` header value, if present
1155
+ * @returns The allow-origin value to send, or `undefined` to set no header
1156
+ *
1157
+ * @example
1158
+ * ```ts
1159
+ * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'
1160
+ * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected
1161
+ * ```
1162
+ */
1163
+ function resolveOrigin(origin, requestOrigin) {
1164
+ if (isString(origin)) return origin;
1165
+ if (!isString(requestOrigin)) return void 0;
1166
+ if (requestOrigin === "null") return void 0;
1167
+ return origin.includes(requestOrigin) ? requestOrigin : void 0;
1168
+ }
1169
+ /**
1170
+ * Merge a `Vary` value into an existing `Vary` header without duplication.
1171
+ *
1172
+ * @remarks
1173
+ * Splits `existing` on `,`, trims each member, and appends `value` only when
1174
+ * no existing member already matches it case-insensitively (`Vary` header
1175
+ * names are case-insensitive). Preserves the existing members' order and
1176
+ * appends the new one last.
1177
+ *
1178
+ * @param existing - The current `Vary` header value, if any
1179
+ * @param value - The header name to ensure is listed
1180
+ * @returns The merged `Vary` value
1181
+ *
1182
+ * @example
1183
+ * ```ts
1184
+ * mergeVary(undefined, 'Origin') // 'Origin'
1185
+ * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)
1186
+ * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'
1187
+ * ```
1188
+ */
1189
+ function mergeVary(existing, value) {
1190
+ const members = existing === void 0 ? [] : existing.split(",").map((member) => member.trim()).filter((member) => member.length > 0);
1191
+ return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
1192
+ }
1193
+ /**
1194
+ * Resolve one opt-out, value-bearing security header.
1195
+ *
1196
+ * @remarks
1197
+ * The shared "a `string` value, or `false` to omit, or a default when unset"
1198
+ * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1199
+ * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1200
+ * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1201
+ *
1202
+ * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default
1203
+ * @param fallback - The secure-default value used when `value` is unset
1204
+ * @returns The header value to set, or `undefined` to omit the header
1205
+ *
1206
+ * @example
1207
+ * ```ts
1208
+ * resolveSecurityHeader(undefined, 'DENY') // 'DENY'
1209
+ * resolveSecurityHeader(false, 'DENY') // undefined — omitted
1210
+ * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override
1211
+ * ```
1212
+ */
1213
+ function resolveSecurityHeader(value, fallback) {
1214
+ if (value === false) return void 0;
1215
+ return value ?? fallback;
1216
+ }
1217
+ /**
1218
+ * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1219
+ * header + `context.state`.
1220
+ *
1221
+ * @remarks
1222
+ * A request id is echoed RAW into a response header and log lines, so an
1223
+ * untrusted one is a header-injection + log-injection + DoS vector. This
1224
+ * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
1225
+ * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
1226
+ * TOTAL — never throws.
1227
+ *
1228
+ * @param value - The candidate incoming request id
1229
+ * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
1230
+ *
1231
+ * @example
1232
+ * ```ts
1233
+ * isValidRequestId('req_abc-123') // true
1234
+ * isValidRequestId('bad\r\nheader') // false
1235
+ * ```
1236
+ */
1237
+ function isValidRequestId(value) {
1238
+ return REQUEST_ID_PATTERN.test(value);
1239
+ }
1240
+ /**
1241
+ * Compute the `/64` network of a full IPv6 address, or `undefined` when the
1242
+ * input is not a plain IPv6 address to collapse.
1243
+ *
1244
+ * @remarks
1245
+ * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
1246
+ * is the identity) or any string that does not expand to exactly eight
1247
+ * hextets. Expands a single `::` into the missing zero hextets, takes the
1248
+ * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
1249
+ * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
1250
+ * first. Total — a malformed address returns `undefined`.
1251
+ *
1252
+ * @param address - The candidate IPv6 address
1253
+ * @returns The `/64` network string, or `undefined` when not a plain IPv6 address
1254
+ *
1255
+ * @example
1256
+ * ```ts
1257
+ * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1258
+ * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1259
+ * ```
1260
+ */
1261
+ function ipv6Network(address) {
1262
+ if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
1263
+ const percent = address.indexOf("%");
1264
+ const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
1265
+ if (halves.length > 2) return void 0;
1266
+ const head = halves[0] === "" ? [] : halves[0].split(":");
1267
+ const tail = halves.length === 2 ? halves[1] === "" ? [] : halves[1].split(":") : [];
1268
+ let groups;
1269
+ if (halves.length === 2) {
1270
+ const missing = 8 - head.length - tail.length;
1271
+ if (missing < 0) return void 0;
1272
+ groups = [
1273
+ ...head,
1274
+ ...Array.from({ length: missing }, () => "0"),
1275
+ ...tail
1276
+ ];
1277
+ } else groups = head;
1278
+ if (groups.length !== 8) return void 0;
1279
+ const prefix = [];
1280
+ for (const group of groups.slice(0, 4)) {
1281
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return void 0;
1282
+ prefix.push(Number.parseInt(group, 16).toString(16));
1283
+ }
1284
+ return `${prefix.join(":")}::/64`;
1285
+ }
1286
+ /**
1287
+ * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
1288
+ * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1289
+ *
1290
+ * @remarks
1291
+ * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1292
+ * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1293
+ * real identity is the `/64` network. Delegates the IPv6 collapse to
1294
+ * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
1295
+ * a malformed string) is kept unchanged.
1296
+ *
1297
+ * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
1298
+ * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
1299
+ *
1300
+ * @example
1301
+ * ```ts
1302
+ * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1303
+ * clientRateKey('192.0.2.1') // '192.0.2.1'
1304
+ * ```
1305
+ */
1306
+ function clientRateKey(address) {
1307
+ return ipv6Network(address) ?? address;
1308
+ }
1309
+ /**
1310
+ * Serialize one {@link SSEMessage} to the SSE wire.
1311
+ *
1312
+ * @remarks
1313
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1314
+ * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1315
+ * (so a consuming parser's multi-`data` concat reproduces the original
1316
+ * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1317
+ * a `data:` line), then the terminating blank line.
1318
+ *
1319
+ * @param message - The event to serialize
1320
+ * @returns The SSE wire text for the event (terminated by a blank line)
1321
+ *
1322
+ * @example
1323
+ * ```ts
1324
+ * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\ndata: hello\n\n'
1325
+ * serializeEvent({ data: 'multi\nline' }) // 'data: multi\ndata: line\n\n'
1326
+ * ```
1327
+ */
1328
+ function serializeEvent(message) {
1329
+ const lines = [];
1330
+ if (message.event !== void 0) lines.push(`event: ${message.event}`);
1331
+ if (message.id !== void 0) lines.push(`id: ${message.id}`);
1332
+ if (message.retry !== void 0) lines.push(`retry: ${message.retry}`);
1333
+ for (const segment of message.data.split(/\r\n|\r|\n/)) lines.push(`data: ${segment}`);
1334
+ return `${lines.join("\n")}\n\n`;
1335
+ }
1336
+ /**
1337
+ * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1338
+ * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1339
+ *
1340
+ * @remarks
1341
+ * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1342
+ * merged under any `options.headers` (a seam-owned key is never overridden),
1343
+ * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1344
+ * `write` serializes one message ({@link serializeEvent}) and enqueues it;
1345
+ * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1346
+ * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1347
+ * by `end()`, or the consumer cancelled the stream), so a late write never
1348
+ * throws.
1349
+ *
1350
+ * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1351
+ * @returns The {@link StreamInterface} handle
1352
+ *
1353
+ * @example
1354
+ * ```ts
1355
+ * const stream = openStream()
1356
+ * stream.write({ event: 'token', data: 'hello' })
1357
+ * stream.end()
1358
+ * // return stream.response from the route handler
1359
+ * ```
1360
+ */
1361
+ function openStream(options) {
1362
+ const encoder = new TextEncoder();
1363
+ let closed = false;
1364
+ let controller;
1365
+ const body = new ReadableStream({
1366
+ start(streamController) {
1367
+ controller = streamController;
1368
+ },
1369
+ cancel() {
1370
+ closed = true;
1371
+ }
1372
+ });
1373
+ const headers = new Headers({
1374
+ ...SSE_HEADERS,
1375
+ ...options?.headers
1376
+ });
1377
+ const response = new Response(body, {
1378
+ status: options?.status ?? 200,
1379
+ headers
1380
+ });
1381
+ const enqueue = (text) => {
1382
+ if (closed || controller === void 0) return;
1383
+ controller.enqueue(encoder.encode(text));
1384
+ };
1385
+ return {
1386
+ response,
1387
+ get closed() {
1388
+ return closed;
1389
+ },
1390
+ write(message) {
1391
+ enqueue(serializeEvent(message));
1392
+ },
1393
+ comment(text) {
1394
+ enqueue(`: ${text}\n\n`);
1395
+ },
1396
+ end() {
1397
+ if (closed) return;
1398
+ closed = true;
1399
+ controller?.close();
1400
+ }
1401
+ };
1402
+ }
1403
+ /**
1404
+ * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1405
+ * or `prototype` — the three keys that, assigned onto a normal object, can
1406
+ * reach and mutate `Object.prototype`.
1407
+ *
1408
+ * @param key - The candidate object key
1409
+ * @returns `true` when `key` is one of the three prototype-pollution keys
1410
+ *
1411
+ * @example
1412
+ * ```ts
1413
+ * isDangerousKey('__proto__') // true
1414
+ * isDangerousKey('name') // false
1415
+ * ```
1416
+ */
1417
+ function isDangerousKey(key) {
1418
+ return key === "__proto__" || key === "constructor" || key === "prototype";
1419
+ }
1420
+ /**
1421
+ * Recursively STRIP the prototype-pollution keys from a parsed value IN
1422
+ * PLACE.
1423
+ *
1424
+ * @remarks
1425
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1426
+ * enumerable `__proto__` DATA property — but that own key becomes a
1427
+ * pollution gadget the moment a downstream deep-merge copies it onto a live
1428
+ * object. This walks the value and `delete`s any own {@link isDangerousKey}
1429
+ * key at every depth, recursing into nested objects + array elements.
1430
+ * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1431
+ * freshly-parsed value (which nothing else holds yet).
1432
+ *
1433
+ * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1434
+ * @returns The same `value`, with every dangerous key removed at every depth
1435
+ *
1436
+ * @example
1437
+ * ```ts
1438
+ * scrubPrototype(JSON.parse('{"__proto__":{"polluted":true},"name":"ok"}'))
1439
+ * // { name: 'ok' } — the __proto__ key is gone
1440
+ * ```
1441
+ */
1442
+ function scrubPrototype(value) {
1443
+ if (Array.isArray(value)) {
1444
+ for (const item of value) scrubPrototype(item);
1445
+ return value;
1446
+ }
1447
+ if (isRecord(value)) {
1448
+ for (const key of Object.keys(value)) {
1449
+ if (isDangerousKey(key)) {
1450
+ Reflect.deleteProperty(value, key);
1451
+ continue;
1452
+ }
1453
+ scrubPrototype(value[key]);
1454
+ }
1455
+ return value;
1456
+ }
1457
+ return value;
1458
+ }
1459
+ /**
1460
+ * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
1461
+ *
1462
+ * @remarks
1463
+ * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
1464
+ * throwing a {@link ContentTooLargeError} (413) the instant the running total
1465
+ * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
1466
+ * collecting an unbounded body. A bodyless request (`request.body === null`)
1467
+ * resolves an empty array. A non-positive `limit` means unbounded.
1468
+ *
1469
+ * @param request - The `Request` to drain
1470
+ * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
1471
+ * @returns The full request body as one `Uint8Array`
1472
+ * @throws {ContentTooLargeError} When the body exceeds `limit`
1473
+ *
1474
+ * @example
1475
+ * ```ts
1476
+ * const bytes = await collectRequestBody(request, 1_048_576)
1477
+ * ```
1478
+ */
1479
+ async function collectRequestBody(request, limit) {
1480
+ if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
1481
+ const reader = request.body.getReader();
1482
+ const chunks = [];
1483
+ let total = 0;
1484
+ for (;;) {
1485
+ const { done, value } = await reader.read();
1486
+ if (done) break;
1487
+ total += value.byteLength;
1488
+ if (limit > 0 && total > limit) {
1489
+ await reader.cancel();
1490
+ throw new ContentTooLargeError(limit);
1491
+ }
1492
+ chunks.push(value);
1493
+ }
1494
+ const merged = new Uint8Array(total);
1495
+ let offset = 0;
1496
+ for (const chunk of chunks) {
1497
+ merged.set(chunk, offset);
1498
+ offset += chunk.byteLength;
1499
+ }
1500
+ return merged;
1501
+ }
1502
+ /**
1503
+ * Narrow a raw `Content-Encoding` header value to a decompressible
1504
+ * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1505
+ * whether a request body needs transparent decompression.
1506
+ *
1507
+ * @remarks
1508
+ * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1509
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1510
+ * the proposal). An absent header, `identity`, an unknown value, or a
1511
+ * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1512
+ * TOTAL — never asserts the loose `string | null` header.
1513
+ *
1514
+ * @param header - The raw `Content-Encoding` header value
1515
+ * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
1516
+ *
1517
+ * @example
1518
+ * ```ts
1519
+ * requestEncoding('gzip') // 'gzip'
1520
+ * requestEncoding('br') // undefined — unsupported by DecompressionStream
1521
+ * ```
1522
+ */
1523
+ function requestEncoding(header) {
1524
+ if (!isString(header)) return void 0;
1525
+ const value = header.trim().toLowerCase();
1526
+ return value === "gzip" || value === "deflate" ? value : void 0;
1527
+ }
1528
+ /**
1529
+ * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
1530
+ * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
1531
+ * the zip-bomb defense.
1532
+ *
1533
+ * @remarks
1534
+ * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1535
+ * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1536
+ * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1537
+ * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
1538
+ * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1539
+ * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
1540
+ * (never conflated with the cap). A non-positive `cap` means uncapped.
1541
+ *
1542
+ * @param bytes - The compressed bytes to decompress
1543
+ * @param encoding - The {@link Encoding} the bytes are compressed with
1544
+ * @param cap - The maximum decompressed byte count; a non-positive value means uncapped
1545
+ * @returns The decompressed bytes
1546
+ * @throws {ContentTooLargeError} When decompressed output would exceed `cap`
1547
+ * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
1548
+ */
1549
+ async function decompressRequestBody(bytes, encoding, cap) {
1550
+ let total = 0;
1551
+ const capStream = new TransformStream({ transform(chunk, controller) {
1552
+ total += chunk.byteLength;
1553
+ if (cap > 0 && total > cap) {
1554
+ controller.error(new ContentTooLargeError(cap));
1555
+ return;
1556
+ }
1557
+ controller.enqueue(chunk);
1558
+ } });
1559
+ const reader = new ReadableStream({ start(controller) {
1560
+ controller.enqueue(bytes);
1561
+ controller.close();
1562
+ } }).pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream).getReader();
1563
+ const chunks = [];
1564
+ let size = 0;
1565
+ try {
1566
+ for (;;) {
1567
+ const { done, value } = await reader.read();
1568
+ if (done) break;
1569
+ chunks.push(value);
1570
+ size += value.byteLength;
1571
+ }
1572
+ } catch (error) {
1573
+ if (error instanceof ContentTooLargeError) throw error;
1574
+ throw new HTTPError(400, "malformed compressed request body");
1575
+ }
1576
+ const merged = new Uint8Array(size);
1577
+ let offset = 0;
1578
+ for (const chunk of chunks) {
1579
+ merged.set(chunk, offset);
1580
+ offset += chunk.byteLength;
1581
+ }
1582
+ return merged;
1583
+ }
1584
+ /**
1585
+ * Collect + decode a `Request` body — the shared body-collection pipeline
1586
+ * surfaced to middleware and handlers as the middleware context's cached
1587
+ * `body()`.
1588
+ *
1589
+ * @remarks
1590
+ * Collects the wire body capped at `options.limit` bytes ({@link
1591
+ * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),
1592
+ * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body
1593
+ * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1594
+ * `options.decompression`, default {@link
1595
+ * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1596
+ * content type: `application/json` is parsed via `@orkestrel/contract`'s
1597
+ * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1598
+ * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1599
+ * decodes to `undefined`.
1600
+ *
1601
+ * @param request - The `Request` to read the body from
1602
+ * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1603
+ * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1604
+ * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1605
+ * @throws {HTTPError} When the compressed body is corrupt (400)
1606
+ *
1607
+ * @example
1608
+ * ```ts
1609
+ * const body = await readBody(request, { limit: 1_048_576 })
1610
+ * ```
1611
+ */
1612
+ async function readBody(request, options) {
1613
+ const limit = options?.limit ?? 1048576;
1614
+ const decompression = options?.decompression ?? 16777216;
1615
+ const wire = await collectRequestBody(request, limit);
1616
+ const encoding = requestEncoding(request.headers.get("content-encoding"));
1617
+ const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
1618
+ if (bytes.length === 0) return void 0;
1619
+ const contentType = request.headers.get("content-type");
1620
+ const semicolon = contentType === null ? -1 : contentType.indexOf(";");
1621
+ const bareType = contentType === null ? "" : (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase();
1622
+ const text = new TextDecoder().decode(bytes);
1623
+ if (bareType === "application/json") return scrubPrototype(parseJSON(text));
1624
+ return text;
1625
+ }
1626
+ //#endregion
1627
+ //#region src/core/Negotiator.ts
1628
+ /**
1629
+ * The content-negotiation machine over the weighted `Accept` family — a
1630
+ * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1631
+ * {@link NegotiatorInterface}.
1632
+ *
1633
+ * @remarks
1634
+ * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1635
+ * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1636
+ * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
1637
+ * rest of the substrate uses — one parser, never two. `format` reads the
1638
+ * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1639
+ * the winner — or answers `406 Not Acceptable`.
1640
+ *
1641
+ * @example
1642
+ * ```ts
1643
+ * const negotiator = new Negotiator()
1644
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
1645
+ * // 'text/html'
1646
+ * ```
1647
+ */
1648
+ var Negotiator = class {
1649
+ negotiate(header, available) {
1650
+ if (available.length === 0) return void 0;
1651
+ const entries = parseAcceptHeader(header);
1652
+ if (entries.length === 0) return available[0];
1653
+ let best;
1654
+ let bestQuality = 0;
1655
+ let bestRank = Number.POSITIVE_INFINITY;
1656
+ for (const candidate of available) {
1657
+ const match = matchMediaType(entries, candidate);
1658
+ if (match === void 0) continue;
1659
+ const { q, rank } = match;
1660
+ if (q > bestQuality || q === bestQuality && rank < bestRank) {
1661
+ best = candidate;
1662
+ bestQuality = q;
1663
+ bestRank = rank;
1664
+ }
1665
+ }
1666
+ return best;
1667
+ }
1668
+ encoding(header, available) {
1669
+ return negotiateEncoding(header, available);
1670
+ }
1671
+ language(header, available) {
1672
+ if (available.length === 0) return void 0;
1673
+ const entries = parseAcceptHeader(header);
1674
+ if (entries.length === 0) return available[0];
1675
+ let best;
1676
+ let bestQuality = 0;
1677
+ for (const candidate of available) {
1678
+ const quality = languageQuality(entries, candidate);
1679
+ if (quality > bestQuality) {
1680
+ best = candidate;
1681
+ bestQuality = quality;
1682
+ }
1683
+ }
1684
+ return best;
1685
+ }
1686
+ /**
1687
+ * @remarks
1688
+ * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1689
+ * server boundary classifies them, never this negotiator.
1690
+ */
1691
+ async format(request, context, handlers) {
1692
+ const keys = Object.keys(handlers);
1693
+ const header = request.headers.get("accept");
1694
+ const type = header === null ? keys[0] : this.negotiate(header, keys);
1695
+ if (type === void 0) return new Response("Not Acceptable", { status: 406 });
1696
+ const handler = handlers[type];
1697
+ if (handler === void 0) return new Response("Not Acceptable", { status: 406 });
1698
+ return handler(request, context);
1699
+ }
1700
+ };
1701
+ //#endregion
1702
+ //#region src/core/factories.ts
1703
+ /**
1704
+ * Create a {@link NegotiatorInterface} — the reusable content-negotiation
1705
+ * machine over the weighted `Accept` family.
1706
+ *
1707
+ * @remarks
1708
+ * Prefer this over `new Negotiator()` at call sites that only need the
1709
+ * interface.
1710
+ *
1711
+ * @returns A {@link NegotiatorInterface}
1712
+ *
1713
+ * @example
1714
+ * ```ts
1715
+ * import { createNegotiator } from '@src/core'
1716
+ *
1717
+ * const negotiator = createNegotiator()
1718
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
1719
+ * // 'text/html'
1720
+ * ```
1721
+ */
1722
+ function createNegotiator() {
1723
+ return new Negotiator();
1724
+ }
1725
+ //#endregion
1726
+ export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, appendCookie, clearCookie, clientRateKey, codingQuality, collectRequestBody, compose, computeBodyETag, createNegotiator, decodeBase64Url, decodeCookieValue, decodeTokenPayload, decompressRequestBody, encodeBase64Url, ipv6Network, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isValidRequestId, languageQuality, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, openStream, parseAcceptHeader, parseCookies, parseRange, readBody, readSignedCookie, requestEncoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, writeSignedCookie };
1727
+
1728
+ //# sourceMappingURL=index.js.map