@orkestrel/server 0.0.2 → 0.0.4

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