@orkestrel/server 0.0.30 → 0.0.32
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["createNetServer","createHTTPServer"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/Negotiator.ts","../../../src/server/ServerBinding.ts","../../../src/server/Server.ts","../../../src/server/Signer.ts","../../../src/server/Stream.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { Encoding } from './types.js'\n\n// The substrate's tunable defaults — only the constants with a real consumer\n// inside this package: a capability arrives with its first real consumer,\n// never speculatively. Each is frozen or declared\n// readonly, so a consumer reads but never mutates the shared default. The\n// defaults only `@orkestrel/middleware` needs (rate limiting, CSRF, sessions,\n// static serving, multipart) stay out of this file; they belong to that\n// package's own `constants.ts`.\n\n/**\n * Names the default graceful-stop deadline `stop()` gives in-flight requests and\n * claimed upgraded sockets, `10_000` ms.\n */\nexport const DEFAULT_DRAIN_MS = 10_000\n\n/**\n * Names the `node:http` default `requestTimeout`, `300_000` ms, which applies when\n * `timeouts.request` is omitted.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 300_000\n\n/**\n * Names the cap of the `node:http` default `headersTimeout`, `60_000` ms: when\n * `timeouts.headers` is omitted, the header timeout is the lesser of this cap and the\n * request timeout.\n */\nexport const DEFAULT_HEADERS_TIMEOUT_MS = 60_000\n\n/**\n * Names the `Symbol.for`-interned brand `HTTPError` carries,\n * `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across\n * package copies. A consumer never sets it by hand.\n *\n * @remarks\n * The brand exists for the dual-package hazard — a version-skewed or\n * workspace-linked duplicate install — where `instanceof` alone fails because\n * each copy's `HTTPError` constructor is a distinct object.\n * `Symbol.for` interns the symbol on the global symbol registry, so every\n * copy of this package that evaluates this key resolves the same symbol\n * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,\n * unequal symbol per copy and defeat the whole point of a cross-copy brand.\n */\nexport const HTTP_ERROR_BRAND = Symbol.for('@orkestrel/server.HTTPError')\n\n/**\n * Names the default maximum request body size `readBody` accepts before a 413,\n * `1_048_576` bytes.\n */\nexport const DEFAULT_BODY_LIMIT = 1_048_576\n\n/**\n * Names the default maximum decompressed request body size, `16_777_216` bytes — the\n * zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when\n * it transparently decompresses a `Content-Encoding` request body.\n *\n * @remarks\n * A small compressed body (under {@link DEFAULT_BODY_LIMIT} on the wire)\n * can inflate by many orders of magnitude — a classic decompression bomb.\n * Capping the decompressed byte count makes the pipe abort the moment the\n * output would exceed this, before the full bomb is materialized, so the\n * inflation can never exhaust memory. Defaults to `16 MiB` — a generous\n * ceiling for a legitimate compressed JSON / form body, far below an OOM. A\n * consumer raises it through {@link import('./types.js').BodyOptions}\n * `decompression` for a workload that genuinely ships larger decompressed\n * bodies.\n */\nexport const DEFAULT_DECOMPRESSED_LIMIT = 16_777_216\n\n/**\n * Holds the SSE response headers a `Stream` sets on its response, merged under any\n * caller `headers` so a caller repeating one of these keys replaces its value.\n *\n * @remarks\n * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`\n * keeps a proxy from caching the stream; `keep-alive` holds the connection\n * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so\n * events flush promptly rather than batching. Frozen so a consumer can read\n * but never mutate the shared default; the merged keys are\n * {@link import('./types.js').StreamOptions.headers}.\n */\nexport const SSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n\t'Content-Type': 'text/event-stream; charset=utf-8',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n\t'X-Accel-Buffering': 'no',\n})\n\n/**\n * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`\n * to match, `^[A-Za-z0-9_-]{1,200}$`.\n *\n * @remarks\n * An incoming id carrying CRLF, log-injection input, a control character,\n * or more characters than the pattern admits fails the match and is rejected —\n * a fresh id is minted instead — so it never rides into a response header or\n * `context.state`. Frozen so a consumer can read but never mutate the shared\n * default.\n */\nexport const REQUEST_ID_PATTERN: Readonly<RegExp> = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/)\n\n/**\n * Defines the `1*DIGIT` form `parseRange` requires of a `Range` bound, `^[0-9]+$`.\n *\n * @remarks\n * Mirrors the `first-pos`, `last-pos`, and `suffix-length` rules of RFC 9110\n * § 14.1.1. A numeral `Number` reads but the grammar refuses — a hexadecimal,\n * octal, or binary prefix, an exponent, a sign, or a decimal point — fails the\n * match, as does a digit outside ASCII, which `Number` reads as `NaN`.\n */\nexport const RANGE_BOUND_PATTERN: Readonly<RegExp> = Object.freeze(/^[0-9]+$/)\n\n/**\n * Defines the line terminators of the SSE wire, `\\r\\n`, `\\r`, and `\\n`, which\n * `serializeEvent` and `serializeComment` split text on.\n */\nexport const SSE_LINE_PATTERN: Readonly<RegExp> = Object.freeze(/\\r\\n|\\r|\\n/)\n\n/**\n * Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,\n * beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that\n * helper also applies.\n *\n * @remarks\n * The text-shaped application types worth compressing (JSON / JavaScript /\n * XML / SVG / WASM / a few document formats) — never already-compressed\n * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's\n * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`\n * withholds `add` / `delete` / `clear` from the shared default, so a consumer\n * reads it without reaching a mutator.\n */\nexport const COMPRESSIBLE_TYPES: ReadonlySet<string> = Object.freeze(\n\tnew Set([\n\t\t'application/json',\n\t\t'application/javascript',\n\t\t'application/xml',\n\t\t'application/xhtml+xml',\n\t\t'application/rss+xml',\n\t\t'application/atom+xml',\n\t\t'application/ld+json',\n\t\t'application/manifest+json',\n\t\t'application/vnd.api+json',\n\t\t'application/wasm',\n\t\t'image/svg+xml',\n\t\t'application/pdf',\n\t]),\n)\n\n/**\n * Lists the default {@link Encoding} content-codings the substrate offers, in\n * preference order — `gzip` then `deflate`.\n *\n * @remarks\n * `identity` (no compression) is always implicitly acceptable and is not\n * listed here — it is the fall-through when a client accepts none of these.\n * Brotli is omitted per the core's `CompressionStream`-only decision (see\n * {@link Encoding}). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const DEFAULT_ENCODINGS: readonly Encoding[] = Object.freeze(['gzip', 'deflate'])\n\n/** Names the identity brand carried by lifecycle errors across package copies. */\nexport const SERVER_ERROR_BRAND = Symbol.for('@orkestrel/server.ServerError')\n\n/** Names the identity brand carried by body-limit errors across package copies. */\nexport const CONTENT_TOO_LARGE_ERROR_BRAND = Symbol.for('@orkestrel/server.ContentTooLargeError')\n","import type { ServerErrorCode } from './types.js'\nimport {\n\tholds,\n\tINTRINSICS,\n\tisFunction,\n\tisInstance,\n\tisNumber,\n\tisObject,\n\tisString,\n} from '@orkestrel/contract'\nimport { CONTENT_TOO_LARGE_ERROR_BRAND, HTTP_ERROR_BRAND, SERVER_ERROR_BRAND } from './constants.js'\n\n/**\n * Represents an error a handler (or middleware) throws to produce an HTTP response of a\n * specific status.\n *\n * @remarks\n * Carries the HTTP `status` to send and an optional `context` record (the\n * offending field / value). The server's built-in error boundary catches it\n * and renders a response of `status` with the error's `message` as the body,\n * and no body for 204, 205, and 304 — so an `HTTPError`'s message is always\n * client-facing (it is the handler's deliberate signal), unlike a generic\n * throw whose message is hidden unless `expose` is set. A `status` the\n * `Response` constructor refuses, an integer below 200 or above 599 or a\n * status that is not an integer, renders `500` instead. Subclass it (as {@link ContentTooLargeError} does) for\n * specific statuses, or throw it directly. Narrow a caught value with\n * {@link isHTTPError}. The machine-readable discriminator is `status`; there is\n * no separate `code`.\n *\n * @example\n * ```ts\n * import { HTTPError } from '@src/server'\n *\n * const handler = async (request: Request): Promise<Response> => {\n * \tconst user = await find(new URL(request.url).searchParams.get('id'))\n * \tif (user === undefined) throw new HTTPError(404, 'user not found')\n * \treturn Response.json(user)\n * }\n * ```\n */\nexport class HTTPError extends Error {\n\treadonly status: number\n\treadonly context?: Readonly<Record<string, unknown>>\n\tdeclare readonly [HTTP_ERROR_BRAND]: this\n\n\tconstructor(status: number, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tObject.defineProperty(this, HTTP_ERROR_BRAND, { value: this })\n\t\tthis.name = 'HTTPError'\n\t\tthis.status = status\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Represents the {@link HTTPError} thrown when a request body exceeds the body\n * pipeline's size limit — a `413 Content Too Large`.\n *\n * @remarks\n * Thrown by `readBody` (and the middleware context's cached `body()`) when\n * the received bytes exceed the configured {@link\n * import('./types.js').BodyOptions.limit}, carrying the `limit` in its\n * `context`. The server's error boundary renders it as a 413.\n *\n * @example\n * ```ts\n * import { ContentTooLargeError, isHTTPError } from '@src/server'\n *\n * try {\n * \tawait readBody(request, { limit: 1024 })\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status) // 413\n * }\n * ```\n */\nexport class ContentTooLargeError extends HTTPError {\n\tconstructor(limit: number) {\n\t\tsuper(413, `request body exceeds the ${limit}-byte limit`, { limit })\n\t\tObject.defineProperty(this, CONTENT_TOO_LARGE_ERROR_BRAND, { value: this })\n\t\tthis.name = 'ContentTooLargeError'\n\t}\n}\n\n/**\n * Narrows an unknown caught value to an {@link HTTPError}, including a subclass such\n * as {@link ContentTooLargeError}, and recognizes an instance from another copy of\n * this package through its own identity brand.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is an {@link HTTPError}; false otherwise\n *\n * @remarks\n * Requires a global Error instance with a derived prototype, its own identity brand,\n * a numeric status, a string message, and an absent or object-valued context.\n * Callable contexts are accepted. Subclass names are unrestricted.\n * Transparent proxies and branded plain objects are rejected.\n *\n * @example\n * ```ts\n * import { isHTTPError } from '@src/server'\n *\n * try {\n * \tawait handle(request)\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status, error.message)\n * }\n * ```\n */\nexport function isHTTPError(value: unknown): value is HTTPError {\n\treturn holds(() => {\n\t\tif (!isInstance(value, Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tif (!INTRINSICS.own(value, HTTP_ERROR_BRAND)) return false\n\t\tif (INTRINSICS.describe(value, HTTP_ERROR_BRAND)?.value !== value) return false\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\tisNumber(INTRINSICS.reflect.read(value, 'status')) &&\n\t\t\tisString(INTRINSICS.reflect.read(value, 'message')) &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n\n/**\n * Recognizes a branded body-limit error, including subclasses and other package copies.\n *\n * @example\n * ```ts\n * isContentTooLargeError(new ContentTooLargeError(1024)) // true\n * ```\n */\nexport function isContentTooLargeError(value: unknown): value is ContentTooLargeError {\n\treturn holds(\n\t\t() =>\n\t\t\tisHTTPError(value) &&\n\t\t\tINTRINSICS.own(value, CONTENT_TOO_LARGE_ERROR_BRAND) &&\n\t\t\tINTRINSICS.describe(value, CONTENT_TOO_LARGE_ERROR_BRAND)?.value === value,\n\t)\n}\n\n/**\n * Represents the error this package raises when a caller programmed a call the\n * entity refuses, carrying `'STATUS'`, `'NEXT'`, `'EVENT'`, or `'SECRET'` as its code.\n *\n * @remarks\n * Carries a machine-readable {@link ServerErrorCode} and an optional `context`\n * record naming the offending facts. This is a programmer error, so it carries\n * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that\n * invoked the lifecycle method, a `'NEXT'` refusal of a second `next` call or\n * of a `next` call with an argument escapes its\n * middleware into the request boundary, which reaches it as a generic 500 with\n * the message hidden unless `expose` is set, and an `'EVENT'` refusal is raised\n * to the caller that serialized an SSE message, its `context.field` naming the\n * refused field, and a `'SECRET'` refusal is raised to the caller that built a\n * signer from a malformed secret, its `context` naming the refused positions,\n * or the received type for a value that is not a string or a readable list, and holding\n * no secret text. Throw an {@link HTTPError} for a\n * client-facing fault instead. Narrow a caught value with\n * {@link isServerError}.\n *\n * @example\n * ```ts\n * import { ServerError } from '@src/server'\n *\n * const error = new ServerError('STATUS', \"server cannot start from 'listening'\", {\n * \tstatus: 'listening',\n * })\n * error.code // 'STATUS'\n * ```\n */\nexport class ServerError extends Error {\n\treadonly code: ServerErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(code: ServerErrorCode, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tObject.defineProperty(this, SERVER_ERROR_BRAND, { value: this })\n\t\tthis.name = 'ServerError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal\n * of a call the caller programmed.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link ServerError}; false otherwise\n *\n * @remarks\n * Requires the own identity brand, a declared code, a string message, and an absent\n * or object-valued context on a global Error with a derived prototype.\n * Callable contexts and subclasses are accepted; transparent proxies are rejected.\n *\n * @example\n * ```ts\n * import { createServer, isServerError } from '@src/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })\n * await server.start()\n * try {\n * \tawait server.start()\n * } catch (error) {\n * \tif (isServerError(error)) console.log(error.code) // 'STATUS'\n * }\n * await server.stop()\n * ```\n */\nexport function isServerError(value: unknown): value is ServerError {\n\treturn holds(() => {\n\t\tif (!isInstance(value, Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tif (!INTRINSICS.own(value, SERVER_ERROR_BRAND)) return false\n\t\tif (INTRINSICS.describe(value, SERVER_ERROR_BRAND)?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\t(code === 'STATUS' || code === 'NEXT' || code === 'EVENT' || code === 'SECRET') &&\n\t\t\tisString(INTRINSICS.reflect.read(value, 'message')) &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n","import type { AddressInfo } from 'node:net'\nimport { isNumber, isRecord, isString } from '@orkestrel/contract'\n\n// The module's guards. A total `Guard<T>` narrows a type rather than answering\n// a plain question, so it lives here rather than beside the boolean predicates\n// `helpers.ts` keeps (`isCookieName`, `isCompressibleType`, `isValidRequestId`).\n// This file sits at the bottom of the module's graph beside `helpers.ts`,\n// imports the `node:net` address type and the `@orkestrel/contract` guards, and\n// never an implementation class.\n\n/**\n * Checks whether a `node:net` `server.address()` return is the structured\n * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`\n * or `null` — the total, never-throwing narrow `discoverPort`\n * and the `Server`'s own port resolution read the bound port through.\n *\n * @remarks\n * Checks the `address`, `family`, and `port` members `node:net` declares as\n * `string`, `string`, and `number`.\n *\n * @param value - The `server.address()` return (`AddressInfo | string | null`)\n * @returns True if `value` is an `AddressInfo`; false otherwise\n *\n * @example\n * ```ts\n * import { isAddressInfo } from '@src/server'\n *\n * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true\n * isAddressInfo(null) // false\n * ```\n */\nexport function isAddressInfo(value: unknown): value is AddressInfo {\n\treturn (\n\t\tisRecord(value) && isString(value.address) && isString(value.family) && isNumber(value.port)\n\t)\n}\n","import type {\n\tAcceptEntry,\n\tBodyOptions,\n\tCookieOptions,\n\tEncoding,\n\tMediaMatch,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tRangeSpec,\n\tSignerInterface,\n\tSSEMessage,\n\tTokenOptions,\n\tTokenSecret,\n} from './types.js'\nimport { addAbortListener, once } from 'node:events'\nimport { createServer as createNetServer } from 'node:net'\nimport { decodeBase64URL, encodeBase64URL, encodeHex } from '@orkestrel/codec'\nimport {\n\tattempt,\n\tholds,\n\tisArray,\n\tisCodedError,\n\tisError,\n\tisFiniteNumber,\n\tisInstance,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisSafeInteger,\n\tisString,\n\tparseJSON,\n\tsettle,\n} from '@orkestrel/contract'\nimport {\n\tCOMPRESSIBLE_TYPES,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DECOMPRESSED_LIMIT,\n\tRANGE_BOUND_PATTERN,\n\tREQUEST_ID_PATTERN,\n\tSSE_LINE_PATTERN,\n} from './constants.js'\nimport { ContentTooLargeError, HTTPError, isHTTPError, ServerError } from './errors.js'\nimport { isAddressInfo } from './validators.js'\n\n// The middleware seam's composition engine — a pure function, not a class:\n// `compose` has no instance state, so it lives here rather than as an entity.\n// The returning onion: each middleware may transform the response (`await\n// next()` then mutate the result) or short-circuit (return without calling\n// `next`). Every layer and the terminal receive the same request and context.\n\n/**\n * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`\n * handler into one request handler — the middleware seam.\n *\n * @remarks\n * `middleware[0]` runs outermost: it is invoked first, and its call to `next`\n * runs `middleware[1]`, and so on until the last middleware's `next` invokes\n * `terminal`. Every layer and `terminal` receive the same `Request` and the same\n * context object. A middleware's `next` is called with no argument, or not\n * called at all (a short-circuit — the middleware's own returned `Response` is\n * sent, and everything downstream never runs). A second call to the same\n * `next` within one middleware invocation, or a call that passes an argument,\n * rejects with a `ServerError` of code `'NEXT'` — each link runs the chain at\n * most once, so a middleware cannot fork the request into two divergent\n * downstream runs. Each `next` resolves the downstream response through\n * {@link normalizeResponse}, so a layer can set headers on a redirect or a\n * `fetch` result; each run keeps its own memo of checked responses, which ends\n * with the run. `compose` copies `middleware` when called, so a layer added to\n * the array later never runs in the returned handler.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param middleware - The ordered chain, outermost first\n * @param terminal - The innermost handler the chain ultimately reaches\n * @returns A single `(request, context) => Promise<Response>` handler running the whole onion\n *\n * @example\n * ```ts\n * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Powered-By', 'orkestrel')\n * \treturn response\n * }\n *\n * const handle = compose([withHeader], async () => new Response('ok'))\n * ```\n */\nexport function compose<TState>(\n\tmiddleware: ReadonlyArray<MiddlewareHandler<TState>>,\n\tterminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\tconst layers = [...middleware]\n\treturn (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tconst known = new Map<Response, Response>()\n\t\treturn layers.reduceRight<\n\t\t\t(request: Request, context: MiddlewareContext<TState>) => Promise<Response>\n\t\t>((next, layer) => wrapMiddleware(layer, next, known), terminal)(request, context)\n\t}\n}\n\n/**\n * Wraps one middleware layer around its downstream handler, enforcing the one-call\n * `next` invariant.\n *\n * @remarks\n * The returned handler enforces the one-call, no-argument `next` invariant: every\n * call, refused or not, spends the layer's one call, so a call after a refused\n * `next(request)` rejects too. It hands `next` the same request and context, and\n * keeps the middleware's synchronous or asynchronous result.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param layer - The middleware layer to invoke\n * @param next - The downstream handler wrapped by `layer`\n * @param known - The {@link normalizeResponse} memo of one composed run, shared by its\n * layers; Default: a fresh `Map` per call of the returned handler\n * @returns A handler with `layer` composed around `next`\n *\n * @example\n * ```ts\n * const handle = wrapMiddleware(\n * \tasync (_request, _context, next) => next(),\n * \tasync () => new Response('ok'),\n * )\n * ```\n */\nexport function wrapMiddleware<TState>(\n\tlayer: MiddlewareHandler<TState>,\n\tnext: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n\tknown?: Map<Response, Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn async (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tconst memo = known ?? new Map<Response, Response>()\n\t\tconst calls = [next].values()\n\t\treturn Promise.resolve(\n\t\t\tlayer(request, context, (...args: readonly unknown[]): Promise<Response> => {\n\t\t\t\tconst invocation = calls.next()\n\t\t\t\tif (invocation.done)\n\t\t\t\t\treturn Promise.reject(\n\t\t\t\t\t\tnew ServerError('NEXT', 'next() was already called by this middleware'),\n\t\t\t\t\t)\n\t\t\t\tif (args.length > 0)\n\t\t\t\t\treturn Promise.reject(\n\t\t\t\t\t\tnew ServerError('NEXT', 'next() takes no argument; every layer reads one request'),\n\t\t\t\t\t)\n\t\t\t\treturn invocation\n\t\t\t\t\t.value(request, context)\n\t\t\t\t\t.then((response) => normalizeResponse(response, memo))\n\t\t\t}),\n\t\t)\n\t}\n}\n\n/**\n * Returns a response whose headers a middleware can set: a copy of `response` when its headers are\n * immutable and its status lies from 200 through 599, and `response` itself otherwise.\n *\n * @remarks\n * A `Response.redirect` result and a `fetch` result carry immutable headers, so `headers.set`\n * throws on them. The copy keeps the body, the status, the status text, and every header; it\n * drops the fields a constructed `Response` cannot carry, such as `url` and `redirected`. A\n * response whose status lies outside 200 through 599, such as `Response.error()`, passes through\n * unchanged. `known` maps each response already checked to its answer, and the copy to itself, so\n * a response that crosses several layers of one composed run is checked once.\n *\n * @param response - The response a downstream handler resolved\n * @param known - The memo of one composed run; Default: a fresh `Map`\n * @returns `response` itself, or its mutable copy\n *\n * @example\n * ```ts\n * const response = normalizeResponse(Response.redirect('http://localhost/next', 302))\n * response.headers.set('X-Request-ID', 'abc') // no throw\n * ```\n */\nexport function normalizeResponse(\n\tresponse: Response,\n\tknown: Map<Response, Response> = new Map(),\n): Response {\n\tconst remembered = known.get(response)\n\tif (remembered !== undefined) return remembered\n\tconst normal =\n\t\tresponse.status < 200 || response.status > 599 || supportsMutation(response.headers)\n\t\t\t? response\n\t\t\t: new Response(response.body, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\theaders: new Headers(response.headers),\n\t\t\t\t})\n\tknown.set(response, normal)\n\tif (normal !== response) known.set(normal, normal)\n\treturn normal\n}\n\n/**\n * Checks whether a `Headers` object accepts changes, leaving its entries as they were.\n *\n * @remarks\n * Fetch refuses `delete` on immutable headers before it looks the name up, so deleting a name\n * the headers lack answers the question and changes nothing. When the probe name is present, the\n * check sets it to its own combined value instead.\n *\n * @param headers - The headers to check\n * @returns True if `headers` accepts changes; false otherwise\n *\n * @example\n * ```ts\n * supportsMutation(new Headers()) // true\n * supportsMutation(Response.redirect('http://localhost/', 302).headers) // false\n * ```\n */\nexport function supportsMutation(headers: Headers): boolean {\n\tconst name = 'x-orkestrel-probe'\n\tconst value = headers.get(name)\n\treturn holds(() => {\n\t\tif (value === null) headers.delete(name)\n\t\telse headers.set(name, value)\n\t\treturn true\n\t})\n}\n\n// The cookie machinery (module-scope helpers) — `parseCookies`\n// decodes a raw `Cookie:` header into a name→value lookup; `serializeCookie`\n// builds a spec-shaped `Set-Cookie` value with its attributes. The signed\n// pair reuses the shipped HMAC token primitives rather than a second HMAC\n// scheme: `writeSignedCookie` is `serializeCookie(name, await signToken(value,\n// { signer }))` appended to a `Headers`, and `readSignedCookie` is `await\n// verifyToken(parseCookies(...)[name], signer)` — so a cookie is a\n// `signToken` value in a `Set-Cookie`, with the same key rotation and tamper\n// rejection. Every reader narrows untrusted request input with `typeof`,\n// never `as`, and remains total on malformed input.\n\n/**\n * Parses a raw `Cookie:` request header into a `name → value` lookup.\n *\n * @remarks\n * Splits on `;`; the first segment keeps any leading whitespace (a genuine\n * cookie-pair separator never precedes it), while every later segment has its\n * inter-pair separator (ASCII space/tab) stripped before parsing — so a\n * whitespace-padded name (`' __Host-x=evil'`) is rejected by\n * {@link isCookieName} rather than silently reconciling into a\n * prefix-protected `__Host-` name. A pair without `=`, or with an invalid\n * name, is skipped; a later duplicate name wins. Total — an absent/empty/\n * malformed header yields an empty record, never throws.\n *\n * The record has a null prototype, so a name that `Object.prototype` carries\n * (`constructor`, `toString`, `__proto__`) reads as an ordinary cookie when\n * present and as `undefined` when absent.\n *\n * @param header - The raw `Cookie` header value (possibly `undefined`)\n * @returns A null-prototype record of every parsed cookie, `name → decoded value`\n *\n * @example\n * ```ts\n * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }\n * ```\n */\nexport function parseCookies(header: string | undefined): Record<string, string> {\n\tconst pairs = (header ?? '')\n\t\t.split(';')\n\t\t.flatMap((raw, index): ReadonlyArray<readonly [string, string]> => {\n\t\t\tconst segment = index === 0 ? raw : raw.replace(/^[ \\t]+/, '')\n\t\t\tconst eq = segment.indexOf('=')\n\t\t\tif (eq < 0) return []\n\t\t\tconst name = segment.slice(0, eq)\n\t\t\treturn isCookieName(name) ? [[name, decodeCookieValue(segment.slice(eq + 1).trim())]] : []\n\t\t})\n\tconst cookies = Object.fromEntries(pairs)\n\tObject.setPrototypeOf(cookies, null)\n\treturn cookies\n}\n\n/**\n * Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of\n * cookie-token characters with no surrounding or interior whitespace.\n *\n * @remarks\n * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$` —\n * which excludes every whitespace char (ASCII and Unicode) plus controls,\n * separators, and `=`. The {@link parseCookies} hardening that stops a\n * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.\n *\n * @param value - The candidate cookie name\n * @returns True if `value` is a valid, whitespace-free cookie token; false otherwise\n *\n * @example\n * ```ts\n * isCookieName('__Host-session') // true\n * isCookieName(' __Host-session') // false — whitespace-padded\n * ```\n */\nexport function isCookieName(value: string): boolean {\n\treturn /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/.test(value)\n}\n\n/**\n * Decodes a cookie value with `decodeURIComponent`, falling back to the raw\n * text when the value is not valid percent-encoding.\n *\n * @param raw - The raw (trimmed) cookie value\n * @returns The URL-decoded value, or the raw value when decoding would throw\n *\n * @example\n * ```ts\n * decodeCookieValue('a%20b') // 'a b'\n * decodeCookieValue('%') // '%' — malformed escape stays literal\n * ```\n */\nexport function decodeCookieValue(raw: string): string {\n\ttry {\n\t\treturn decodeURIComponent(raw)\n\t} catch {\n\t\treturn raw\n\t}\n}\n\n/**\n * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —\n * the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it\n * emits them.\n *\n * @remarks\n * Rejects a value carrying a `;` (splits attributes), a `,` (can split a\n * folded header), ASCII/Unicode whitespace, or a C0/DEL control char\n * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`\n * directive. Total — never throws (a bad value returns `false`).\n *\n * @param value - The candidate attribute value (a `Domain` or `Path`)\n * @returns True if `value` carries no separator / whitespace / control char; false otherwise\n *\n * @example\n * ```ts\n * isCookieAttribute('/app') // true\n * isCookieAttribute('/a\\r\\nSet-Cookie: x=y') // false\n * ```\n */\nexport function isCookieAttribute(value: string): boolean {\n\tfor (const char of value) {\n\t\tif (char === ';' || char === ',' || /\\s/.test(char)) return false\n\t\tconst code = char.codePointAt(0)\n\t\tif (code !== undefined && (code < 0x20 || code === 0x7f)) return false\n\t}\n\treturn true\n}\n\n/**\n * Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.\n *\n * @remarks\n * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and\n * appends the present {@link CookieOptions} attributes in canonical order:\n * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`\n * (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated\n * with {@link isCookieAttribute} and throw an {@link HTTPError} on an\n * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of\n * the `secure` option (the spec requires it); an un-resolved `undefined`\n * `secure` here falls to off — request-aware callers resolve it first through\n * {@link resolveSecure}.\n *\n * @param name - The cookie name\n * @param value - The cookie value (URL-encoded into the output)\n * @param options - The {@link CookieOptions} attributes; see its fields for defaults\n * @returns The `Set-Cookie` header value\n * @throws {HTTPError} When `domain` or `path` carries an injection char\n *\n * @example\n * ```ts\n * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'\n * ```\n */\nexport function serializeCookie(name: string, value: string, options?: CookieOptions): string {\n\tconst sameSite = options?.sameSite ?? 'Lax'\n\tconst domain = options?.domain\n\tif (domain !== undefined && !isCookieAttribute(domain))\n\t\tthrow new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`)\n\tconst path = options?.path ?? '/'\n\tif (!isCookieAttribute(path))\n\t\tthrow new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`)\n\tconst secure = sameSite === 'None' || options?.secure === true\n\tconst parts = [`${name}=${encodeURIComponent(value)}`]\n\tif (domain !== undefined) parts.push(`Domain=${domain}`)\n\tparts.push(`Path=${path}`)\n\tif (options?.maxAge !== undefined) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`)\n\tif (options?.httpOnly !== false) parts.push('HttpOnly')\n\tif (secure) parts.push('Secure')\n\tparts.push(`SameSite=${sameSite}`)\n\treturn parts.join('; ')\n}\n\n/**\n * Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}\n * `secure` setting and whether the request arrived over TLS.\n *\n * @remarks\n * `true` / `false` are explicit overrides. `undefined` (the secure default —\n * the option omitted) resolves to `encrypted` — `Secure` on a TLS\n * connection, off over plaintext HTTP — so a production HTTPS deployment\n * gets `Secure` automatically while local-dev HTTP still works.\n *\n * @param secure - The {@link CookieOptions} `secure` setting\n * @param encrypted - The connection's TLS flag\n * ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted\n * `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to\n * no `Secure` attribute.\n * @returns The concrete `Secure` flag to emit\n *\n * @example\n * ```ts\n * resolveSecure(undefined, true) // true\n * resolveSecure(undefined, false) // false\n * resolveSecure(false, true) // false — explicit override wins\n * ```\n */\nexport function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean {\n\tif (secure === true || secure === false) return secure\n\treturn encrypted\n}\n\n/**\n * Writes a signed cookie — HMAC-signs `value` with {@link signToken} and\n * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).\n *\n * @remarks\n * The cookie value is `await signToken(value, { signer })`\n * (`<payload>.<signature>`), so a signed cookie is a stateless token in a\n * cookie — the same key rotation and tamper rejection, no second HMAC\n * scheme. Appends (never clobbers) through `Headers.append`, which accumulates\n * repeated headers.\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name\n * @param value - The opaque value to sign into the cookie\n * @param signer - The {@link SignerInterface} that signs (its first key signs)\n * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * await writeSignedCookie(headers, 'session', 'user-1', createSigner('secret'))\n * ```\n */\nexport async function writeSignedCookie(\n\theaders: Headers,\n\tname: string,\n\tvalue: string,\n\tsigner: SignerInterface,\n\toptions?: CookieOptions,\n): Promise<void> {\n\theaders.append('set-cookie', serializeCookie(name, await signToken(value, { signer }), options))\n}\n\n/**\n * Reads and verifies a signed cookie off a request, returning the embedded value\n * or `undefined` (the inverse of {@link writeSignedCookie}).\n *\n * @remarks\n * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,\n * and verifies it with {@link verifyToken} against `signer` (a signer over a\n * rotation list accepts a cookie signed by any of its keys). An absent cookie,\n * a tampered value, and a wrong key each yield `undefined`, a name such as\n * `constructor` included. It rejects only when `signer.verify` rejects, which\n * the signer `createSigner` returns never does.\n *\n * @param request - The `Request` to read the `Cookie` header from\n * @param name - The cookie name to read\n * @param signer - The {@link SignerInterface} to verify against\n * @returns The embedded value when the cookie is present + valid, else `undefined`\n *\n * @example\n * ```ts\n * const value = await readSignedCookie(request, 'session', createSigner('secret'))\n * ```\n */\nexport async function readSignedCookie(\n\trequest: Request,\n\tname: string,\n\tsigner: SignerInterface,\n): Promise<string | undefined> {\n\tconst cookie = parseCookies(request.headers.get('cookie') ?? undefined)[name]\n\treturn cookie === undefined ? undefined : verifyToken(cookie, signer)\n}\n\n/**\n * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).\n *\n * @remarks\n * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the\n * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops\n * a cookie when those match the one it set).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name to clear\n * @param options - The {@link CookieOptions} that must match the original cookie\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * clearCookie(headers, 'session')\n * ```\n */\nexport function clearCookie(headers: Headers, name: string, options?: CookieOptions): void {\n\theaders.append('set-cookie', serializeCookie(name, '', { ...options, maxAge: 0 }))\n}\n\n// The stateless signed-token primitives (module-scope helpers). A token is\n// `<payload>.<signature>`: the payload a base64url JSON `{ value, exp? }`, the\n// signature the signer's HMAC-SHA256 of the payload.\n\n/**\n * Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.\n *\n * @remarks\n * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the\n * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so\n * the expiry is HMAC-COVERED — a client cannot extend it without invalidating\n * the signature), signed by `options.signer`, whose first key signs. Verify\n * with {@link verifyToken}. Omitting `ttl` mints a token that never expires.\n *\n * @param value - The opaque value to embed (a session id, a deployment marker)\n * @param options - The `signer` and optional `ttl` (ms); see {@link TokenOptions}\n * @returns The signed `<payload>.<signature>` token string\n *\n * @example\n * ```ts\n * const signer = createSigner('shh')\n * const token = await signToken('client', { signer, ttl: 60_000 })\n * await verifyToken(token, signer) // 'client' (within 60s), else undefined\n * ```\n */\nexport async function signToken(value: string, options: TokenOptions): Promise<string> {\n\tconst exp = options.ttl !== undefined ? Date.now() + options.ttl : undefined\n\tconst encoded = encodeBase64URL(new TextEncoder().encode(JSON.stringify({ value, exp })))\n\treturn `${encoded}.${await options.signer.sign(encoded)}`\n}\n\n/**\n * Verifies a stateless token and returns its embedded value, or `undefined` for a\n * malformed, tampered, or expired token.\n *\n * @remarks\n * The inverse of {@link signToken}: splits the token on its last `.` (so a\n * value containing dots survives), checks the signature with `signer.verify`\n * (a signer over a rotation list accepts any of its keys), then decodes and\n * narrows the payload with {@link decodeTokenPayload}, which refuses an\n * elapsed expiry. It rejects only when `signer.verify` rejects, which the\n * signer `createSigner` returns never does, so a consumer signer's outage\n * surfaces as an error rather than as an invalid token.\n *\n * @param token - The candidate token string (from a request header/cookie)\n * @param signer - The {@link SignerInterface} to verify against\n * @returns The embedded value when the token is valid + unexpired, else `undefined`\n *\n * @example\n * ```ts\n * await verifyToken('bad.token', createSigner('shh')) // undefined\n * ```\n */\nexport async function verifyToken(\n\ttoken: string,\n\tsigner: SignerInterface,\n): Promise<string | undefined> {\n\tconst dot = token.lastIndexOf('.')\n\tif (dot < 0) return undefined\n\tconst encoded = token.slice(0, dot)\n\treturn (await signer.verify(encoded, token.slice(dot + 1)))\n\t\t? decodeTokenPayload(encoded)\n\t\t: undefined\n}\n\n/**\n * Decodes and narrows a signed token's base64url JSON payload, honoring its\n * expiry — the shared decode step {@link verifyToken} applies after a\n * signature match.\n *\n * @remarks\n * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a\n * non-canonical base64url segment answers `undefined` rather than throwing),\n * reads it as UTF-8 JSON, narrows it to a record with a string `value` without\n * `as`, and rejects an expired `exp`. Total — any decode/shape/expiry failure\n * yields `undefined`, including invalid JSON (`parseJSON` answers `undefined`).\n *\n * @param encoded - The base64url-encoded payload segment (before the last `.`)\n * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`\n */\nexport function decodeTokenPayload(encoded: string): string | undefined {\n\tconst bytes = decodeBase64URL(encoded)\n\tif (bytes === undefined) return undefined\n\tconst payload = parseJSON(new TextDecoder().decode(bytes))\n\tif (!isRecord(payload)) return undefined\n\tif (!isString(payload.value)) return undefined\n\tif (payload.exp !== undefined && !isNumber(payload.exp)) return undefined\n\tif (payload.exp !== undefined && Date.now() >= payload.exp) return undefined\n\treturn payload.value\n}\n\n/**\n * Normalizes a {@link TokenSecret} to its `[current, ...older]` list — the list a\n * signer creates its keys from — refusing a malformed secret.\n *\n * @remarks\n * A single string becomes a one-element list; a rotation list is copied once\n * and its copy validated, each secret kept verbatim. A blank entry is refused,\n * never dropped, because dropping a blank current secret would make an older\n * key sign. The refusal names the blank or non-string positions in `context`\n * and carries no secret text.\n *\n * @param secret - The {@link TokenSecret} (a single string, or a rotation list)\n * @returns The secrets, current first\n * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of\n * strings, when the list is empty, or when any entry is blank\n *\n * @example\n * ```ts\n * normalizeSecret(['new', 'old']) // ['new', 'old']\n * normalizeSecret(['new', ' ']) // throws ServerError 'SECRET', context { entries: [1], count: 2 }\n * ```\n */\nexport function normalizeSecret(secret: TokenSecret): readonly [string, ...string[]] {\n\tconst copied = attempt((): readonly unknown[] | undefined =>\n\t\tisString(secret) ? [secret] : isArray(secret) ? Array.from(secret) : undefined,\n\t)\n\tconst entries = copied.success ? copied.value : undefined\n\tif (entries === undefined)\n\t\tthrow new ServerError(\n\t\t\t'SECRET',\n\t\t\t'the signing secret is not a string or a list of strings: pass a non-blank string or a non-empty list of non-blank strings',\n\t\t\t{ received: typeof secret },\n\t\t)\n\tconst blank = entries.flatMap((entry, index) =>\n\t\tisString(entry) && entry.trim().length > 0 ? [] : [index],\n\t)\n\tconst [current, ...older] = entries\n\tif (!isString(current) || blank.length > 0 || !older.every(isString))\n\t\tthrow new ServerError(\n\t\t\t'SECRET',\n\t\t\tentries.length === 0\n\t\t\t\t? 'the signing secret is an empty list: pass a non-blank string or a non-empty list of non-blank strings'\n\t\t\t\t: `the signing secret has blank or non-string entries at ${blank.join(', ')}: pass a non-blank string or a non-empty list of non-blank strings`,\n\t\t\t{ entries: blank, count: entries.length },\n\t\t)\n\treturn [current, ...older]\n}\n\n// The content-negotiation helpers (module-scope) — the one shared q-value\n// parser behind the `Negotiator` and any compression middleware's\n// `Accept-Encoding` pick.\n\n/**\n * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header\n * into its q-sorted entries.\n *\n * @remarks\n * Splits on `,`; for each part takes the token before the first `;`\n * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the\n * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls\n * back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must\n * honor). The result is sorted by `q` descending, a stable sort preserving\n * the header's own order within a tie — a single pass with no backtracking,\n * so parsing stays linear in the header length (ReDoS-safe). Total — an\n * empty/malformed header yields `[]`/best-effort entries, never throws.\n *\n * @param header - The raw weighted header value\n * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending\n *\n * @example\n * ```ts\n * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')\n * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]\n * ```\n */\nexport function parseAcceptHeader(header: string): readonly AcceptEntry[] {\n\tconst entries: AcceptEntry[] = []\n\tfor (const part of header.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.length === 0) continue\n\t\tconst semicolon = trimmed.indexOf(';')\n\t\tconst value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase()\n\t\tif (value.length === 0) continue\n\t\tconst match = semicolon === -1 ? null : /;\\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon))\n\t\tconst parsed = match === null ? undefined : Number(match[1])\n\t\tconst q = isFiniteNumber(parsed) ? Math.min(1, Math.max(0, parsed)) : 1\n\t\tentries.push({ value, q })\n\t}\n\treturn entries\n\t\t.map((entry, index) => ({ entry, index }))\n\t\t.sort((a, b) => b.entry.q - a.entry.q || a.index - b.index)\n\t\t.map((ranked) => ranked.entry)\n}\n\n/**\n * Computes the client's quality (q) for one content-coding from the parsed\n * `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over\n * each offered coding.\n *\n * @remarks\n * Prefers an exact named match (including an explicit `;q=0` rejection);\n * failing that, a bare `*` wildcard's q applies. A coding that is neither\n * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins\n * over a `*` (a specific rejection beats the wildcard), so it scores `0`.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param coding - The candidate coding to score\n * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5\n * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1\n * ```\n */\nexport function computeCodingQuality(entries: readonly AcceptEntry[], coding: string): number {\n\tconst named = entries.find((entry) => entry.value === coding)\n\tif (named !== undefined) return named.q\n\tconst wildcard = entries.find((entry) => entry.value === '*')\n\treturn wildcard?.q ?? 0\n}\n\n/**\n * Picks the highest-scoring content-coding the server offers against already\n * parsed `Accept-Encoding` entries — the shared selection leaf behind\n * {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.\n *\n * @remarks\n * The single selection leaf behind both doors onto this axis —\n * {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the\n * entity — so the scoring loop has one implementation. Scores each `available`\n * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`\n * keeps the earlier-offered coding on a client-side tie, which is what makes\n * `available` the server's preference order. An empty `available` list, and a\n * list the client rejects outright, both yield `undefined` (identity — no\n * compression). Total on malformed input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param entries - The parsed {@link AcceptEntry} list\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The winning coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'\n * resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined\n * ```\n */\nexport function resolveCoding<T extends string>(\n\tentries: readonly AcceptEntry[],\n\tavailable: readonly T[],\n): T | undefined {\n\tconst best = Iterator.from(available).reduce<\n\t\t{ readonly value: T; readonly quality: number } | undefined\n\t>((previous, coding) => {\n\t\tconst quality = computeCodingQuality(entries, coding)\n\t\treturn quality > (previous?.quality ?? 0) ? { value: coding, quality } : previous\n\t}, undefined)\n\treturn best?.value\n}\n\n/**\n * Selects the best content-coding for a raw `Accept-Encoding` header from the\n * codings the server offers.\n *\n * @remarks\n * Parses the header ({@link parseAcceptHeader}) and hands the entries to\n * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so\n * the two doors onto this axis cannot drift. Returns `undefined` when the\n * client accepts none of `available` (identity — no compression). Total on\n * malformed input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param header - The raw `Accept-Encoding` header value\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The negotiated coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * ```\n */\nexport function negotiateEncoding<T extends string>(\n\theader: string,\n\tavailable: readonly T[],\n): T | undefined {\n\tif (available.length === 0) return undefined\n\treturn resolveCoding(parseAcceptHeader(header), available)\n}\n\n/**\n * Reports the rank and quality of one `candidate` media type against the parsed `Accept`\n * entries — the generic media-type primitive the `Negotiator`'s `negotiate`\n * uses to score each `available` candidate.\n *\n * @remarks\n * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the\n * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact\n * `;q=0` entry explicitly rejects the candidate outright (returns\n * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own\n * (less specific) coverage, so a later more-specific match can still allow\n * it. Among multiple matching entries, the lowest `rank` wins, and among a\n * rank tie the highest `q` wins. The candidate matches case-insensitively, as\n * the entries do.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate media type to score (for example `'text/html'`)\n * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches\n *\n * @example\n * ```ts\n * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')\n * // { q: 1, rank: 0 }\n * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }\n * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined\n * ```\n */\nexport function matchMediaType(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): MediaMatch | undefined {\n\tconst matches = iterateMediaMatches(entries, candidate)\n\treturn matches.reduce<MediaMatch | undefined>((best, match) => {\n\t\tif (match.q === 0) return undefined\n\t\tconst preferred =\n\t\t\tbest === undefined || match.rank < best.rank || (match.rank === best.rank && match.q > best.q)\n\t\treturn preferred ? match : best\n\t}, undefined)\n}\n\n/**\n * Yields matching media ranges through the first exact rejection.\n *\n * @example\n * ```ts\n * Array.from(iterateMediaMatches([{ value: 'text/plain', q: 1 }], 'text/plain'))\n * // [{ q: 1, rank: 0 }]\n * ```\n */\nexport function* iterateMediaMatches(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): Generator<MediaMatch, void, unknown> {\n\t// `parseAcceptHeader` lower-cases each entry, and a media type matches case-insensitively.\n\tconst media = candidate.toLowerCase()\n\tconst slash = media.indexOf('/')\n\tconst type = slash === -1 ? media : media.slice(0, slash)\n\tfor (const entry of entries) {\n\t\tconst rank =\n\t\t\tentry.value === media\n\t\t\t\t? 0\n\t\t\t\t: entry.value === `${type}/*`\n\t\t\t\t\t? 1\n\t\t\t\t\t: entry.value === '*/*'\n\t\t\t\t\t\t? 2\n\t\t\t\t\t\t: undefined\n\t\tif (rank === undefined) continue\n\t\tif (entry.q === 0) {\n\t\t\t// An exact `;q=0` explicitly rejects this candidate outright; a\n\t\t\t// wildcard `;q=0` only rejects the wildcard's own (less specific)\n\t\t\t// coverage, so a later more-specific match can still allow it.\n\t\t\tif (rank === 0) {\n\t\t\t\tyield { q: 0, rank }\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tyield { q: entry.q, rank }\n\t}\n}\n\n/**\n * Yields the same lazily collected request-body promise on every read.\n *\n * @example\n * ```ts\n * const bodies = iterateRequestBody(new Request('http://localhost/'), 1024)\n * bodies.next().value === bodies.next().value // true\n * ```\n */\nexport function* iterateRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Generator<Promise<unknown>, never, unknown> {\n\tconst body = readBody(request, { limit })\n\tfor (;;) yield body\n}\n\n/**\n * Computes the client's quality for one `candidate` language from the parsed\n * `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`\n * axis runs over each offered tag.\n *\n * @remarks\n * Prefers an exact match, then a primary-tag prefix match (`en` accepts\n * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry\n * is an explicit rejection).\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate language tag to score (for example `'en-US'`)\n * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1\n * computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix\n * computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard\n * ```\n */\nexport function computeLanguageQuality(entries: readonly AcceptEntry[], candidate: string): number {\n\tconst lower = candidate.toLowerCase()\n\tconst primary = lower.split('-')[0]\n\tconst qualities = Iterator.from(entries).reduce<{\n\t\treadonly named?: number\n\t\treadonly prefixed?: number\n\t\treadonly wildcard?: number\n\t}>((previous, entry) => {\n\t\tconst entryPrimary = entry.value.split('-')[0]\n\t\tif (entry.value === lower) return { ...previous, named: entry.q }\n\t\tif (entryPrimary === primary) {\n\t\t\treturn previous.prefixed === undefined ? { ...previous, prefixed: entry.q } : previous\n\t\t}\n\t\treturn entry.value === '*' ? { ...previous, wildcard: entry.q } : previous\n\t}, {})\n\treturn qualities.named ?? qualities.prefixed ?? qualities.wildcard ?? 0\n}\n\n/**\n * Checks whether a `Content-Type` is worth compressing.\n *\n * @remarks\n * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`\n * type, a `+json`/`+xml` structured suffix, or one of the explicit\n * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed\n * binary (`image/png`, `application/zip`) is not compressible. An\n * absent/empty type is not compressible. Total.\n *\n * @param type - The response `Content-Type` header value (with or without parameters)\n * @returns True if the type is text-shaped and worth compressing; false otherwise\n *\n * @example\n * ```ts\n * isCompressibleType('application/json; charset=utf-8') // true\n * isCompressibleType('image/png') // false\n * ```\n */\nexport function isCompressibleType(type: string): boolean {\n\tconst semicolon = type.indexOf(';')\n\tconst bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase()\n\tif (bare.length === 0) return false\n\tif (bare.startsWith('text/')) return true\n\tif (bare.endsWith('+json') || bare.endsWith('+xml')) return true\n\treturn COMPRESSIBLE_TYPES.has(bare)\n}\n\n// The conditional-request helpers (module-scope) — ETag\n// compute/compare (RFC 7232 §2.3.2 weak comparison) and the total `Range`\n// parser.\n\n/**\n * Computes a content `ETag` over a fully-buffered response body by using WebCrypto.\n *\n * @remarks\n * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex\n * digest as a weak validator (`W/\"<hash>\"`) when `weak` is `true` — the\n * default, encoding-agnostic, so the tag survives a downstream content\n * re-encoding (gzip) and still matches on revalidation — or a strong one\n * (`\"<hash>\"`, byte-identity) when `weak` is `false`.\n *\n * @param body - The full (uncompressed) response body to hash\n * @param weak - If `true` (the default), returns a weak `W/\"…\"` validator; if\n * `false`, returns a strong `\"…\"` one.\n * @returns The `ETag` header value\n *\n * @example\n * ```ts\n * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/\"…sha256-hex…\"'\n * ```\n */\nexport async function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak = true): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', body)\n\tconst hex = encodeHex(new Uint8Array(digest))\n\treturn weak ? `W/\"${hex}\"` : `\"${hex}\"`\n}\n\n/**\n * Strips the weak indicator (`W/`) from an entity-tag, returning its opaque\n * comparison body — the reduction {@link matchesETag} applies to each side\n * before the RFC 7232 §2.3.2 weak comparison.\n *\n * @param tag - One entity-tag (`W/\"<body>\"` or `\"<body>\"`)\n * @returns The tag with any leading `W/` removed (the quotes preserved)\n *\n * @example\n * ```ts\n * unwrapETag('W/\"abc\"') // '\"abc\"'\n * ```\n */\nexport function unwrapETag(tag: string): string {\n\tconst trimmed = tag.trim()\n\treturn trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed\n}\n\n/**\n * Checks whether a request's `If-None-Match` header matches a resource's current\n * `ETag` — the RFC 7232 §2.3.2 weak comparison.\n *\n * @remarks\n * `If-None-Match` is a comma-separated list of entity-tags (matches if any\n * listed tag matches), or the `*` wildcard (matches any current\n * representation — only a list of exactly `*` is the wildcard). Comparison is\n * weak: `W/\"abc\"` and `\"abc\"` are equal (each side's weak prefix is stripped\n * through {@link unwrapETag} before comparing the opaque body). Total — a\n * malformed/empty header matches nothing, never throws.\n *\n * @param header - The raw `If-None-Match` header value\n * @param etag - The resource's current `ETag`\n * @returns True if the conditional matches (the caller answers `304`); false otherwise\n *\n * @example\n * ```ts\n * matchesETag('\"abc\", W/\"def\"', 'W/\"abc\"') // true — weak comparison\n * matchesETag('*', 'W/\"anything\"') // true — wildcard\n * ```\n */\nexport function matchesETag(header: string, etag: string): boolean {\n\tconst trimmed = header.trim()\n\tif (trimmed === '*') return true\n\tconst target = unwrapETag(etag)\n\tfor (const member of trimmed.split(',')) {\n\t\tconst candidate = member.trim()\n\t\tif (candidate.length === 0) continue\n\t\tif (unwrapETag(candidate) === target) return true\n\t}\n\treturn false\n}\n\n/**\n * Parses an HTTP `Range` request header against a known resource `size` —\n * total, returning a {@link RangeSpec} or `undefined`.\n *\n * @remarks\n * Reads the field value by RFC 9110 § 14.1:\n * `range-unit \"=\" OWS range-set`, where the unit matches `bytes`\n * case-insensitively and `range-set` is `1#range-spec` under the § 5.6.1 list\n * rule, so empty list elements are skipped. OWS is a space or a tab, and it\n * stands only around the field value, after `=`, and around a `,`; a range\n * holds none. A range is an `int-range` (`first-pos \"-\" [ last-pos ]`) or a\n * `suffix-range` (`\"-\" suffix-length`), each bound `1*DIGIT` ({@link\n * import('./constants.js').RANGE_BOUND_PATTERN}). A bound of any length is\n * compared with {@link compareDigits}, so none is misread through `Number`.\n * OWS is stripped with {@link stripOWS}, so the read is linear in the header's\n * length.\n *\n * Returns `{ satisfiable: true, start, end }` with the window clamped to\n * `[0, size - 1]` (the HTTP inclusive-end convention), and\n * `{ satisfiable: false }` when the range does not overlap the resource: a\n * `first-pos` at or past `size`, or a zero `suffix-length`.\n * Returns `undefined`, the § 14.2 \"ignore the field and serve the whole\n * resource\" answer, for an absent header, another unit, text outside the\n * grammar, a `last-pos` below its `first-pos`, more than one range (not\n * supported), a non-zero `suffix-length` on an empty resource (satisfiable by\n * § 14.1.2, but it selects no window to serve), and a `size` that is not a\n * non-negative safe integer. Never throws on a malformed header.\n *\n * @param header - The raw `Range` header value\n * @param size - The resource's total byte length\n * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource\n *\n * @example\n * ```ts\n * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }\n * parseRange('Bytes=-100,', 1000) // { satisfiable: true, start: 900, end: 999 }\n * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused\n * parseRange('bytes=0x10-', 1000) // undefined — not a decimal bound\n * parseRange('bytes=5 - 9', 1000) // undefined — no OWS inside a range\n * ```\n */\nexport function parseRange(header: string | undefined, size: number): RangeSpec | undefined {\n\tif (header === undefined || !isSafeInteger(size) || size < 0) return undefined\n\tconst field = stripOWS(header)\n\tconst equals = field.indexOf('=')\n\tif (equals < 0 || field.slice(0, equals).toLowerCase() !== 'bytes') return undefined\n\tconst specs = field\n\t\t.slice(equals + 1)\n\t\t.split(',')\n\t\t.map((item) => stripOWS(item))\n\t\t.filter((spec) => spec !== '')\n\tconst spec = specs[0]\n\tif (spec === undefined || specs.length > 1) return undefined\n\tconst dash = spec.indexOf('-')\n\tif (dash < 0) return undefined\n\tconst first = spec.slice(0, dash)\n\tconst last = spec.slice(dash + 1)\n\tconst extent = String(size)\n\tif (first === '') {\n\t\tif (!RANGE_BOUND_PATTERN.test(last)) return undefined\n\t\tif (compareDigits(last, '0') === 0) return { satisfiable: false }\n\t\tif (size === 0) return undefined\n\t\tconst start = compareDigits(last, extent) < 0 ? size - Number(last) : 0\n\t\treturn { satisfiable: true, start, end: size - 1 }\n\t}\n\tif (!RANGE_BOUND_PATTERN.test(first)) return undefined\n\tif (last !== '' && !RANGE_BOUND_PATTERN.test(last)) return undefined\n\tif (last !== '' && compareDigits(last, first) < 0) return undefined\n\tif (compareDigits(first, extent) >= 0) return { satisfiable: false }\n\tconst end = last === '' || compareDigits(last, extent) >= 0 ? size - 1 : Number(last)\n\treturn { satisfiable: true, start: Number(first), end }\n}\n\n/**\n * Strips the OWS of RFC 9110 § 5.6.3 — spaces and tabs, and no other\n * character — from both ends of a text, in time linear in its length.\n *\n * @remarks\n * Reads the leading run with one anchored match and the trailing run with one\n * scan from the end, so a long run of spaces followed by another character\n * costs one pass, where a search for a trailing run restarts at every space.\n * A Unicode space such as U+00A0 stays, unlike `trim`.\n *\n * @param text - The text to strip\n * @returns `text` without its leading and trailing spaces and tabs\n *\n * @example\n * ```ts\n * stripOWS(' \\tbytes=0-1 ') // 'bytes=0-1'\n * ```\n */\nexport function stripOWS(text: string): string {\n\tconst start = /^[ \\t]*/.exec(text)?.[0].length ?? 0\n\tconst end = text.split('').findLastIndex((char) => char !== ' ' && char !== '\\t') + 1\n\treturn end <= start ? '' : text.slice(start, end)\n}\n\n/**\n * Compares two `1*DIGIT` strings by their decimal value, at any length.\n *\n * @remarks\n * Drops leading zeros, then compares the digit counts and, at an equal count,\n * the digits in order, so a bound longer than any safe integer compares\n * exactly and never passes through `Number`. Both arguments must be\n * `1*DIGIT`; the answer for any other text is unspecified.\n *\n * @param left - The first digit string\n * @param right - The second digit string\n * @returns `-1` if `left` is less, `1` if it is greater, `0` if the two are equal\n *\n * @example\n * ```ts\n * compareDigits('9', '10') // -1\n * compareDigits('007', '7') // 0\n * ```\n */\nexport function compareDigits(left: string, right: string): number {\n\tconst a = left.replace(/^0+/, '')\n\tconst b = right.replace(/^0+/, '')\n\tif (a.length !== b.length) return a.length < b.length ? -1 : 1\n\treturn a < b ? -1 : a > b ? 1 : 0\n}\n\n// The security primitives (module-scope) — CORS origin\n// resolution, `Vary` merging, security-header resolution, request-id\n// validation, and the IPv6 `/64` rate-key collapse.\n\n/**\n * Resolves the `Access-Control-Allow-Origin` value for a request.\n *\n * @remarks\n * `'*'` and a single origin string pass straight through. An allow-list\n * echoes the request's `Origin` only when it is present in the list, else\n * `undefined` (no header set). Security: the literal `'null'` origin — sent\n * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is\n * never reflected even if `'null'` were listed, closing the opaque-origin\n * cross-origin-access hole.\n *\n * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list\n * @param requestOrigin - The request's `Origin` header value, if present\n * @returns The allow-origin value to send, or `undefined` to set no header\n *\n * @example\n * ```ts\n * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'\n * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected\n * ```\n */\nexport function resolveOrigin(\n\torigin: string | readonly string[],\n\trequestOrigin: string | undefined,\n): string | undefined {\n\tif (isString(origin)) return origin\n\tif (!isString(requestOrigin)) return undefined\n\tif (requestOrigin === 'null') return undefined\n\treturn origin.includes(requestOrigin) ? requestOrigin : undefined\n}\n\n/**\n * Merges a `Vary` value into an existing `Vary` header without duplication.\n *\n * @remarks\n * Splits `existing` on `,`, trims each member, and appends `value` only when\n * no existing member already matches it case-insensitively (`Vary` header\n * names are case-insensitive). Preserves the existing members' order and\n * appends the new one last.\n *\n * @param existing - The current `Vary` header value, if any\n * @param value - The header name to ensure is listed\n * @returns The merged `Vary` value\n *\n * @example\n * ```ts\n * mergeVary(undefined, 'Origin') // 'Origin'\n * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)\n * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'\n * ```\n */\nexport function mergeVary(existing: string | undefined, value: string): string {\n\tconst members =\n\t\texisting === undefined\n\t\t\t? []\n\t\t\t: existing\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((member) => member.trim())\n\t\t\t\t\t.filter((member) => member.length > 0)\n\tconst present = members.some((member) => member.toLowerCase() === value.toLowerCase())\n\treturn present ? members.join(', ') : [...members, value].join(', ')\n}\n\n/**\n * Resolves one opt-out, value-bearing security header.\n *\n * @remarks\n * The shared \"a `string` value, or `false` to omit, or a default when unset\"\n * resolution (a value-or-off union, not a behavioral toggle):\n * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that\n * override, `undefined` (unset) ⇒ `fallback` (the secure default).\n *\n * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default\n * @param fallback - The secure-default value used when `value` is unset\n * @returns The header value to set, or `undefined` to omit the header\n *\n * @example\n * ```ts\n * resolveSecurityHeader(undefined, 'DENY') // 'DENY'\n * resolveSecurityHeader(false, 'DENY') // undefined — omitted\n * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override\n * ```\n */\nexport function resolveSecurityHeader(\n\tvalue: string | false | undefined,\n\tfallback: string,\n): string | undefined {\n\tif (value === false) return undefined\n\treturn value ?? fallback\n}\n\n/**\n * Checks whether a client-supplied `X-Request-ID` is safe to echo into a response\n * header and `context.state`.\n *\n * @remarks\n * A request id is echoed raw into a response header and log lines, so an\n * untrusted one is a header-injection + log-injection + DoS vector. This\n * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}\n * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).\n * Total — never throws.\n *\n * @param value - The candidate incoming request id\n * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise\n *\n * @example\n * ```ts\n * isValidRequestId('req_abc-123') // true\n * isValidRequestId('bad\\r\\nheader') // false\n * ```\n */\nexport function isValidRequestId(value: string): boolean {\n\treturn REQUEST_ID_PATTERN.test(value)\n}\n\n/**\n * Computes the `/64` network of a full IPv6 address, or `undefined` when the\n * input is not a plain IPv6 address to collapse.\n *\n * @remarks\n * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4\n * is the identity) or any string that does not expand to exactly eight\n * hextets. Expands a single `::` into the missing zero hextets, takes the\n * first four (the `/64` prefix), normalizes each (lower-case, no leading\n * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped\n * first. Total — a malformed address returns `undefined`.\n *\n * @param address - The candidate IPv6 address\n * @returns The `/64` network string, or `undefined` when not a plain IPv6 address\n *\n * @example\n * ```ts\n * computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'\n * computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed\n * ```\n */\nexport function computeIPv6Network(address: string): string | undefined {\n\tif (/^::ffff:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i.test(address)) return undefined\n\tconst percent = address.indexOf('%')\n\tconst bare = percent === -1 ? address : address.slice(0, percent)\n\tconst halves = bare.split('::')\n\tif (halves.length > 2) return undefined\n\tconst first = halves[0]\n\tif (first === undefined) return undefined\n\tconst second = halves[1]\n\tif (halves.length === 2 && second === undefined) return undefined\n\tconst head = first === '' ? [] : first.split(':')\n\tconst tail = second === undefined || second === '' ? [] : second.split(':')\n\tconst missing = 8 - head.length - tail.length\n\tif (halves.length === 2 && missing < 0) return undefined\n\tconst groups =\n\t\thalves.length === 2 ? [...head, ...Array.from({ length: missing }, () => '0'), ...tail] : head\n\tif (groups.length !== 8) return undefined\n\tconst prefix: string[] = []\n\tfor (const group of groups.slice(0, 4)) {\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return undefined\n\t\tprefix.push(Number.parseInt(group, 16).toString(16))\n\t}\n\treturn `${prefix.join(':')}::/64`\n}\n\n/**\n * Collapses a client IP into its rate-limit bucket key — an IPv6 address to\n * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.\n *\n * @remarks\n * A residential/mobile IPv6 user is routinely handed a whole `/64`, so a\n * per-`/128` rate limit is trivially bypassed by rotating host bits — the\n * real identity is the `/64` network. Delegates the IPv6 collapse to\n * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,\n * a malformed string) is kept unchanged.\n *\n * @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})\n * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged\n *\n * @example\n * ```ts\n * computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'\n * computeClientKey('192.0.2.1') // '192.0.2.1'\n * ```\n */\nexport function computeClientKey(address: string): string {\n\treturn computeIPv6Network(address) ?? address\n}\n\n// The Server-Sent-Events seam (module-scope) — `serializeEvent` and\n// `serializeComment` are the wire encoders. A conforming SSE parser reads an\n// event back with each line break in its data as `\\n`, and exposes no\n// comment, so a comment dispatches nothing. The stream handle\n// that writes those events over a `ReadableStream` is the `Stream` entity,\n// reached through `createStream`.\n\n/**\n * Serializes one {@link SSEMessage} to the SSE wire.\n *\n * @remarks\n * Emits an `event:`/`id:`/`retry:` line for each present field, then one\n * `data:` line per CRLF-aware-split (`\\r\\n` / `\\r` / `\\n`) segment of `data`\n * (so a consuming parser's multi-`data` concat reproduces `data` with each\n * line break read as `\\n`, and no raw `\\r` or `\\n` can ever ride onto the wire\n * inside a `data:` line), then the terminating blank line.\n *\n * It refuses a field the wire cannot carry rather than emit a second field or\n * a second event: an `event` with a line break, an `id` with a line break or\n * a NUL (which a conforming parser drops), and a `retry` that is not a\n * non-negative safe integer.\n *\n * @param message - The event to serialize\n * @returns The SSE wire text for the event (terminated by a blank line)\n * @throws {ServerError} Thrown when a field is refused, with code `'EVENT'`\n * and `context.field` naming the field\n *\n * @example\n * ```ts\n * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\\ndata: hello\\n\\n'\n * serializeEvent({ data: 'multi\\nline' }) // 'data: multi\\ndata: line\\n\\n'\n * ```\n */\nexport function serializeEvent(message: SSEMessage): string {\n\tconst { event, id, retry } = message\n\tif (event !== undefined && /[\\r\\n]/.test(event))\n\t\tthrow new ServerError('EVENT', 'an SSE event type must be one line', { field: 'event' })\n\tif (id !== undefined && /[\\r\\n\\0]/.test(id))\n\t\tthrow new ServerError('EVENT', 'an SSE id must be one line with no NUL', { field: 'id' })\n\tif (retry !== undefined && !(isSafeInteger(retry) && retry >= 0))\n\t\tthrow new ServerError('EVENT', 'an SSE retry must be a non-negative safe integer', {\n\t\t\tfield: 'retry',\n\t\t})\n\tconst lines = [\n\t\t...(event === undefined ? [] : [`event: ${event}`]),\n\t\t...(id === undefined ? [] : [`id: ${id}`]),\n\t\t...(retry === undefined ? [] : [`retry: ${retry}`]),\n\t\t...message.data.split(SSE_LINE_PATTERN).map((segment) => `data: ${segment}`),\n\t]\n\treturn `${lines.join('\\n')}\\n\\n`\n}\n\n/**\n * Serializes a comment to the SSE wire, one `: ` line per line of `text`.\n *\n * @remarks\n * Splits `text` on `\\r\\n`, `\\r`, and `\\n`, so no line of the comment can\n * reach a parser as a field and no comment can dispatch an event.\n *\n * @example\n * ```ts\n * serializeComment('keep-alive') // ': keep-alive\\n\\n'\n * serializeComment('a\\nb') // ': a\\n: b\\n\\n'\n * ```\n */\nexport function serializeComment(text: string): string {\n\treturn `${text\n\t\t.split(SSE_LINE_PATTERN)\n\t\t.map((line) => `: ${line}`)\n\t\t.join('\\n')}\\n\\n`\n}\n\n// The body pipeline (module-scope) —\n// `readBody` collects a request body capped at `limit` bytes (413 over),\n// transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n// through a byte-counting `TransformStream` that aborts the instant\n// decompressed output exceeds `decompression` (the zip-bomb defense — fail\n// before materializing the bomb, because `DecompressionStream` has no\n// `maxOutputLength` knob), then decodes by content type. `scrubPrototype` /\n// `isDangerousKey` are the prototype-pollution scrub `readBody` applies to a\n// parsed JSON or urlencoded body.\n\n/**\n * Checks whether a key is a prototype-pollution vector — `__proto__`,\n * `constructor`, or `prototype`, each of which can reach and mutate\n * `Object.prototype` when it is assigned onto a normal object.\n *\n * @param key - The candidate object key\n * @returns True if `key` is one of the three prototype-pollution keys; false otherwise\n *\n * @example\n * ```ts\n * isDangerousKey('__proto__') // true\n * isDangerousKey('name') // false\n * ```\n */\nexport function isDangerousKey(key: string): boolean {\n\treturn key === '__proto__' || key === 'constructor' || key === 'prototype'\n}\n\n/**\n * Strips the prototype-pollution keys from a parsed value in place, at every depth.\n *\n * @remarks\n * `JSON.parse('{\"__proto__\":{…}}')` is benign on its own — it produces an own,\n * enumerable `__proto__` data property — but that own key becomes a\n * pollution gadget the moment a downstream deep-merge copies it onto a live\n * object. This walks the value and `delete`s any own {@link isDangerousKey}\n * key at every depth, into nested records and array elements.\n * Primitives/`null` pass through untouched. Total — never throws. Mutates the\n * freshly-parsed value (which nothing else holds yet).\n *\n * The walk keeps a worklist rather than the call stack, so a value nested as\n * deep as the body limit admits costs no stack depth, and it reads a node\n * reached twice once, so a self-referencing value terminates.\n *\n * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)\n * @returns The same `value`, with every dangerous key removed at every depth\n *\n * @example\n * ```ts\n * scrubPrototype(JSON.parse('{\"__proto__\":{\"polluted\":true},\"name\":\"ok\"}'))\n * // { name: 'ok' } — the __proto__ key is gone\n * ```\n */\nexport function scrubPrototype(value: unknown): unknown {\n\tconst nodes = new Set<unknown>([value])\n\tfor (const node of nodes) {\n\t\tif (isArray(node)) {\n\t\t\tfor (const member of node)\n\t\t\t\tif (isObject(member) && (isArray(member) || isRecord(member))) nodes.add(member)\n\t\t\tcontinue\n\t\t}\n\t\tif (!isRecord(node)) continue\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (isDangerousKey(key)) {\n\t\t\t\tReflect.deleteProperty(node, key)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst member = node[key]\n\t\t\tif (isObject(member) && (isArray(member) || isRecord(member))) nodes.add(member)\n\t\t}\n\t}\n\treturn value\n}\n\n/**\n * Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.\n *\n * @remarks\n * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,\n * throwing a {@link ContentTooLargeError} (413) the instant the running total\n * exceeds `limit` — before the rest of the stream is buffered — rather than\n * collecting an unbounded body. A bodyless request (`request.body === null`)\n * resolves an empty array. A non-positive `limit` means unbounded. When\n * `request.signal` aborts before the call or while a read waits, the body is\n * cancelled with the signal's reason and the promise rejects with that reason.\n *\n * @param request - The `Request` to drain\n * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded\n * @returns The full request body as one `Uint8Array`\n * @throws {ContentTooLargeError} When the body exceeds `limit`\n *\n * @example\n * ```ts\n * const bytes = await collectRequestBody(request, 1_048_576)\n * ```\n */\nexport async function collectRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst signal = request.signal\n\tsignal.throwIfAborted()\n\tif (request.body === null) return new Uint8Array(0)\n\tconst reader = request.body.getReader()\n\tconst chunks: Array<{ readonly bytes: Uint8Array; readonly total: number }> = []\n\tconst relay = addAbortListener(signal, () => reader.cancel(signal.reason).catch(() => undefined))\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tsignal.throwIfAborted()\n\t\t\tif (done) break\n\t\t\tconst total = (chunks.at(-1)?.total ?? 0) + value.byteLength\n\t\t\tif (limit > 0 && total > limit) {\n\t\t\t\tawait reader.cancel()\n\t\t\t\tthrow new ContentTooLargeError(limit)\n\t\t\t}\n\t\t\tchunks.push({ bytes: value, total })\n\t\t}\n\t} finally {\n\t\trelay[Symbol.dispose]()\n\t}\n\tconst merged = new Uint8Array(chunks.at(-1)?.total ?? 0)\n\tchunks.reduce((offset, chunk) => {\n\t\tmerged.set(chunk.bytes, offset)\n\t\treturn offset + chunk.bytes.byteLength\n\t}, 0)\n\treturn merged\n}\n\n/**\n * Parses a raw `Content-Encoding` header value into a decompressible\n * {@link Encoding} — the boundary {@link readBody} coerces through to decide\n * whether a request body needs transparent decompression.\n *\n * @remarks\n * Lower-cases + trims and returns the matching {@link Encoding} only for\n * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An\n * absent header, `identity`, an unknown value, or a\n * comma-joined multi-coding all yield `undefined` (the body is read as-is).\n * Total — never asserts the loose `string | null` header.\n *\n * @param header - The raw `Content-Encoding` header value\n * @returns The single decompressible {@link Encoding}, or `undefined` when none applies\n *\n * @example\n * ```ts\n * parseEncoding('gzip') // 'gzip'\n * parseEncoding('br') // undefined — unsupported by DecompressionStream\n * ```\n */\nexport function parseEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined {\n\tif (!isString(header)) return undefined\n\tconst value = header.trim().toLowerCase()\n\treturn value === 'gzip' || value === 'deflate' ? value : undefined\n}\n\n/**\n * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence\n * transparently through `DecompressionStream`, capping the decompressed output —\n * the zip-bomb defense.\n *\n * @remarks\n * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting\n * `TransformStream` that aborts the pipe the instant the running decompressed\n * total exceeds `cap` — fail-before-materialize, because `DecompressionStream`\n * has no `maxOutputLength` knob. A cap breach surfaces\n * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated\n * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}\n * (never conflated with the cap). A non-positive `cap` means uncapped.\n *\n * @param bytes - The compressed bytes to decompress\n * @param encoding - The {@link Encoding} the bytes are compressed with\n * @param cap - The maximum decompressed byte count; a non-positive value means uncapped\n * @returns The decompressed bytes\n * @throws {ContentTooLargeError} When decompressed output would exceed `cap`\n * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)\n */\nexport async function decompressRequestBody(\n\tbytes: Uint8Array<ArrayBuffer>,\n\tencoding: Exclude<Encoding, 'identity'>,\n\tcap: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst chunks: Array<{ readonly bytes: Uint8Array; readonly total: number }> = []\n\tconst capStream = new TransformStream<Uint8Array, Uint8Array>({\n\t\ttransform(chunk, controller) {\n\t\t\tconst total = (chunks.at(-1)?.total ?? 0) + chunk.byteLength\n\t\t\tif (cap > 0 && total > cap) {\n\t\t\t\tcontroller.error(new ContentTooLargeError(cap))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tchunks.push({ bytes: chunk, total })\n\t\t\tcontroller.enqueue(chunk)\n\t\t},\n\t})\n\tconst source = new ReadableStream<Uint8Array<ArrayBuffer>>({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(bytes)\n\t\t\tcontroller.close()\n\t\t},\n\t})\n\tconst decompressed = source.pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream)\n\tconst reader = decompressed.getReader()\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done } = await reader.read()\n\t\t\tif (done) break\n\t\t}\n\t} catch (error) {\n\t\tif (isInstance(error, ContentTooLargeError)) throw error\n\t\tthrow new HTTPError(400, 'malformed compressed request body')\n\t}\n\tconst merged = new Uint8Array(chunks.at(-1)?.total ?? 0)\n\tchunks.reduce((offset, chunk) => {\n\t\tmerged.set(chunk.bytes, offset)\n\t\treturn offset + chunk.bytes.byteLength\n\t}, 0)\n\treturn merged\n}\n\n/**\n * Collects and decodes a `Request` body — the shared body-collection pipeline\n * surfaced to middleware and handlers as the middleware context's cached\n * `body()`. An empty body and a malformed `application/json` body each decode to\n * `undefined`.\n *\n * @remarks\n * Collects the wire body capped at `options.limit` bytes ({@link\n * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),\n * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at\n * `options.decompression`, default {@link\n * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by\n * content type: `application/json` is parsed by using `@orkestrel/contract`'s\n * `parseJSON`, `application/x-www-form-urlencoded` is read through\n * `URLSearchParams` into a record whose repeated field keeps its last value,\n * and both are scrubbed of prototype-pollution keys ({@link scrubPrototype});\n * any other type decodes as UTF-8 text. The media type matches\n * case-insensitively and ignores its parameters.\n *\n * A malformed JSON body is total: it decodes rather than throwing, so a handler\n * that must reject one checks for `undefined` itself, and nothing in the returned\n * value tells an empty body from a malformed one.\n *\n * @param request - The `Request` to read the body from\n * @param options - The {@link BodyOptions} `limit` + `decompression` caps\n * @returns The parsed JSON value, the decoded form record, the raw text, or\n * `undefined` — for an empty body, and for an `application/json` body whose\n * text is not valid JSON\n * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap\n * @throws {HTTPError} When the compressed body is corrupt (400)\n *\n * @example\n * ```ts\n * const body = await readBody(request, { limit: 1_048_576 })\n * ```\n */\nexport async function readBody(request: Request, options?: BodyOptions): Promise<unknown> {\n\tconst limit = options?.limit ?? DEFAULT_BODY_LIMIT\n\tconst decompression = options?.decompression ?? DEFAULT_DECOMPRESSED_LIMIT\n\tconst wire = await collectRequestBody(request, limit)\n\tconst encoding = parseEncoding(request.headers.get('content-encoding'))\n\tconst bytes =\n\t\tencoding === undefined ? wire : await decompressRequestBody(wire, encoding, decompression)\n\tif (bytes.length === 0) return undefined\n\tconst contentType = request.headers.get('content-type')\n\tconst semicolon = contentType === null ? -1 : contentType.indexOf(';')\n\tconst bareType =\n\t\tcontentType === null\n\t\t\t? ''\n\t\t\t: (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase()\n\tconst text = new TextDecoder().decode(bytes)\n\tif (bareType === 'application/json') return scrubPrototype(parseJSON(text))\n\tif (bareType === 'application/x-www-form-urlencoded')\n\t\treturn scrubPrototype(Object.fromEntries(new URLSearchParams(text)))\n\treturn text\n}\n\n// ============================================================================\n// The node face — pure helpers. Every function here is genuinely\n// node-bound (a `node:net` probe) — everything\n// fetch/string-pure lives earlier in this same file and is consumed, never\n// duplicated (the socket-encrypted narrow and the `Request`/`Response`\n// conversion are `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` /\n// `sendResponse`).\n// ============================================================================\n\n/**\n * Binds and closes a throwaway TCP server to resolve one available port.\n *\n * @remarks\n * The probe always closes, including on the rejection path. A listener whose\n * address is not an {@link import('node:net').AddressInfo} — a pipe listener,\n * which a numeric `port` cannot request — has no port to report, so this\n * rejects rather than substituting a number.\n *\n * @param port - The requested port, with `0` selecting an ephemeral port\n * @returns The bound port after the probe server has closed\n * @throws {TypeError} When the bound listener's address carries no numeric port\n *\n * @example\n * ```ts\n * const port = await probePort(0)\n * ```\n */\nexport async function probePort(port: number): Promise<number> {\n\tconst probe = createNetServer()\n\tconst listening = once(probe, 'listening')\n\tprobe.listen(port)\n\tawait listening\n\tconst address = probe.address()\n\tconst closed = once(probe, 'close')\n\tprobe.close()\n\tawait closed\n\t// This branch is unreachable through `listen(port)` and exists for the other members of `address()`'s union.\n\tif (!isAddressInfo(address)) {\n\t\tthrow new TypeError('server bound a listener with no resolvable AddressInfo')\n\t}\n\treturn address.port\n}\n\n/**\n * Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`\n * port where one is given and on an ephemeral port otherwise, reads the bound\n * port, closes the server, and resolves that port.\n *\n * @remarks\n * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)\n * and returns it. With a `preferred` port it tries that port first and\n * returns it when free; if already in use (`EADDRINUSE`) it falls back to an\n * ephemeral free port rather than rejecting — a caller always gets a usable\n * port. It binds then immediately closes a probe server, so the returned\n * port is free at the instant of the probe (an inherent TOCTOU race — bind it\n * promptly). Rejects only on an unexpected listen error other than a taken\n * `preferred` port (for example, a permission fault). A listener whose address is not\n * an {@link import('node:net').AddressInfo} — a pipe listener, which this\n * package's options cannot request — rejects with a `TypeError` rather than\n * reporting `0`, because `0` is this package's own request for an ephemeral\n * port and never means an unknown one.\n *\n * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒\n * fall back to an ephemeral port\n * @returns A free TCP port number\n * @throws {TypeError} When the bound listener's address carries no numeric port\n *\n * @example\n * ```ts\n * import { createServer, discoverPort } from '@src/server'\n *\n * const port = await discoverPort() // a guaranteed-free ephemeral port\n * ```\n */\nexport async function discoverPort(preferred?: number): Promise<number> {\n\tif (preferred === undefined) return probePort(0)\n\tconst probed = await settle(() => probePort(preferred))\n\tif (probed.success) return probed.value\n\tif (isCodedError(probed.error) && probed.error.code === 'EADDRINUSE') return probePort(0)\n\tthrow probed.error\n}\n\n/**\n * Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the\n * `Response` constructor admits keeps that status, and every other value renders a 500 whose\n * message stays hidden unless `expose` is `true`.\n *\n * @remarks\n * The renderer is total: it returns a `Response` for every value and never throws.\n * - An `HTTPError` whose status the `Response` constructor admits renders that status with its\n * message as the body, and with no body for a null body status (204, 205, and 304).\n * - Every other value renders 500: a throw that is no `HTTPError`, and an `HTTPError` whose status\n * no `Response` carries (an integer below 200 or above 599, which includes 101 and 103, or a\n * status that is not an integer). Its body is `Internal Server Error`, or the error's own message\n * when `expose` is `true` and the value is an `Error`.\n * - A thrown value is a fault to report when it is no `HTTPError`, or when the rendered status\n * differs from its `status`. The server's boundary reports those values with their\n * `RequestLine`, except a throw after the peer disconnected, which is no fault and reports\n * nothing.\n *\n * @param error - The thrown value\n * @param expose - If `true`, a 500 carries the message of the `Error` it renders; if `false`, it\n * carries `Internal Server Error`\n * @returns The response to send\n *\n * @example\n * ```ts\n * import { buildErrorResponse, HTTPError } from '@src/server'\n *\n * buildErrorResponse(new HTTPError(404, 'no such lamp'), false).status // 404\n * buildErrorResponse(new HTTPError(600, 'past the range'), false).status // 500\n * buildErrorResponse(new Error('database offline'), true).status // 500, body 'database offline'\n * ```\n */\nexport function buildErrorResponse(error: unknown, expose: boolean): Response {\n\tif (isHTTPError(error)) {\n\t\tconst rendered = attempt(() => {\n\t\t\tconst status = error.status\n\t\t\tconst full = attempt(() => new Response(error.message, { status }))\n\t\t\tconst response = full.success ? full.value : new Response(null, { status })\n\t\t\treturn response.status === status ? response : undefined\n\t\t})\n\t\tif (rendered.success && rendered.value !== undefined) return rendered.value\n\t}\n\tconst message = attempt(() => (expose && isError(error) ? error.message : undefined))\n\treturn new Response(\n\t\tmessage.success && isString(message.value) ? message.value : 'Internal Server Error',\n\t\t{ status: 500 },\n\t)\n}\n","import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js'\nimport {\n\tcomputeLanguageQuality,\n\tmatchMediaType,\n\tmergeVary,\n\tparseAcceptHeader,\n\tresolveCoding,\n} from './helpers.js'\n\n/**\n * Represents the content-negotiation machine over the weighted `Accept` family — a\n * reusable, cross-middleware entity rather than a middleware. Implements exactly\n * {@link NegotiatorInterface}.\n *\n * @remarks\n * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /\n * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its\n * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the\n * rest of the substrate uses — one parser, never two. A media type matches\n * case-insensitively. `format` reads the request `Accept`, negotiates a\n * {@link FormatHandlerMap}'s keys, and invokes the winner — or answers\n * `406 Not Acceptable` — and sets `Vary: Accept` on either answer.\n *\n * @example\n * ```ts\n * const negotiator = new Negotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport class Negotiator implements NegotiatorInterface {\n\tnegotiate(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tconst best = Iterator.from(available).reduce<\n\t\t\t{ readonly value: string; readonly q: number; readonly rank: number } | undefined\n\t\t>((previous, candidate) => {\n\t\t\tconst match = matchMediaType(entries, candidate)\n\t\t\tif (match === undefined) return previous\n\t\t\tconst { q, rank } = match\n\t\t\treturn q > (previous?.q ?? 0) ||\n\t\t\t\t(q === (previous?.q ?? 0) && rank < (previous?.rank ?? Number.POSITIVE_INFINITY))\n\t\t\t\t? { value: candidate, q, rank }\n\t\t\t\t: previous\n\t\t}, undefined)\n\t\treturn best?.value\n\t}\n\n\tencoding(header: string, available: readonly Encoding[]): Encoding | undefined {\n\t\tif (available.length === 0) return undefined\n\t\treturn resolveCoding(parseAcceptHeader(header), available)\n\t}\n\n\tlanguage(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tconst best = Iterator.from(available).reduce<\n\t\t\t{ readonly value: string; readonly quality: number } | undefined\n\t\t>((previous, candidate) => {\n\t\t\tconst quality = computeLanguageQuality(entries, candidate)\n\t\t\treturn quality > (previous?.quality ?? 0) ? { value: candidate, quality } : previous\n\t\t}, undefined)\n\t\treturn best?.value\n\t}\n\n\t/**\n\t * Dispatches the request to the handler its `Accept` header negotiates,\n\t * answering 406 when none matches.\n\t *\n\t * @remarks\n\t * Errors thrown by the negotiated handler propagate unmodified — the\n\t * server boundary classifies them, never this negotiator. The answer is a\n\t * copy of the handler's response carrying `Vary: Accept`.\n\t */\n\tasync format<TState>(\n\t\trequest: Request,\n\t\tcontext: MiddlewareContext<TState>,\n\t\thandlers: FormatHandlerMap<TState>,\n\t): Promise<Response> {\n\t\tconst keys = Object.keys(handlers)\n\t\tconst header = request.headers.get('accept')\n\t\tconst type = header === null ? keys[0] : this.negotiate(header, keys)\n\t\tconst handler = type === undefined ? undefined : handlers[type]\n\t\tif (handler === undefined) {\n\t\t\treturn new Response('Not Acceptable', { status: 406, headers: { Vary: 'Accept' } })\n\t\t}\n\t\tconst response = await handler(request, context)\n\t\tconst headers = new Headers(response.headers)\n\t\theaders.set('Vary', mergeVary(headers.get('vary') ?? undefined, 'Accept'))\n\t\treturn new Response(response.body, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t\theaders,\n\t\t})\n\t}\n}\n","import type { Server as NodeHTTPServer } from 'node:http'\nimport { once } from 'node:events'\nimport { isAddressInfo } from './validators.js'\n\n/**\n * Owns one startup attempt's listening subscription and validated bound port.\n *\n * @remarks\n * Create an instance per bind attempt. Subscribe before calling the native server's\n * `listen`, retain `pending` for failure cleanup, and record the native address after\n * listening settles. Reading `port` before a valid address was recorded throws.\n */\nexport class ServerBinding {\n\t#pending: Promise<readonly unknown[]> | undefined\n\t#port: number | undefined\n\n\tget pending(): Promise<readonly unknown[]> | undefined {\n\t\treturn this.#pending\n\t}\n\n\tget port(): number {\n\t\tif (this.#port === undefined) {\n\t\t\tthrow new TypeError('server bound a listener with no resolvable AddressInfo')\n\t\t}\n\t\treturn this.#port\n\t}\n\n\tsubscribe(server: NodeHTTPServer, signal: AbortSignal): Promise<readonly unknown[]> {\n\t\tconst pending = once(server, 'listening', { signal })\n\t\tthis.#pending = pending\n\t\treturn pending\n\t}\n\n\trecord(address: unknown): void {\n\t\tif (!isAddressInfo(address)) {\n\t\t\tthrow new TypeError('server bound a listener with no resolvable AddressInfo')\n\t\t}\n\t\tthis.#port = address.port\n\t}\n}\n","import type {\n\tIncomingMessage,\n\tServer as NodeHTTPServer,\n\tServerOptions as NodeHTTPServerOptions,\n\tServerResponse,\n} from 'node:http'\nimport type { AddressInfo, Socket } from 'node:net'\nimport type { Duplex } from 'node:stream'\nimport type { AbortInterface } from '@orkestrel/abort'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnection,\n\tConnectionStateFunction,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tRequestLine,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { addAbortListener, once } from 'node:events'\nimport { createServer as createHTTPServer } from 'node:http'\nimport { createAbort, linkSignal } from '@orkestrel/abort'\nimport { createTimeout, isTimeoutDuration } from '@orkestrel/timeout'\nimport { buildRequest, isEncryptedSocket, sendResponse } from '@orkestrel/router/server'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tattempt,\n\tisFiniteNumber,\n\tisFunction,\n\tisInteger,\n\tisPromise,\n\trefuseValue,\n\tsettle,\n} from '@orkestrel/contract'\nimport { buildErrorResponse, compose, iterateRequestBody } from './helpers.js'\nimport { isAddressInfo } from './validators.js'\nimport {\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tDEFAULT_HEADERS_TIMEOUT_MS,\n\tDEFAULT_REQUEST_TIMEOUT_MS,\n} from './constants.js'\nimport { HTTPError, isHTTPError, ServerError } from './errors.js'\nimport { ServerBinding } from './ServerBinding.js'\n\n/**\n * Represents the HTTP server facade — an observable `node:http` lifecycle composing this\n * module's own middleware onion around a consumed `@orkestrel/router`\n * dispatcher. Implements exactly {@link ServerInterface}.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n *\n * @remarks\n * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`\n * server, binds the configured {@link ServerOptions.host} / {@link\n * ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the\n * bound address), exposes that {@link AddressInfo} through `address`, observes\n * caller cancellation plus the configured `timeouts.start` deadline while the\n * bind is pending, and transitions `idle → starting → listening`. A\n * cancelled or expired bind closes its partial server and resets to `idle` for\n * another start. `stop()` transitions\n * to `stopping`: aborts the signal of every in-flight request so handlers\n * observe cancellation (a request that arrives during the drain is served\n * with its signal already aborted), drains in-flight requests and\n * claimed upgraded sockets up to the `drain` deadline (event-driven, no\n * busy-loop), then closes → `stopped`. After a clean drain the close\n * destroys every connection that carries no open request exchange, and a\n * connection that still carries one ends when its last exchange completes\n * or the same `drain` deadline expires, whichever comes first.\n * A request or an upgrade that such a connection sends after the listener\n * closes is refused: its connection is destroyed before the request is\n * counted or a handler sees it, so the `stop()` call waits only on work\n * counted before the close. After an expired drain the close destroys every\n * socket. A `stop()` call made while a stop runs returns that stop's\n * promise. `destroy()` is the idempotent final teardown.\n * - **Per request.** The exchange's own `AbortController` joins the\n * in-flight registry until the response's `close`; the one\n * `Request` of the exchange is built through the router's `buildRequest`\n * with that controller's signal, so `request.signal` aborts on a peer\n * disconnect, on `context.abort(reason)`, or on `stop()`, and no request\n * signal links to a signal that outlives the exchange; `context.state` is\n * built through {@link ServerOptions.state} from the connection facts, which\n * `context.connection` carries as the same object; the composed middleware\n * onion runs, terminating in `dispatcher.handle`; the result is written\n * back through `sendResponse`.\n * - **The built-in boundary** wraps the whole per-request chain, including\n * setup: `buildRequest` runs behind its own inner boundary that maps a\n * throw (for example, a malformed `Host` header) to a silent `400` with no\n * `error` emit; everything after (connection\n * facts, `state`, the composed onion, and `dispatcher.handle`) runs\n * behind the outer boundary, which renders a throw through\n * `buildErrorResponse`: an `HTTPError` whose status `Response` admits\n * keeps that status, with no body for 204, 205, and 304, and every other\n * throw renders `500` (message hidden unless `expose`). Each fault, every\n * throw except an `HTTPError` whose status the response carries and a\n * throw after a peer disconnect the server read first (the peer's FIN or a\n * reset), reaches `error` and `report` with its\n * `RequestLine`; a fault on the inner phase's `400` path carries none,\n * because no `Request` exists there. A `report` that throws or rejects is\n * contained, except a rejected native promise whose species constructor\n * cannot build a promise, which reaches `unhandledRejection` (see\n * `ServerOptions.report`). A write that fails destroys the connection and is a fault, unless the peer disconnected first,\n * and a terminal catch over the whole exchange, the `400` path included,\n * holds a throw from any step.\n * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a\n * throwing handler is treated as declined and surfaced on `error`, an\n * unclaimed upgrade destroys the socket), bound per-run to this instance.\n * A claimed socket joins `#upgraded` until it closes: the claimant still\n * owns it, and the tracking exists because Node detaches an upgraded socket\n * from the set its own close calls walk, so nothing else can end it.\n * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}\n * exposed as `readonly emitter`; the emitter isolates a listener throw and\n * routes it to the `error` option rather than to the domain `error` event.\n */\nexport class Server<TState> implements ServerInterface<TState> {\n\treadonly #id: string\n\treadonly #dispatcher: DispatcherInterface<TState>\n\treadonly #state: ConnectionStateFunction<TState>\n\treadonly #middleware: Array<MiddlewareHandler<TState>>\n\treadonly #upgradeHandlers: UpgradeHandler[] = []\n\treadonly #upgraded = new Set<Duplex>()\n\treadonly #requests = new Set<AbortController>()\n\treadonly #exchanges = new Map<Socket, Map<ServerResponse, () => void>>()\n\treadonly #emitter: Emitter<ServerEventMap>\n\treadonly #host: string | undefined\n\treadonly #configuredPort: number | undefined\n\treadonly #drain: number\n\treadonly #limit: number\n\treadonly #expose: boolean\n\treadonly #report: ((error: unknown, request?: RequestLine) => void) | undefined\n\treadonly #startup: number | undefined\n\treadonly #options: NodeHTTPServerOptions\n\treadonly #sockets: {\n\t\treadonly connections?: number\n\t\treadonly headers?: number\n\t\treadonly requests?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#wakeup: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#stopping: Promise<void> | undefined\n\n\tconstructor(options: ServerOptions<TState>) {\n\t\trefuseValue(options.state, isFunction, 'Server', {\n\t\t\tpath: ['options', 'state'],\n\t\t\tlimit: 'a function',\n\t\t\tcode: 'placement',\n\t\t})\n\t\tif (options.report !== undefined) {\n\t\t\trefuseValue(options.report, isFunction, 'Server', {\n\t\t\t\tpath: ['options', 'report'],\n\t\t\t\tlimit: 'a function',\n\t\t\t\tcode: 'placement',\n\t\t\t})\n\t\t}\n\t\tconst drain = options.drain ?? DEFAULT_DRAIN_MS\n\t\trefuseValue(drain, isTimeoutDuration, 'Server', {\n\t\t\tpath: ['options', 'drain'],\n\t\t\tlimit: 'an integer from 0 through 2_147_483_647',\n\t\t\tcode: 'range',\n\t\t})\n\t\tconst limit = options.limit ?? DEFAULT_BODY_LIMIT\n\t\trefuseValue(limit, (value): value is number => isFiniteNumber(value) && value >= 0, 'Server', {\n\t\t\tpath: ['options', 'limit'],\n\t\t\tlimit: 'a non-negative finite number',\n\t\t\tcode: 'range',\n\t\t})\n\t\tconst timeouts = options.timeouts ?? {}\n\t\tfor (const [name, value] of Object.entries(timeouts)) {\n\t\t\t// Node arms `keepalive` plus its default 1_000 ms `keepAliveTimeoutBuffer` as one timer.\n\t\t\tif (value === undefined) continue\n\t\t\tif (name === 'keepalive') {\n\t\t\t\trefuseValue(\n\t\t\t\t\tvalue,\n\t\t\t\t\t(candidate): candidate is number =>\n\t\t\t\t\t\tisTimeoutDuration(candidate) && isTimeoutDuration(candidate + 1_000),\n\t\t\t\t\t'Server',\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: ['options', 'timeouts', name],\n\t\t\t\t\t\tlimit: 'an integer from 0 through 2_147_482_647',\n\t\t\t\t\t\tcode: 'range',\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\trefuseValue(value, isTimeoutDuration, 'Server', {\n\t\t\t\t\tpath: ['options', 'timeouts', name],\n\t\t\t\t\tlimit: 'an integer from 0 through 2_147_483_647',\n\t\t\t\t\tcode: 'range',\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\t// Node's own defaults, so the relation and the checking interval read the values Node enforces.\n\t\tconst request = timeouts.request ?? DEFAULT_REQUEST_TIMEOUT_MS\n\t\tconst headers = timeouts.headers ?? Math.min(DEFAULT_HEADERS_TIMEOUT_MS, request)\n\t\trefuseValue(\n\t\t\theaders,\n\t\t\t(value): value is number => !(request > 0 && Number(value) > request),\n\t\t\t'Server',\n\t\t\t{\n\t\t\t\tpath: ['options', 'timeouts', 'headers'],\n\t\t\t\tlimit:\n\t\t\t\t\t'no greater than options.timeouts.request (300_000 when omitted) while it is positive',\n\t\t\t\tcode: 'range',\n\t\t\t},\n\t\t)\n\t\tconst checked = [headers, request].filter((ms) => ms > 0)\n\t\tconst sockets = options.sockets ?? {}\n\t\tfor (const [name, value] of Object.entries(sockets)) {\n\t\t\tif (value === undefined) continue\n\t\t\trefuseValue(\n\t\t\t\tvalue,\n\t\t\t\t(candidate): candidate is number => isInteger(candidate) && candidate >= 0,\n\t\t\t\t'Server',\n\t\t\t\t{\n\t\t\t\t\tpath: ['options', 'sockets', name],\n\t\t\t\t\tlimit: 'a non-negative integer',\n\t\t\t\t\tcode: 'range',\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tthis.#id = crypto.randomUUID()\n\t\tthis.#dispatcher = options.dispatcher\n\t\tthis.#state = options.state\n\t\tthis.#middleware = options.middleware === undefined ? [] : [...options.middleware]\n\t\tthis.#host = options.host\n\t\tthis.#configuredPort = options.port\n\t\tthis.#drain = drain\n\t\tthis.#limit = limit\n\t\tthis.#expose = options.expose ?? false\n\t\tthis.#report = options.report\n\t\tthis.#startup = timeouts.start\n\t\tthis.#options = {\n\t\t\theadersTimeout: headers,\n\t\t\trequestTimeout: request,\n\t\t\t...(timeouts.keepalive === undefined ? {} : { keepAliveTimeout: timeouts.keepalive }),\n\t\t\t...(checked.length === 0\n\t\t\t\t? {}\n\t\t\t\t: { connectionsCheckingInterval: Math.ceil(Math.min(...checked) / 2) }),\n\t\t}\n\t\tthis.#sockets = sockets\n\t\tthis.#emitter = new Emitter<ServerEventMap>({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\tget id(): string {\n\t\treturn this.#id\n\t}\n\n\tget status(): ServerStatus {\n\t\treturn this.#status\n\t}\n\n\tget port(): number | undefined {\n\t\treturn this.#port\n\t}\n\n\tget address(): AddressInfo | undefined {\n\t\tconst address = this.#http?.address()\n\t\treturn isAddressInfo(address) ? address : undefined\n\t}\n\n\tget dispatcher(): DispatcherInterface<TState> {\n\t\treturn this.#dispatcher\n\t}\n\n\tget emitter(): EmitterInterface<ServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tuse(middleware: MiddlewareHandler<TState>): void\n\tuse(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void\n\tuse(middleware: MiddlewareHandler<TState> | ReadonlyArray<MiddlewareHandler<TState>>): void {\n\t\tif (typeof middleware === 'function') this.#middleware.push(middleware)\n\t\telse this.#middleware.push(...middleware)\n\t}\n\n\tupgrade(handler: UpgradeHandler): void {\n\t\tthis.#upgradeHandlers.push(handler)\n\t}\n\n\tstart(signal?: AbortSignal): Promise<number> {\n\t\tif (this.#status !== 'idle' && this.#status !== 'stopped') {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew ServerError('STATUS', `server cannot start from '${this.#status}'`, {\n\t\t\t\t\tstatus: this.#status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tthis.#status = 'starting'\n\t\tconst server = createHTTPServer(this.#options, (request, response) =>\n\t\t\tthis.#handle(request, response),\n\t\t)\n\t\tif (this.#sockets.connections !== undefined) server.maxConnections = this.#sockets.connections\n\t\tif (this.#sockets.headers !== undefined) server.maxHeadersCount = this.#sockets.headers\n\t\tif (this.#sockets.requests !== undefined) server.maxRequestsPerSocket = this.#sockets.requests\n\t\t// Bound to this run's server instance, discarded with it on stop/restart —\n\t\t// no manual removal needed (the same per-run lifecycle as the request\n\t\t// handler `createHTTPServer` takes).\n\t\tserver.on('upgrade', (request, socket, head) => this.#onUpgrade(request, socket, head))\n\t\tserver.on('connection', (socket) => this.#trackConnection(socket))\n\t\tthis.#http = server\n\t\treturn this.#listen(server, signal)\n\t}\n\n\t// A call during a stop returns the stop in flight, so every caller resolves\n\t// after the same close; the field is released only by the stop that set it.\n\t// The promise is published before the stop's synchronous prologue, because\n\t// that prologue emits `stop` and aborts every in-flight request's signal, and\n\t// a listener on either can call this method.\n\tstop(): Promise<void> {\n\t\tif (this.#status !== 'listening') return this.#stopping ?? Promise.resolve()\n\t\tconst { promise, resolve, reject } = Promise.withResolvers<void>()\n\t\tthis.#stopping = promise\n\t\tvoid this.#stopGracefully()\n\t\t\t.finally(() => {\n\t\t\t\tif (this.#stopping === promise) this.#stopping = undefined\n\t\t\t})\n\t\t\t.then(resolve, reject)\n\t\treturn promise\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#status === 'stopped' && this.#http === undefined) {\n\t\t\tthis.#emitter.destroy()\n\t\t\treturn\n\t\t}\n\t\tfor (const exchange of this.#requests) exchange.abort()\n\t\tconst server = this.#http\n\t\tif (server !== undefined) await this.#close(server, true)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// One `drain` deadline bounds the whole stop: it bounds the drain, then\n\t// stays armed through the clean close's wait on open exchanges, and its\n\t// expiry cuts what is still held as an expired drain does. It is a pure\n\t// clock rather than a child of any signal, because a parent abort clears\n\t// a `Timeout` instead of expiring it.\n\tasync #stopGracefully(): Promise<void> {\n\t\tthis.#status = 'stopping'\n\t\tthis.#emitter.emit('stop')\n\t\tconst server = this.#http\n\t\tfor (const exchange of this.#requests) exchange.abort()\n\t\tconst deadline: TimeoutInterface = createTimeout({ ms: this.#drain })\n\t\tdeadline.start()\n\t\ttry {\n\t\t\tawait this.#drainPending(deadline.signal)\n\t\t\tconst pending = this.#requests.size\n\t\t\tconst upgraded = this.#upgraded.size\n\t\t\tthis.#emitter.emit('drain', pending, upgraded)\n\t\t\tif (server !== undefined) {\n\t\t\t\tconst relay = addAbortListener(deadline.signal, () => this.#cut(server))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#close(server, pending + upgraded > 0)\n\t\t\t\t} finally {\n\t\t\t\t\trelay[Symbol.dispose]()\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tdeadline.clear()\n\t\t}\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t}\n\n\t// Register the exchange's abort handle for draining first — before anything\n\t// that can throw — so the sync listener itself never throws; the rest of\n\t// setup (which can throw on a malformed request) is deferred into the async\n\t// `#accept` entry, kept behind the built-in boundary. A request that arrives\n\t// while the drain runs is registered already aborted. A request parsed after\n\t// the close on a connection an open exchange still holds is not counted\n\t// work, so its connection is destroyed before the request counts or runs.\n\t#handle(message: IncomingMessage, response: ServerResponse): void {\n\t\tif (this.#closed) {\n\t\t\tmessage.socket.destroy()\n\t\t\treturn\n\t\t}\n\t\tconst exchange = new AbortController()\n\t\tconst disconnect = new AbortController()\n\t\tconst release = this.#register(exchange)\n\t\tif (this.#status === 'stopping') exchange.abort()\n\t\t// Only the connection tells a peer disconnect from a close the server or Node made.\n\t\tconst socket = message.socket\n\t\tresponse.once('close', () => this.#latch(socket, response, disconnect, release))\n\t\tvoid this.#trackExchange(message, response, () => {\n\t\t\tthis.#latch(socket, response, disconnect, release)\n\t\t\texchange.abort()\n\t\t})\n\t\tvoid this.#accept(message, response, exchange, disconnect.signal)\n\t}\n\n\t// Latch the peer disconnect the socket shows, an error on the response excluded, then release the exchange.\n\t#latch(\n\t\tsocket: Socket,\n\t\tresponse: ServerResponse,\n\t\tdisconnect: AbortController,\n\t\trelease: () => void,\n\t): void {\n\t\tconst failure = socket.errored\n\t\tconst reset = failure !== null && 'code' in failure && failure.code === 'ECONNRESET'\n\t\tif (!response.writableEnded && response.errored === null && (socket.readableEnded || reset))\n\t\t\tdisconnect.abort()\n\t\trelease()\n\t}\n\n\t// The terminal catch: a throw here, the inner phase's `400` included, has no `RequestLine`.\n\tasync #accept(\n\t\tmessage: IncomingMessage,\n\t\tresponse: ServerResponse,\n\t\texchange: AbortController,\n\t\tdisconnect: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tconst created = attempt(() => buildRequest(message, { response, signal: exchange.signal }))\n\t\t\tif (created.success) await this.#serve(created.value, message, response, exchange, disconnect)\n\t\t\telse\n\t\t\t\tawait this.#respond(\n\t\t\t\t\tbuildErrorResponse(new HTTPError(400, 'invalid request'), false),\n\t\t\t\t\tresponse,\n\t\t\t\t)\n\t\t} catch (error) {\n\t\t\tresponse.destroy()\n\t\t\tthis.#fault(error, undefined)\n\t\t}\n\t}\n\n\t// The terminal catch of an exchange whose `Request` exists, so its faults carry the line.\n\tasync #serve(\n\t\trequest: Request,\n\t\tmessage: IncomingMessage,\n\t\tresponse: ServerResponse,\n\t\texchange: AbortController,\n\t\tdisconnect: AbortSignal,\n\t): Promise<void> {\n\t\tconst line: RequestLine = { method: request.method, url: new URL(request.url) }\n\t\tconst start = performance.now()\n\t\ttry {\n\t\t\tthis.#emitter.emit('request', line.method, line.url.pathname)\n\t\t\tconst result = await this.#run(request, line, message, exchange, disconnect)\n\t\t\tconst sent = await this.#respond(result, response, line, disconnect)\n\t\t\t// A body-less answer after a disconnect still reaches `finish`, so the latch decides.\n\t\t\tif (sent && !disconnect.aborted) {\n\t\t\t\tthis.#emitter.emit('response', {\n\t\t\t\t\tmethod: line.method,\n\t\t\t\t\tpathname: line.url.pathname,\n\t\t\t\t\tstatus: result.status,\n\t\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresponse.destroy()\n\t\t\tthis.#fault(error, line)\n\t\t}\n\t}\n\n\t// A returned status no `Response` carries, as from `Response.error()`, is thrown to render 500.\n\tasync #run(\n\t\trequest: Request,\n\t\tline: RequestLine,\n\t\tmessage: IncomingMessage,\n\t\texchange: AbortController,\n\t\tdisconnect: AbortSignal,\n\t): Promise<Response> {\n\t\ttry {\n\t\t\tconst ip = message.socket.remoteAddress\n\t\t\tconst connection: Connection = {\n\t\t\t\t...(ip === undefined ? {} : { ip }),\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl: line.url,\n\t\t\t\tmethod: line.method,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tconnection,\n\t\t\t\tbody: this.#createBody(request),\n\t\t\t\tabort: exchange.abort.bind(exchange),\n\t\t\t}\n\t\t\tconst runner = compose(this.#middleware, (currentRequest, currentContext) =>\n\t\t\t\tthis.#dispatcher.handle(currentRequest, currentContext.state),\n\t\t\t)\n\t\t\tconst result = await runner(request, context)\n\t\t\tconst status = result.status\n\t\t\tif (isInteger(status) && status >= 200 && status <= 599) return result\n\t\t\tthrow new HTTPError(status, `a handler returned status ${String(status)}`)\n\t\t} catch (error) {\n\t\t\treturn this.#boundary(error, line, disconnect.aborted)\n\t\t}\n\t}\n\n\t// A failed write destroys the connection and is a fault, unless the peer disconnected first.\n\tasync #respond(\n\t\tresult: Response,\n\t\tresponse: ServerResponse,\n\t\tline?: RequestLine,\n\t\tdisconnect?: AbortSignal,\n\t): Promise<boolean> {\n\t\tconst sent = await settle(() => sendResponse(result, response))\n\t\tif (!sent.success) {\n\t\t\tresponse.destroy()\n\t\t\tif (disconnect?.aborted !== true) this.#fault(sent.error, line)\n\t\t\treturn false\n\t\t}\n\t\treturn response.writableFinished\n\t}\n\n\t#boundary(error: unknown, line: RequestLine, disconnected: boolean): Response {\n\t\tconst rendered = buildErrorResponse(error, this.#expose)\n\t\tconst carried = attempt(() => isHTTPError(error) && error.status === rendered.status)\n\t\tif (!disconnected && !(carried.success && carried.value)) this.#fault(error, line)\n\t\treturn rendered\n\t}\n\n\t// `then.call` skips a promise's own `then`; `attempt` holds a throwing `constructor` getter.\n\t#fault(error: unknown, line: RequestLine | undefined): void {\n\t\tif (line === undefined) this.#emitter.emit('error', error)\n\t\telse this.#emitter.emit('error', error, line)\n\t\tconst report = this.#report\n\t\tif (report === undefined) return\n\t\tconst reported = attempt((): unknown => report(error, line))\n\t\tif (!reported.success) return\n\t\tconst value = reported.value\n\t\tattempt(() =>\n\t\t\tisPromise(value)\n\t\t\t\t? Promise.prototype.then.call(value, undefined, () => undefined)\n\t\t\t\t: Promise.resolve(value).catch(() => undefined),\n\t\t)\n\t}\n\n\t// Fan a raw protocol-upgrade out to the registered handlers in\n\t// registration order: the first to return `true` claims the socket. A\n\t// throwing handler is treated as declined — surfaced on `error` — and the\n\t// fan-out continues so a later handler can still claim. Unclaimed ⇒ the\n\t// socket is destroyed so an unhandled upgrade never leaks a connection.\n\t// An upgrade parsed after the close is refused the way the `#handle` method\n\t// refuses a request: its socket is destroyed before any handler sees it.\n\t#onUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {\n\t\tif (this.#closed) {\n\t\t\tsocket.destroy()\n\t\t\treturn\n\t\t}\n\t\tconst handled = Iterator.from(this.#upgradeHandlers).some((handler) => {\n\t\t\ttry {\n\t\t\t\treturn handler(request, socket, head)\n\t\t\t} catch (error) {\n\t\t\t\tthis.#emitter.emit('error', error)\n\t\t\t\treturn false\n\t\t\t}\n\t\t})\n\t\tif (handled) this.#trackSocket(socket)\n\t\telse socket.destroy()\n\t\tthis.#emitter.emit('upgrade', request, handled)\n\t}\n\n\tasync #listen(server: NodeHTTPServer, signal?: AbortSignal): Promise<number> {\n\t\tconst deadline = this.#startup === undefined ? undefined : createTimeout({ ms: this.#startup })\n\t\tconst startup = deadline === undefined ? signal : linkSignal(deadline.signal, signal)\n\t\tconst binding = createAbort()\n\t\tconst relay =\n\t\t\tstartup === undefined\n\t\t\t\t? undefined\n\t\t\t\t: addAbortListener(startup, () => binding.abort(startup.reason))\n\t\tconst operation = new ServerBinding()\n\t\t// The bound port, read inside the `try` so an address carrying none takes\n\t\t// the same cleanup path a failed bind takes. `0` is this package's request\n\t\t// for an ephemeral port, so it can never stand in for an unknown one.\n\t\ttry {\n\t\t\tsignal?.throwIfAborted()\n\t\t\tdeadline?.start()\n\t\t\tif (deadline?.ms === 0 && startup !== undefined) await once(startup, 'abort')\n\t\t\tstartup?.throwIfAborted()\n\t\t\tconst listening = operation.subscribe(server, binding.signal)\n\t\t\tif (startup === undefined) server.listen(this.#configuredPort ?? 0, this.#host)\n\t\t\telse {\n\t\t\t\tserver.listen({\n\t\t\t\t\tport: this.#configuredPort ?? 0,\n\t\t\t\t\t...(this.#host === undefined ? {} : { host: this.#host }),\n\t\t\t\t\tsignal: binding.signal,\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait listening\n\t\t\toperation.record(server.address())\n\t\t} catch (error) {\n\t\t\tconst expired = deadline?.expired === true\n\t\t\tconst cancelled = startup?.aborted === true\n\t\t\t// A cancellation removes `events.once`'s temporary error listener. Keep\n\t\t\t// the discarded server guarded while a simultaneous late bind error\n\t\t\t// settles so it cannot escape as an uncaught process error.\n\t\t\tserver.on('error', () => undefined)\n\t\t\tbinding.abort(error)\n\t\t\tconst listening = operation.pending\n\t\t\tif (listening !== undefined) await listening.catch(() => undefined)\n\t\t\tawait this.#close(server, true)\n\t\t\tthis.#http = undefined\n\t\t\tthis.#port = undefined\n\t\t\tthis.#status = 'idle'\n\t\t\tif (expired && deadline !== undefined) {\n\t\t\t\tthrow new DOMException(\n\t\t\t\t\t`Server startup exceeded ${deadline.ms} milliseconds`,\n\t\t\t\t\t'TimeoutError',\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (cancelled && startup !== undefined) throw startup.reason\n\t\t\tthrow error\n\t\t} finally {\n\t\t\trelay?.[Symbol.dispose]()\n\t\t\tdeadline?.clear()\n\t\t}\n\t\tconst port = operation.port\n\t\tthis.#port = port\n\t\tthis.#status = 'listening'\n\t\tthis.#emitter.emit('start', port)\n\t\treturn port\n\t}\n\n\t#createBody(request: Request): () => Promise<unknown> {\n\t\tconst bodies = iterateRequestBody(request, this.#limit)\n\t\treturn () => bodies.next().value\n\t}\n\n\t// Close the underlying server, resolving after the listener closes, which\n\t// Node does only after every connection has closed. A clean close (the\n\t// drain settled) destroys every connection with no open exchange: one that\n\t// never sent a request, one partway through a header block, and an idle\n\t// keep-alive one. That covers every connection `closeIdleConnections()`\n\t// ends, which `server.close()` also calls itself. A connection with an open\n\t// exchange, such as one whose body still uploads after its response, stays\n\t// open, because destroying it can reset the connection and lose that\n\t// response; the `#trackExchange` method ends it when its count returns to\n\t// zero, and the stop's deadline cuts it if that comes first. A forced close\n\t// (the drain deadline expired, `destroy`, or a failed bind) cuts at once.\n\t#close(server: NodeHTTPServer, force: boolean): Promise<void> {\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tserver.close(() => resolve())\n\t\t\tif (force) this.#cut(server)\n\t\t\telse for (const [socket, open] of this.#exchanges) if (open.size === 0) socket.destroy()\n\t\t})\n\t}\n\n\t// Destroy every socket. A protocol-upgraded socket needs the extra loop:\n\t// Node detaches it from the connection set `closeAllConnections()` walks,\n\t// so that call never reaches it while `server.close()` still waits on it.\n\t#cut(server: NodeHTTPServer): void {\n\t\tserver.closeAllConnections()\n\t\tfor (const socket of this.#upgraded) socket.destroy()\n\t}\n\n\t// Count a connection's open exchanges from its accept to its close, so a\n\t// clean close can find the connections that carry none.\n\t// Node never closes a queued (pipelined) response whose connection ended, so the socket's close\n\t// settles each exchange that still has no socket assigned; an active response settles from its own close.\n\t#trackConnection(socket: Socket): void {\n\t\tconst open = new Map<ServerResponse, () => void>()\n\t\tthis.#exchanges.set(socket, open)\n\t\tsocket.once('close', () => {\n\t\t\tfor (const [response, release] of open) if (response.socket === null) release()\n\t\t\tthis.#exchanges.delete(socket)\n\t\t})\n\t}\n\n\t// Count one exchange open on its connection until both its request message\n\t// and its response have closed; a count, not a flag, because a pipelining\n\t// client holds several at once. Each closes after it ends or is destroyed,\n\t// so one `close` listener apiece covers both paths and leaves when it fires.\n\t// While a clean close waits, the connection ends as its count returns to\n\t// zero. Node's `requestTimeout` bounds an upload that keeps sending after\n\t// its response unless `timeouts.request` is 0; then only the stop's\n\t// deadline does.\n\tasync #trackExchange(\n\t\tmessage: IncomingMessage,\n\t\tresponse: ServerResponse,\n\t\trelease: () => void,\n\t): Promise<void> {\n\t\tconst socket = message.socket\n\t\tconst open = this.#exchanges.get(socket)\n\t\tif (open === undefined) return\n\t\topen.set(response, release)\n\t\tawait Promise.all([\n\t\t\tnew Promise((resolve) => message.once('close', resolve)),\n\t\t\tnew Promise((resolve) => response.once('close', resolve)),\n\t\t])\n\t\topen.delete(response)\n\t\tif (open.size === 0 && this.#exchanges.get(socket) === open && this.#closed) socket.destroy()\n\t}\n\n\t// The listener has closed while the server stops, so the drain has settled\n\t// and no further request or upgrade is counted work. Derived, so it cannot\n\t// drift from the status and the listener it reads.\n\tget #closed(): boolean {\n\t\treturn this.#status === 'stopping' && this.#http?.listening === false\n\t}\n\n\t// Everything `stop()` has to drain: in-flight requests plus the upgraded\n\t// sockets handlers claimed. Derived, so the two counters can never drift\n\t// out of step with a third stored flag.\n\tget #inflight(): number {\n\t\treturn this.#requests.size + this.#upgraded.size\n\t}\n\n\t// Arm a fresh drain wakeup when the server goes from settled to busy.\n\t// Called before the new unit is counted, so a zero here means nothing was\n\t// in flight yet. The invariant this pair holds — `#wakeup` is un-aborted\n\t// whenever `#inflight` is positive — is what lets `#drainPending` park on\n\t// it without racing a wakeup that already fired.\n\t#enter(): void {\n\t\tif (this.#inflight === 0) this.#wakeup = createAbort()\n\t}\n\n\t// Fire the current drain wakeup after the last unit of drainable work has\n\t// left. Called after that unit is uncounted — event-driven, never a\n\t// busy-loop.\n\t#settle(): void {\n\t\tif (this.#inflight === 0) this.#wakeup.abort()\n\t}\n\n\t// Register one in-flight exchange's abort handle; returns the idempotent\n\t// removal its response's `close` runs.\n\t#register(exchange: AbortController): () => void {\n\t\tthis.#enter()\n\t\tthis.#requests.add(exchange)\n\t\treturn () => {\n\t\t\tif (this.#requests.delete(exchange)) this.#settle()\n\t\t}\n\t}\n\n\t// Track one claimed upgraded socket for the duration of its life. The\n\t// claiming handler still owns the socket — this only watches it, so the\n\t// stop path can drain it like a request and cut it if the deadline wins.\n\t// An already-dead socket never enters (nothing would ever untrack it).\n\t#trackSocket(socket: Duplex): void {\n\t\tif (socket.destroyed || this.#upgraded.has(socket)) return\n\t\tthis.#enter()\n\t\tthis.#upgraded.add(socket)\n\t\tsocket.once('close', () => {\n\t\t\tthis.#upgraded.delete(socket)\n\t\t\tthis.#settle()\n\t\t})\n\t}\n\n\t// Park until every in-flight request and claimed upgraded socket is gone\n\t// OR `signal` fires — event-driven (wake-park), no polling.\n\tasync #drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#inflight === 0 || signal.aborted) return\n\t\tawait once(AbortSignal.any([signal, this.#wakeup.signal]), 'abort')\n\t}\n}\n","import type { KeyObject } from 'node:crypto'\nimport type { SignerInterface, TokenSecret } from './types.js'\nimport { createHmac, createSecretKey, timingSafeEqual } from 'node:crypto'\nimport { decodeBase64URL, encodeBase64URL } from '@orkestrel/codec'\nimport { normalizeSecret } from './helpers.js'\n\n/**\n * Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at\n * construction and reuses it on every call. Implements exactly {@link SignerInterface}.\n *\n * @remarks\n * The constructor normalizes the secret through {@link normalizeSecret}, so it\n * throws a {@link ServerError} of code `'SECRET'` for a secret that is not a\n * string or a list of strings, an empty list, or a list holding a blank entry.\n * `verify` compares signature bytes only through `timingSafeEqual`, after a\n * length check.\n *\n * @example\n * ```ts\n * import { Signer } from '@orkestrel/server'\n *\n * const signer = new Signer(['current-secret', 'previous-secret'])\n * await signer.verify('payload', await signer.sign('payload')) // true\n * ```\n */\nexport class Signer implements SignerInterface {\n\treadonly #keys: readonly [KeyObject, ...KeyObject[]]\n\n\tconstructor(secret: TokenSecret) {\n\t\tconst [current, ...older] = normalizeSecret(secret)\n\t\tthis.#keys = [\n\t\t\tcreateSecretKey(current, 'utf8'),\n\t\t\t...older.map((entry) => createSecretKey(entry, 'utf8')),\n\t\t]\n\t}\n\n\tasync sign(message: string): Promise<string> {\n\t\tconst [key] = this.#keys\n\t\treturn encodeBase64URL(createHmac('sha256', key).update(message, 'utf8').digest())\n\t}\n\n\tasync verify(message: string, signature: string): Promise<boolean> {\n\t\tconst bytes = decodeBase64URL(signature)\n\t\t// 32 is the byte length of an HMAC-SHA256; `timingSafeEqual` throws on unequal lengths.\n\t\tif (bytes === undefined || bytes.byteLength !== 32) return false\n\t\treturn this.#keys.some((key) =>\n\t\t\ttimingSafeEqual(createHmac('sha256', key).update(message, 'utf8').digest(), bytes),\n\t\t)\n\t}\n}\n","import type { SSEMessage, SSEStreamInterface, StreamOptions } from './types.js'\nimport { serializeComment, serializeEvent } from './helpers.js'\nimport { SSE_HEADERS } from './constants.js'\n\n/**\n * Represents the Server-Sent-Events handle over an open, fetch-standard streaming\n * `Response`. Implements exactly {@link SSEStreamInterface}.\n *\n * @remarks\n * Builds the `Response` at construction from\n * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`\n * merged over them, at `options.status` (default `200`). A caller repeating one\n * of those keys therefore replaces the seam's value, in any casing. The\n * instance owns the stream's\n * controller, its text encoder, the closed flag, and the parked producer's\n * wakeup, so the whole handle is one entity rather than a closure over four\n * bindings.\n *\n * The stream opens with one comment line ({@link serializeComment}), so the\n * response pump has a first chunk and the headers leave before any event.\n * `write` serializes one message ({@link serializeEvent}), enqueues it, and\n * returns whether the controller still has positive desired size; on an open\n * stream it throws the `ServerError` `serializeEvent` raises for a refused\n * field and enqueues nothing. A producer\n * receiving `false` awaits `drain()`; that promise resolves on the next\n * consumer pull restoring capacity, or on stream closure. `comment` writes a\n * `: text` keep-alive line per line of its text, which a conforming SSE parser\n * ignores; `end` closes the stream. Every method is a safe no-op while `closed`\n * (ended by `end()`, or the consumer cancelled the stream), so a late write\n * never throws.\n *\n * The readiness signal reflects only the process-local `ReadableStream`\n * queue — it is not proof that a remote peer consumed bytes. When the response\n * pump honors its socket sink's drain state, socket pressure stops body pulls\n * and therefore keeps this queue full, letting a cooperative producer bound\n * its buffering. Ignoring the return value preserves an unconditional-enqueue\n * producer. The default stream strategy counts chunks rather than their byte\n * length, so a byte-bounded producer must also cap each message. Return\n * `response` before awaiting a `false` write or `drain()`, because the consumer\n * cannot pull until it receives the response, and the opening comment fills\n * the queue, so a `drain()` before any write also waits on that pull.\n *\n * @example\n * ```ts\n * import { Stream } from '@src/server'\n *\n * const stream = new Stream()\n * void Promise.resolve().then(async () => {\n * \tif (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()\n * \tstream.comment('keep-alive')\n * \tstream.end()\n * })\n * // return stream.response from the route handler\n * ```\n */\nexport class Stream implements SSEStreamInterface {\n\treadonly #encoder = new TextEncoder()\n\treadonly #response: Response\n\t#controller: ReadableStreamDefaultController<Uint8Array> | undefined\n\t#closed = false\n\t#wakeup: PromiseWithResolvers<void> | undefined\n\n\tconstructor(options?: StreamOptions) {\n\t\t// The underlying source is a table of bound methods rather than inline\n\t\t// callbacks: every branch it names reaches `#` state, and instance-bound\n\t\t// work belongs in a method rather than in a function nested here.\n\t\tconst body = new ReadableStream<Uint8Array>({\n\t\t\tstart: this.#attach.bind(this),\n\t\t\tpull: this.#pull.bind(this),\n\t\t\tcancel: this.#cancel.bind(this),\n\t\t})\n\t\t// `Headers.set` matches a field name case-insensitively and replaces every\n\t\t// existing value, so any spelling of a seam-owned key wins. An object\n\t\t// spread would resolve the collision case-sensitively and leave `Headers`\n\t\t// to append the re-cased spelling into one comma-joined value.\n\t\tconst headers = new Headers(SSE_HEADERS)\n\t\tfor (const [name, value] of Object.entries(options?.headers ?? {})) headers.set(name, value)\n\t\tthis.#response = new Response(body, { status: options?.status ?? 200, headers })\n\t}\n\n\tget response(): Response {\n\t\treturn this.#response\n\t}\n\n\tget closed(): boolean {\n\t\treturn this.#closed\n\t}\n\n\twrite(message: SSEMessage): boolean {\n\t\tif (this.#closed || this.#controller === undefined) return false\n\t\tthis.#enqueue(serializeEvent(message))\n\t\treturn this.#controller.desiredSize !== null && this.#controller.desiredSize > 0\n\t}\n\n\tcomment(text: string): void {\n\t\tthis.#enqueue(serializeComment(text))\n\t}\n\n\tdrain(): Promise<void> {\n\t\tconst desired = this.#controller?.desiredSize\n\t\tif (this.#closed || (desired !== undefined && desired !== null && desired > 0)) {\n\t\t\treturn Promise.resolve()\n\t\t}\n\t\tthis.#wakeup ??= Promise.withResolvers<void>()\n\t\treturn this.#wakeup.promise\n\t}\n\n\tend(): void {\n\t\tif (this.#closed) return\n\t\tthis.#closed = true\n\t\tthis.#controller?.close()\n\t\tthis.#settle()\n\t}\n\n\t// The stream hands its controller over at start; every write path reads it\n\t// and treats an absent one as \"not yet writable\".\n\t#attach(controller: ReadableStreamDefaultController<Uint8Array>): void {\n\t\tthis.#controller = controller\n\t\t// The opening comment is the pump's first chunk, so the headers leave before any event.\n\t\tcontroller.enqueue(this.#encoder.encode(serializeComment('')))\n\t}\n\n\t// A pull that restored positive desired size is the wakeup a parked\n\t// producer is waiting on; a pull that did not restore it changes nothing.\n\t#pull(controller: ReadableStreamDefaultController<Uint8Array>): void {\n\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) return\n\t\tthis.#settle()\n\t}\n\n\t// The consumer cancelled the stream: the handle is closed from the far end,\n\t// so a parked producer settles rather than waiting for a pull that cannot come.\n\t#cancel(): void {\n\t\tthis.#closed = true\n\t\tthis.#settle()\n\t}\n\n\t// Encode and enqueue one wire fragment, ignoring a closed or unstarted stream.\n\t#enqueue(text: string): void {\n\t\tif (this.#closed || this.#controller === undefined) return\n\t\tthis.#controller.enqueue(this.#encoder.encode(text))\n\t}\n\n\t// Release a parked producer and drop the spent wakeup, so the next park\n\t// allocates a fresh one.\n\t#settle(): void {\n\t\tthis.#wakeup?.resolve()\n\t\tthis.#wakeup = undefined\n\t}\n}\n","import type {\n\tNegotiatorInterface,\n\tServerInterface,\n\tServerOptions,\n\tSignerInterface,\n\tSSEStreamInterface,\n\tStreamOptions,\n\tTokenSecret,\n} from './types.js'\nimport { Negotiator } from './Negotiator.js'\nimport { Server } from './Server.js'\nimport { Signer } from './Signer.js'\nimport { Stream } from './Stream.js'\n\n/**\n * Creates a {@link NegotiatorInterface} — the reusable content-negotiation\n * machine over the weighted `Accept` family.\n *\n * @returns A {@link NegotiatorInterface}\n *\n * @example\n * ```ts\n * import type { MiddlewareContext } from '@src/server'\n * import { createNegotiator } from '@src/server'\n *\n * declare const context: MiddlewareContext<Record<string, never>>\n *\n * const negotiator = createNegotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'\n * negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'\n * await negotiator.format(new Request('http://x'), context, {\n * \t'application/json': (_request, _context) => Response.json({ ok: true }),\n * })\n * ```\n */\nexport function createNegotiator(): NegotiatorInterface {\n\treturn new Negotiator()\n}\n\n/**\n * Creates a {@link ServerInterface} — the node face's HTTP server facade over\n * a consumed `@orkestrel/router` dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param options - {@link ServerOptions}\n * @returns A {@link ServerInterface}, not yet started\n *\n * @example Quickstart: dispatcher, middleware, lifecycle\n * ```ts\n * import type { MiddlewareHandler } from '@orkestrel/server'\n * import { createServer } from '@orkestrel/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * interface State {\n * \treadonly requestId: string\n * \treadonly ip: string | undefined\n * }\n *\n * const dispatcher = createDispatcher<State>()\n * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })\n *\n * const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Request-ID', context.state.requestId)\n * \treturn response\n * }\n *\n * const server = createServer<State>({\n * \tdispatcher,\n * \tstate: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),\n * })\n * server.use(logRequestId)\n * const port = await server.start()\n * await server.stop()\n * await server.destroy()\n * ```\n */\nexport function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState> {\n\treturn new Server(options)\n}\n\n/**\n * Creates a {@link SignerInterface} that holds one HMAC-SHA256 key per secret, each\n * created at this call.\n *\n * @param secret - A secret, or a `[current, ...older]` rotation list; see {@link TokenSecret}\n * @returns A {@link SignerInterface} whose first key signs and whose every key verifies\n * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of strings,\n * when the list is empty, or when any entry is blank\n *\n * @example\n * ```ts\n * import { createSigner, signToken, verifyToken } from '@orkestrel/server'\n *\n * const signer = createSigner(['current-secret', 'previous-secret'])\n * const token = await signToken('session-7f3a', { signer, ttl: 60_000 })\n * await verifyToken(token, signer) // 'session-7f3a'\n * ```\n */\nexport function createSigner(secret: TokenSecret): SignerInterface {\n\treturn new Signer(secret)\n}\n\n/**\n * Creates an {@link SSEStreamInterface} — a generic Server-Sent-Events stream whose\n * `response` is a fetch-standard streaming `Response` a route returns.\n *\n * @param options - {@link StreamOptions}\n * @returns An {@link SSEStreamInterface} whose stream is open\n *\n * @example\n * ```ts\n * import { createStream } from '@src/server'\n *\n * const stream = createStream()\n * void Promise.resolve().then(async () => {\n * \tif (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()\n * \tstream.comment('keep-alive')\n * \tstream.end()\n * })\n * // return stream.response from the route handler\n * ```\n */\nexport function createStream(options?: StreamOptions): SSEStreamInterface {\n\treturn new Stream(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,mBAAmB;;;;;AAMhC,IAAa,6BAA6B;;;;;;AAO1C,IAAa,6BAA6B;;;;;;;;;;;;;;;AAgB1C,IAAa,mBAAmB,OAAO,IAAI,6BAA6B;;;;;AAMxE,IAAa,qBAAqB;;;;;;;;;;;;;;;;;AAkBlC,IAAa,6BAA6B;;;;;;;;;;;;;AAc1C,IAAa,cAAgD,OAAO,OAAO;CAC1E,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,qBAAqB;AACtB,CAAC;;;;;;;;;;;;AAaD,IAAa,qBAAuC,OAAO,OAAO,wBAAwB;;;;;;;;;;AAW1F,IAAa,sBAAwC,OAAO,OAAO,UAAU;;;;;AAM7E,IAAa,mBAAqC,OAAO,OAAO,YAAY;;;;;;;;;;;;;;AAe5E,IAAa,qBAA0C,OAAO,uBAC7D,IAAI,IAAI;CACP;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC,CACF;;;;;;;;;;;;AAaA,IAAa,oBAAyC,OAAO,OAAO,CAAC,QAAQ,SAAS,CAAC;;AAGvF,IAAa,qBAAqB,OAAO,IAAI,+BAA+B;;AAG5E,IAAa,gCAAgC,OAAO,IAAI,wCAAwC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7HhG,IAAa,YAAb,cAA+B,MAAM;CACpC;CACA;CAGA,YAAY,QAAgB,SAAiB,SAA6C;EACzF,MAAM,OAAO;EACb,OAAO,eAAe,MAAM,kBAAkB,EAAE,OAAO,KAAK,CAAC;EAC7D,KAAK,OAAO;E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AgB,mBAAwC;CACvD,OAAO,IAAI,WAAW;AACvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,aAAa,QAAsC;CAClE,OAAO,IAAI,OAAO,MAAM;AACzB;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,aAAa,SAA6C;CACzE,OAAO,IAAI,OAAO,OAAO;AAC1B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["createNetServer","createHTTPServer"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/Negotiator.ts","../../../src/server/ServerBinding.ts","../../../src/server/Server.ts","../../../src/server/Signer.ts","../../../src/server/Stream.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { Encoding } from './types.js'\n\n// The substrate's tunable defaults — only the constants with a real consumer\n// inside this package: a capability arrives with its first real consumer,\n// never speculatively. Each is frozen or declared\n// readonly, so a consumer reads but never mutates the shared default. The\n// defaults only `@orkestrel/middleware` needs (rate limiting, CSRF, sessions,\n// static serving, multipart) stay out of this file; they belong to that\n// package's own `constants.ts`.\n\n/**\n * Names the default graceful-stop deadline `stop()` gives in-flight requests and\n * claimed upgraded sockets, `10_000` ms.\n */\nexport const DEFAULT_DRAIN_MS = 10_000\n\n/**\n * Names the `node:http` default `requestTimeout`, `300_000` ms, which applies when\n * `timeouts.request` is omitted.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 300_000\n\n/**\n * Names the cap of the `node:http` default `headersTimeout`, `60_000` ms: when\n * `timeouts.headers` is omitted, the header timeout is the lesser of this cap and the\n * request timeout.\n */\nexport const DEFAULT_HEADERS_TIMEOUT_MS = 60_000\n\n/**\n * Names the `Symbol.for`-interned brand `HTTPError` carries,\n * `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across\n * package copies. A consumer never sets it by hand.\n *\n * @remarks\n * The brand exists for the dual-package hazard — a version-skewed or\n * workspace-linked duplicate install — where `instanceof` alone fails because\n * each copy's `HTTPError` constructor is a distinct object.\n * `Symbol.for` interns the symbol on the global symbol registry, so every\n * copy of this package that evaluates this key resolves the same symbol\n * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,\n * unequal symbol per copy and defeat the whole point of a cross-copy brand.\n */\nexport const HTTP_ERROR_BRAND = Symbol.for('@orkestrel/server.HTTPError')\n\n/**\n * Names the default maximum request body size `readBody` accepts before a 413,\n * `1_048_576` bytes.\n */\nexport const DEFAULT_BODY_LIMIT = 1_048_576\n\n/**\n * Names the default maximum decompressed request body size, `16_777_216` bytes — the\n * zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when\n * it transparently decompresses a `Content-Encoding` request body.\n *\n * @remarks\n * A small compressed body (under {@link DEFAULT_BODY_LIMIT} on the wire)\n * can inflate by many orders of magnitude — a classic decompression bomb.\n * Capping the decompressed byte count makes the pipe abort the moment the\n * output would exceed this, before the full bomb is materialized, so the\n * inflation can never exhaust memory. Defaults to `16 MiB` — a generous\n * ceiling for a legitimate compressed JSON / form body, far below an OOM. A\n * consumer raises it through {@link import('./types.js').BodyOptions}\n * `decompression` for a workload that genuinely ships larger decompressed\n * bodies.\n */\nexport const DEFAULT_DECOMPRESSED_LIMIT = 16_777_216\n\n/**\n * Holds the SSE response headers a `Stream` sets on its response, merged under any\n * caller `headers` so a caller repeating one of these keys replaces its value.\n *\n * @remarks\n * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`\n * keeps a proxy from caching the stream; `keep-alive` holds the connection\n * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so\n * events flush promptly rather than batching. Frozen so a consumer can read\n * but never mutate the shared default; the merged keys are\n * {@link import('./types.js').StreamOptions.headers}.\n */\nexport const SSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n\t'Content-Type': 'text/event-stream; charset=utf-8',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n\t'X-Accel-Buffering': 'no',\n})\n\n/**\n * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`\n * to match, `^[A-Za-z0-9_-]{1,200}$`.\n *\n * @remarks\n * An incoming id carrying CRLF, log-injection input, a control character,\n * or more characters than the pattern admits fails the match and is rejected —\n * a fresh id is minted instead — so it never rides into a response header or\n * `context.state`. Frozen so a consumer can read but never mutate the shared\n * default.\n */\nexport const REQUEST_ID_PATTERN: Readonly<RegExp> = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/)\n\n/**\n * Defines the `1*DIGIT` form `parseRange` requires of a `Range` bound, `^[0-9]+$`.\n *\n * @remarks\n * Mirrors the `first-pos`, `last-pos`, and `suffix-length` rules of RFC 9110\n * § 14.1.1. A numeral `Number` reads but the grammar refuses — a hexadecimal,\n * octal, or binary prefix, an exponent, a sign, or a decimal point — fails the\n * match, as does a digit outside ASCII, which `Number` reads as `NaN`.\n */\nexport const RANGE_BOUND_PATTERN: Readonly<RegExp> = Object.freeze(/^[0-9]+$/)\n\n/**\n * Defines the line terminators of the SSE wire, `\\r\\n`, `\\r`, and `\\n`, which\n * `serializeEvent` and `serializeComment` split text on.\n */\nexport const SSE_LINE_PATTERN: Readonly<RegExp> = Object.freeze(/\\r\\n|\\r|\\n/)\n\n/**\n * Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,\n * beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that\n * helper also applies.\n *\n * @remarks\n * The text-shaped application types worth compressing (JSON / JavaScript /\n * XML / SVG / WASM / a few document formats) — never already-compressed\n * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's\n * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`\n * withholds `add` / `delete` / `clear` from the shared default, so a consumer\n * reads it without reaching a mutator.\n */\nexport const COMPRESSIBLE_TYPES: ReadonlySet<string> = Object.freeze(\n\tnew Set([\n\t\t'application/json',\n\t\t'application/javascript',\n\t\t'application/xml',\n\t\t'application/xhtml+xml',\n\t\t'application/rss+xml',\n\t\t'application/atom+xml',\n\t\t'application/ld+json',\n\t\t'application/manifest+json',\n\t\t'application/vnd.api+json',\n\t\t'application/wasm',\n\t\t'image/svg+xml',\n\t\t'application/pdf',\n\t]),\n)\n\n/**\n * Lists the default {@link Encoding} content-codings the substrate offers, in\n * preference order — `gzip` then `deflate`.\n *\n * @remarks\n * `identity` (no compression) is always implicitly acceptable and is not\n * listed here — it is the fall-through when a client accepts none of these.\n * Brotli is omitted per the core's `CompressionStream`-only decision (see\n * {@link Encoding}). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const DEFAULT_ENCODINGS: readonly Encoding[] = Object.freeze(['gzip', 'deflate'])\n\n/** Names the identity brand carried by lifecycle errors across package copies. */\nexport const SERVER_ERROR_BRAND = Symbol.for('@orkestrel/server.ServerError')\n\n/** Names the identity brand carried by body-limit errors across package copies. */\nexport const CONTENT_TOO_LARGE_ERROR_BRAND = Symbol.for('@orkestrel/server.ContentTooLargeError')\n","import type { ServerErrorCode } from './types.js'\nimport {\n\tholds,\n\tINTRINSICS,\n\tisFunction,\n\tisInstance,\n\tisNumber,\n\tisObject,\n\tisString,\n} from '@orkestrel/contract'\nimport { CONTENT_TOO_LARGE_ERROR_BRAND, HTTP_ERROR_BRAND, SERVER_ERROR_BRAND } from './constants.js'\n\n/**\n * Represents an error a handler (or middleware) throws to produce an HTTP response of a\n * specific status.\n *\n * @remarks\n * Carries the HTTP `status` to send and an optional `context` record (the\n * offending field / value). The server's built-in error boundary catches it\n * and renders a response of `status` with the error's `message` as the body,\n * and no body for 204, 205, and 304 — so an `HTTPError`'s message is always\n * client-facing (it is the handler's deliberate signal), unlike a generic\n * throw whose message is hidden unless `expose` is set. A `status` the\n * `Response` constructor refuses, an integer below 200 or above 599 or a\n * status that is not an integer, renders `500` instead. Subclass it (as {@link ContentTooLargeError} does) for\n * specific statuses, or throw it directly. Narrow a caught value with\n * {@link isHTTPError}. The machine-readable discriminator is `status`; there is\n * no separate `code`.\n *\n * @example\n * ```ts\n * import { HTTPError } from '@src/server'\n *\n * const handler = async (request: Request): Promise<Response> => {\n * \tconst user = await find(new URL(request.url).searchParams.get('id'))\n * \tif (user === undefined) throw new HTTPError(404, 'user not found')\n * \treturn Response.json(user)\n * }\n * ```\n */\nexport class HTTPError extends Error {\n\treadonly status: number\n\treadonly context?: Readonly<Record<string, unknown>>\n\tdeclare readonly [HTTP_ERROR_BRAND]: this\n\n\tconstructor(status: number, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tObject.defineProperty(this, HTTP_ERROR_BRAND, { value: this })\n\t\tthis.name = 'HTTPError'\n\t\tthis.status = status\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Represents the {@link HTTPError} thrown when a request body exceeds the body\n * pipeline's size limit — a `413 Content Too Large`.\n *\n * @remarks\n * Thrown by `readBody` (and the middleware context's cached `body()`) when\n * the received bytes exceed the configured {@link\n * import('./types.js').BodyOptions.limit}, carrying the `limit` in its\n * `context`. The server's error boundary renders it as a 413.\n *\n * @example\n * ```ts\n * import { ContentTooLargeError, isHTTPError } from '@src/server'\n *\n * try {\n * \tawait readBody(request, { limit: 1024 })\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status) // 413\n * }\n * ```\n */\nexport class ContentTooLargeError extends HTTPError {\n\tconstructor(limit: number) {\n\t\tsuper(413, `request body exceeds the ${limit}-byte limit`, { limit })\n\t\tObject.defineProperty(this, CONTENT_TOO_LARGE_ERROR_BRAND, { value: this })\n\t\tthis.name = 'ContentTooLargeError'\n\t}\n}\n\n/**\n * Narrows an unknown caught value to an {@link HTTPError}, including a subclass such\n * as {@link ContentTooLargeError}, and recognizes an instance from another copy of\n * this package through its own identity brand.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is an {@link HTTPError}; false otherwise\n *\n * @remarks\n * Requires a global Error instance with a derived prototype, its own identity brand,\n * a numeric status, a string message, and an absent or object-valued context.\n * Callable contexts are accepted. Subclass names are unrestricted.\n * Transparent proxies and branded plain objects are rejected.\n *\n * @example\n * ```ts\n * import { isHTTPError } from '@src/server'\n *\n * try {\n * \tawait handle(request)\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status, error.message)\n * }\n * ```\n */\nexport function isHTTPError(value: unknown): value is HTTPError {\n\treturn holds(() => {\n\t\tif (!isInstance(value, Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tif (!INTRINSICS.own(value, HTTP_ERROR_BRAND)) return false\n\t\tif (INTRINSICS.describe(value, HTTP_ERROR_BRAND)?.value !== value) return false\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\tisNumber(INTRINSICS.reflect.read(value, 'status')) &&\n\t\t\tisString(INTRINSICS.reflect.read(value, 'message')) &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n\n/**\n * Recognizes a branded body-limit error, including subclasses and other package copies.\n *\n * @example\n * ```ts\n * isContentTooLargeError(new ContentTooLargeError(1024)) // true\n * ```\n */\nexport function isContentTooLargeError(value: unknown): value is ContentTooLargeError {\n\treturn holds(\n\t\t() =>\n\t\t\tisHTTPError(value) &&\n\t\t\tINTRINSICS.own(value, CONTENT_TOO_LARGE_ERROR_BRAND) &&\n\t\t\tINTRINSICS.describe(value, CONTENT_TOO_LARGE_ERROR_BRAND)?.value === value,\n\t)\n}\n\n/**\n * Represents the error this package raises when a caller programmed a call the\n * entity refuses, carrying `'STATUS'`, `'NEXT'`, `'EVENT'`, or `'SECRET'` as its code.\n *\n * @remarks\n * Carries a machine-readable {@link ServerErrorCode} and an optional `context`\n * record naming the offending facts. This is a programmer error, so it carries\n * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that\n * invoked the lifecycle method, a `'NEXT'` refusal of a second `next` call or\n * of a `next` call with an argument escapes its\n * middleware into the request boundary, which reaches it as a generic 500 with\n * the message hidden unless `expose` is set, and an `'EVENT'` refusal is raised\n * to the caller that serialized an SSE message, its `context.field` naming the\n * refused field, and a `'SECRET'` refusal is raised to the caller that built a\n * signer from a malformed secret, its `context` naming the refused positions,\n * or the received type for a value that is not a string or a readable list, and holding\n * no secret text. Throw an {@link HTTPError} for a\n * client-facing fault instead. Narrow a caught value with\n * {@link isServerError}.\n *\n * @example\n * ```ts\n * import { ServerError } from '@src/server'\n *\n * const error = new ServerError('STATUS', \"server cannot start from 'listening'\", {\n * \tstatus: 'listening',\n * })\n * error.code // 'STATUS'\n * ```\n */\nexport class ServerError extends Error {\n\treadonly code: ServerErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(code: ServerErrorCode, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tObject.defineProperty(this, SERVER_ERROR_BRAND, { value: this })\n\t\tthis.name = 'ServerError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal\n * of a call the caller programmed.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link ServerError}; false otherwise\n *\n * @remarks\n * Requires the own identity brand, a declared code, a string message, and an absent\n * or object-valued context on a global Error with a derived prototype.\n * Callable contexts and subclasses are accepted; transparent proxies are rejected.\n *\n * @example\n * ```ts\n * import { createServer, isServerError } from '@src/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })\n * await server.start()\n * try {\n * \tawait server.start()\n * } catch (error) {\n * \tif (isServerError(error)) console.log(error.code) // 'STATUS'\n * }\n * await server.stop()\n * ```\n */\nexport function isServerError(value: unknown): value is ServerError {\n\treturn holds(() => {\n\t\tif (!isInstance(value, Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tif (!INTRINSICS.own(value, SERVER_ERROR_BRAND)) return false\n\t\tif (INTRINSICS.describe(value, SERVER_ERROR_BRAND)?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\t(code === 'STATUS' || code === 'NEXT' || code === 'EVENT' || code === 'SECRET') &&\n\t\t\tisString(INTRINSICS.reflect.read(value, 'message')) &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n","import type { AddressInfo } from 'node:net'\nimport { isNumber, isRecord, isString } from '@orkestrel/contract'\n\n// The module's guards. A total `Guard<T>` narrows a type rather than answering\n// a plain question, so it lives here rather than beside the boolean predicates\n// `helpers.ts` keeps (`isCookieName`, `isCompressibleType`, `isValidRequestId`).\n// This file sits at the bottom of the module's graph beside `helpers.ts`,\n// imports the `node:net` address type and the `@orkestrel/contract` guards, and\n// never an implementation class.\n\n/**\n * Checks whether a `node:net` `server.address()` return is the structured\n * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`\n * or `null` — the total, never-throwing narrow `discoverPort`\n * and the `Server`'s own port resolution read the bound port through.\n *\n * @remarks\n * Checks the `address`, `family`, and `port` members `node:net` declares as\n * `string`, `string`, and `number`.\n *\n * @param value - The `server.address()` return (`AddressInfo | string | null`)\n * @returns True if `value` is an `AddressInfo`; false otherwise\n *\n * @example\n * ```ts\n * import { isAddressInfo } from '@src/server'\n *\n * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true\n * isAddressInfo(null) // false\n * ```\n */\nexport function isAddressInfo(value: unknown): value is AddressInfo {\n\treturn (\n\t\tisRecord(value) && isString(value.address) && isString(value.family) && isNumber(value.port)\n\t)\n}\n","import type {\n\tAcceptEntry,\n\tBodyOptions,\n\tCookieOptions,\n\tEncoding,\n\tMediaMatch,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tRangeSpec,\n\tSignerInterface,\n\tSSEMessage,\n\tTokenOptions,\n\tTokenSecret,\n} from './types.js'\nimport { addAbortListener, once } from 'node:events'\nimport { createServer as createNetServer } from 'node:net'\nimport { decodeBase64URL, encodeBase64URL, encodeHex } from '@orkestrel/codec'\nimport {\n\tattempt,\n\tholds,\n\tisArray,\n\tisCodedError,\n\tisError,\n\tisFiniteNumber,\n\tisInstance,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisSafeInteger,\n\tisString,\n\tparseJSON,\n\tsettle,\n} from '@orkestrel/contract'\nimport {\n\tCOMPRESSIBLE_TYPES,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DECOMPRESSED_LIMIT,\n\tRANGE_BOUND_PATTERN,\n\tREQUEST_ID_PATTERN,\n\tSSE_LINE_PATTERN,\n} from './constants.js'\nimport { ContentTooLargeError, HTTPError, isHTTPError, ServerError } from './errors.js'\nimport { isAddressInfo } from './validators.js'\n\n// The middleware seam's composition engine — a pure function, not a class:\n// `compose` has no instance state, so it lives here rather than as an entity.\n// The returning onion: each middleware may transform the response (`await\n// next()` then mutate the result) or short-circuit (return without calling\n// `next`). Every layer and the terminal receive the same request and context.\n\n/**\n * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`\n * handler into one request handler — the middleware seam.\n *\n * @remarks\n * `middleware[0]` runs outermost: it is invoked first, and its call to `next`\n * runs `middleware[1]`, and so on until the last middleware's `next` invokes\n * `terminal`. Every layer and `terminal` receive the same `Request` and the same\n * context object. A middleware's `next` is called with no argument, or not\n * called at all (a short-circuit — the middleware's own returned `Response` is\n * sent, and everything downstream never runs). A second call to the same\n * `next` within one middleware invocation, or a call that passes an argument,\n * rejects with a `ServerError` of code `'NEXT'` — each link runs the chain at\n * most once, so a middleware cannot fork the request into two divergent\n * downstream runs. Each `next` resolves the downstream response through\n * {@link normalizeResponse}, so a layer can set headers on a redirect or a\n * `fetch` result; each run keeps its own memo of checked responses, which ends\n * with the run. `compose` copies `middleware` when called, so a layer added to\n * the array later never runs in the returned handler.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param middleware - The ordered chain, outermost first\n * @param terminal - The innermost handler the chain ultimately reaches\n * @returns A single `(request, context) => Promise<Response>` handler running the whole onion\n *\n * @example\n * ```ts\n * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Powered-By', 'orkestrel')\n * \treturn response\n * }\n *\n * const handle = compose([withHeader], async () => new Response('ok'))\n * ```\n */\nexport function compose<TState>(\n\tmiddleware: ReadonlyArray<MiddlewareHandler<TState>>,\n\tterminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\tconst layers = [...middleware]\n\treturn (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tconst known = new Map<Response, Response>()\n\t\treturn layers.reduceRight<\n\t\t\t(request: Request, context: MiddlewareContext<TState>) => Promise<Response>\n\t\t>((next, layer) => wrapMiddleware(layer, next, known), terminal)(request, context)\n\t}\n}\n\n/**\n * Wraps one middleware layer around its downstream handler, enforcing the one-call\n * `next` invariant.\n *\n * @remarks\n * The returned handler enforces the one-call, no-argument `next` invariant: every\n * call, refused or not, spends the layer's one call, so a call after a refused\n * `next(request)` rejects too. It hands `next` the same request and context, and\n * keeps the middleware's synchronous or asynchronous result.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param layer - The middleware layer to invoke\n * @param next - The downstream handler wrapped by `layer`\n * @param known - The {@link normalizeResponse} memo of one composed run, shared by its\n * layers; Default: a fresh `Map` per call of the returned handler\n * @returns A handler with `layer` composed around `next`\n *\n * @example\n * ```ts\n * const handle = wrapMiddleware(\n * \tasync (_request, _context, next) => next(),\n * \tasync () => new Response('ok'),\n * )\n * ```\n */\nexport function wrapMiddleware<TState>(\n\tlayer: MiddlewareHandler<TState>,\n\tnext: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n\tknown?: Map<Response, Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn async (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tconst memo = known ?? new Map<Response, Response>()\n\t\tconst calls = [next].values()\n\t\treturn Promise.resolve(\n\t\t\tlayer(request, context, (...args: readonly unknown[]): Promise<Response> => {\n\t\t\t\tconst invocation = calls.next()\n\t\t\t\tif (invocation.done)\n\t\t\t\t\treturn Promise.reject(\n\t\t\t\t\t\tnew ServerError('NEXT', 'next() was already called by this middleware'),\n\t\t\t\t\t)\n\t\t\t\tif (args.length > 0)\n\t\t\t\t\treturn Promise.reject(\n\t\t\t\t\t\tnew ServerError('NEXT', 'next() takes no argument; every layer reads one request'),\n\t\t\t\t\t)\n\t\t\t\treturn invocation\n\t\t\t\t\t.value(request, context)\n\t\t\t\t\t.then((response) => normalizeResponse(response, memo))\n\t\t\t}),\n\t\t)\n\t}\n}\n\n/**\n * Returns a response whose headers a middleware can set: a copy of `response` when its headers are\n * immutable and its status lies from 200 through 599, and `response` itself otherwise.\n *\n * @remarks\n * A `Response.redirect` result and a `fetch` result carry immutable headers, so `headers.set`\n * throws on them. The copy keeps the body, the status, the status text, and every header; it\n * drops the fields a constructed `Response` cannot carry, such as `url` and `redirected`. A\n * response whose status lies outside 200 through 599, such as `Response.error()`, passes through\n * unchanged. `known` maps each response already checked to its answer, and the copy to itself, so\n * a response that crosses several layers of one composed run is checked once.\n *\n * @param response - The response a downstream handler resolved\n * @param known - The memo of one composed run; Default: a fresh `Map`\n * @returns `response` itself, or its mutable copy\n *\n * @example\n * ```ts\n * const response = normalizeResponse(Response.redirect('http://localhost/next', 302))\n * response.headers.set('X-Request-ID', 'abc') // no throw\n * ```\n */\nexport function normalizeResponse(\n\tresponse: Response,\n\tknown: Map<Response, Response> = new Map(),\n): Response {\n\tconst remembered = known.get(response)\n\tif (remembered !== undefined) return remembered\n\tconst normal =\n\t\tresponse.status < 200 || response.status > 599 || supportsMutation(response.headers)\n\t\t\t? response\n\t\t\t: new Response(response.body, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\theaders: new Headers(response.headers),\n\t\t\t\t})\n\tknown.set(response, normal)\n\tif (normal !== response) known.set(normal, normal)\n\treturn normal\n}\n\n/**\n * Checks whether a `Headers` object accepts changes, leaving its entries as they were.\n *\n * @remarks\n * Fetch refuses `delete` on immutable headers before it looks the name up, so deleting a name\n * the headers lack answers the question and changes nothing. When the probe name is present, the\n * check sets it to its own combined value instead.\n *\n * @param headers - The headers to check\n * @returns True if `headers` accepts changes; false otherwise\n *\n * @example\n * ```ts\n * supportsMutation(new Headers()) // true\n * supportsMutation(Response.redirect('http://localhost/', 302).headers) // false\n * ```\n */\nexport function supportsMutation(headers: Headers): boolean {\n\tconst name = 'x-orkestrel-probe'\n\tconst value = headers.get(name)\n\treturn holds(() => {\n\t\tif (value === null) headers.delete(name)\n\t\telse headers.set(name, value)\n\t\treturn true\n\t})\n}\n\n// The cookie machinery (module-scope helpers) — `parseCookies`\n// decodes a raw `Cookie:` header into a name→value lookup; `serializeCookie`\n// builds a spec-shaped `Set-Cookie` value with its attributes. The signed\n// pair reuses the shipped HMAC token primitives rather than a second HMAC\n// scheme: `writeSignedCookie` is `serializeCookie(name, await signToken(value,\n// { signer }))` appended to a `Headers`, and `readSignedCookie` is `await\n// verifyToken(parseCookies(...)[name], signer)` — so a cookie is a\n// `signToken` value in a `Set-Cookie`, with the same key rotation and tamper\n// rejection. Every reader narrows untrusted request input with `typeof`,\n// never `as`, and remains total on malformed input.\n\n/**\n * Parses a raw `Cookie:` request header into a `name → value` lookup.\n *\n * @remarks\n * Splits on `;`; the first segment keeps any leading whitespace (a genuine\n * cookie-pair separator never precedes it), while every later segment has its\n * inter-pair separator (ASCII space/tab) stripped before parsing — so a\n * whitespace-padded name (`' __Host-x=evil'`) is rejected by\n * {@link isCookieName} rather than silently reconciling into a\n * prefix-protected `__Host-` name. A pair without `=`, or with an invalid\n * name, is skipped; a later duplicate name wins. Total — an absent/empty/\n * malformed header yields an empty record, never throws.\n *\n * The record has a null prototype, so a name that `Object.prototype` carries\n * (`constructor`, `toString`, `__proto__`) reads as an ordinary cookie when\n * present and as `undefined` when absent.\n *\n * @param header - The raw `Cookie` header value (possibly `undefined`)\n * @returns A null-prototype record of every parsed cookie, `name → decoded value`\n *\n * @example\n * ```ts\n * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }\n * ```\n */\nexport function parseCookies(header: string | undefined): Record<string, string> {\n\tconst pairs = (header ?? '')\n\t\t.split(';')\n\t\t.flatMap((raw, index): ReadonlyArray<readonly [string, string]> => {\n\t\t\tconst segment = index === 0 ? raw : raw.replace(/^[ \\t]+/, '')\n\t\t\tconst eq = segment.indexOf('=')\n\t\t\tif (eq < 0) return []\n\t\t\tconst name = segment.slice(0, eq)\n\t\t\treturn isCookieName(name) ? [[name, decodeCookieValue(segment.slice(eq + 1).trim())]] : []\n\t\t})\n\tconst cookies = Object.fromEntries(pairs)\n\tObject.setPrototypeOf(cookies, null)\n\treturn cookies\n}\n\n/**\n * Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of\n * cookie-token characters with no surrounding or interior whitespace.\n *\n * @remarks\n * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$` —\n * which excludes every whitespace char (ASCII and Unicode) plus controls,\n * separators, and `=`. The {@link parseCookies} hardening that stops a\n * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.\n *\n * @param value - The candidate cookie name\n * @returns True if `value` is a valid, whitespace-free cookie token; false otherwise\n *\n * @example\n * ```ts\n * isCookieName('__Host-session') // true\n * isCookieName(' __Host-session') // false — whitespace-padded\n * ```\n */\nexport function isCookieName(value: string): boolean {\n\treturn /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/.test(value)\n}\n\n/**\n * Decodes a cookie value with `decodeURIComponent`, falling back to the raw\n * text when the value is not valid percent-encoding.\n *\n * @param raw - The raw (trimmed) cookie value\n * @returns The URL-decoded value, or the raw value when decoding would throw\n *\n * @example\n * ```ts\n * decodeCookieValue('a%20b') // 'a b'\n * decodeCookieValue('%') // '%' — malformed escape stays literal\n * ```\n */\nexport function decodeCookieValue(raw: string): string {\n\ttry {\n\t\treturn decodeURIComponent(raw)\n\t} catch {\n\t\treturn raw\n\t}\n}\n\n/**\n * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —\n * the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it\n * emits them.\n *\n * @remarks\n * Rejects a value carrying a `;` (splits attributes), a `,` (can split a\n * folded header), ASCII/Unicode whitespace, or a C0/DEL control char\n * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`\n * directive. Total — never throws (a bad value returns `false`).\n *\n * @param value - The candidate attribute value (a `Domain` or `Path`)\n * @returns True if `value` carries no separator / whitespace / control char; false otherwise\n *\n * @example\n * ```ts\n * isCookieAttribute('/app') // true\n * isCookieAttribute('/a\\r\\nSet-Cookie: x=y') // false\n * ```\n */\nexport function isCookieAttribute(value: string): boolean {\n\tfor (const char of value) {\n\t\tif (char === ';' || char === ',' || /\\s/.test(char)) return false\n\t\tconst code = char.codePointAt(0)\n\t\tif (code !== undefined && (code < 0x20 || code === 0x7f)) return false\n\t}\n\treturn true\n}\n\n/**\n * Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.\n *\n * @remarks\n * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and\n * appends the present {@link CookieOptions} attributes in canonical order:\n * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`\n * (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated\n * with {@link isCookieAttribute} and throw an {@link HTTPError} on an\n * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of\n * the `secure` option (the spec requires it); an un-resolved `undefined`\n * `secure` here falls to off — request-aware callers resolve it first through\n * {@link resolveSecure}.\n *\n * @param name - The cookie name\n * @param value - The cookie value (URL-encoded into the output)\n * @param options - The {@link CookieOptions} attributes; see its fields for defaults\n * @returns The `Set-Cookie` header value\n * @throws {HTTPError} When `domain` or `path` carries an injection char\n *\n * @example\n * ```ts\n * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'\n * ```\n */\nexport function serializeCookie(name: string, value: string, options?: CookieOptions): string {\n\tconst sameSite = options?.sameSite ?? 'Lax'\n\tconst domain = options?.domain\n\tif (domain !== undefined && !isCookieAttribute(domain))\n\t\tthrow new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`)\n\tconst path = options?.path ?? '/'\n\tif (!isCookieAttribute(path))\n\t\tthrow new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`)\n\tconst secure = sameSite === 'None' || options?.secure === true\n\tconst parts = [`${name}=${encodeURIComponent(value)}`]\n\tif (domain !== undefined) parts.push(`Domain=${domain}`)\n\tparts.push(`Path=${path}`)\n\tif (options?.maxAge !== undefined) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`)\n\tif (options?.httpOnly !== false) parts.push('HttpOnly')\n\tif (secure) parts.push('Secure')\n\tparts.push(`SameSite=${sameSite}`)\n\treturn parts.join('; ')\n}\n\n/**\n * Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}\n * `secure` setting and whether the request arrived over TLS.\n *\n * @remarks\n * `true` / `false` are explicit overrides. `undefined` (the secure default —\n * the option omitted) resolves to `encrypted` — `Secure` on a TLS\n * connection, off over plaintext HTTP — so a production HTTPS deployment\n * gets `Secure` automatically while local-dev HTTP still works.\n *\n * @param secure - The {@link CookieOptions} `secure` setting\n * @param encrypted - The connection's TLS flag\n * ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted\n * `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to\n * no `Secure` attribute.\n * @returns The concrete `Secure` flag to emit\n *\n * @example\n * ```ts\n * resolveSecure(undefined, true) // true\n * resolveSecure(undefined, false) // false\n * resolveSecure(false, true) // false — explicit override wins\n * ```\n */\nexport function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean {\n\tif (secure === true || secure === false) return secure\n\treturn encrypted\n}\n\n/**\n * Writes a signed cookie — HMAC-signs `value` with {@link signToken} and\n * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).\n *\n * @remarks\n * The cookie value is `await signToken(value, { signer })`\n * (`<payload>.<signature>`), so a signed cookie is a stateless token in a\n * cookie — the same key rotation and tamper rejection, no second HMAC\n * scheme. Appends (never clobbers) through `Headers.append`, which accumulates\n * repeated headers.\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name\n * @param value - The opaque value to sign into the cookie\n * @param signer - The {@link SignerInterface} that signs (its first key signs)\n * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * await writeSignedCookie(headers, 'session', 'user-1', createSigner('secret'))\n * ```\n */\nexport async function writeSignedCookie(\n\theaders: Headers,\n\tname: string,\n\tvalue: string,\n\tsigner: SignerInterface,\n\toptions?: CookieOptions,\n): Promise<void> {\n\theaders.append('set-cookie', serializeCookie(name, await signToken(value, { signer }), options))\n}\n\n/**\n * Reads and verifies a signed cookie off a request, returning the embedded value\n * or `undefined` (the inverse of {@link writeSignedCookie}).\n *\n * @remarks\n * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,\n * and verifies it with {@link verifyToken} against `signer` (a signer over a\n * rotation list accepts a cookie signed by any of its keys). An absent cookie,\n * a tampered value, and a wrong key each yield `undefined`, a name such as\n * `constructor` included. It rejects only when `signer.verify` rejects, which\n * the signer `createSigner` returns never does.\n *\n * @param request - The `Request` to read the `Cookie` header from\n * @param name - The cookie name to read\n * @param signer - The {@link SignerInterface} to verify against\n * @returns The embedded value when the cookie is present + valid, else `undefined`\n *\n * @example\n * ```ts\n * const value = await readSignedCookie(request, 'session', createSigner('secret'))\n * ```\n */\nexport async function readSignedCookie(\n\trequest: Request,\n\tname: string,\n\tsigner: SignerInterface,\n): Promise<string | undefined> {\n\tconst cookie = parseCookies(request.headers.get('cookie') ?? undefined)[name]\n\treturn cookie === undefined ? undefined : verifyToken(cookie, signer)\n}\n\n/**\n * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).\n *\n * @remarks\n * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the\n * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops\n * a cookie when those match the one it set).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name to clear\n * @param options - The {@link CookieOptions} that must match the original cookie\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * clearCookie(headers, 'session')\n * ```\n */\nexport function clearCookie(headers: Headers, name: string, options?: CookieOptions): void {\n\theaders.append('set-cookie', serializeCookie(name, '', { ...options, maxAge: 0 }))\n}\n\n// The stateless signed-token primitives (module-scope helpers). A token is\n// `<payload>.<signature>`: the payload a base64url JSON `{ value, exp? }`, the\n// signature the signer's HMAC-SHA256 of the payload.\n\n/**\n * Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.\n *\n * @remarks\n * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the\n * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so\n * the expiry is HMAC-COVERED — a client cannot extend it without invalidating\n * the signature), signed by `options.signer`, whose first key signs. Verify\n * with {@link verifyToken}. Omitting `ttl` mints a token that never expires.\n *\n * @param value - The opaque value to embed (a session id, a deployment marker)\n * @param options - The `signer` and optional `ttl` (ms); see {@link TokenOptions}\n * @returns The signed `<payload>.<signature>` token string\n *\n * @example\n * ```ts\n * const signer = createSigner('shh')\n * const token = await signToken('client', { signer, ttl: 60_000 })\n * await verifyToken(token, signer) // 'client' (within 60s), else undefined\n * ```\n */\nexport async function signToken(value: string, options: TokenOptions): Promise<string> {\n\tconst exp = options.ttl !== undefined ? Date.now() + options.ttl : undefined\n\tconst encoded = encodeBase64URL(new TextEncoder().encode(JSON.stringify({ value, exp })))\n\treturn `${encoded}.${await options.signer.sign(encoded)}`\n}\n\n/**\n * Verifies a stateless token and returns its embedded value, or `undefined` for a\n * malformed, tampered, or expired token.\n *\n * @remarks\n * The inverse of {@link signToken}: splits the token on its last `.` (so a\n * value containing dots survives), checks the signature with `signer.verify`\n * (a signer over a rotation list accepts any of its keys), then decodes and\n * narrows the payload with {@link decodeTokenPayload}, which refuses an\n * elapsed expiry. It rejects only when `signer.verify` rejects, which the\n * signer `createSigner` returns never does, so a consumer signer's outage\n * surfaces as an error rather than as an invalid token.\n *\n * @param token - The candidate token string (from a request header/cookie)\n * @param signer - The {@link SignerInterface} to verify against\n * @returns The embedded value when the token is valid + unexpired, else `undefined`\n *\n * @example\n * ```ts\n * await verifyToken('bad.token', createSigner('shh')) // undefined\n * ```\n */\nexport async function verifyToken(\n\ttoken: string,\n\tsigner: SignerInterface,\n): Promise<string | undefined> {\n\tconst dot = token.lastIndexOf('.')\n\tif (dot < 0) return undefined\n\tconst encoded = token.slice(0, dot)\n\treturn (await signer.verify(encoded, token.slice(dot + 1)))\n\t\t? decodeTokenPayload(encoded)\n\t\t: undefined\n}\n\n/**\n * Decodes and narrows a signed token's base64url JSON payload, honoring its\n * expiry — the shared decode step {@link verifyToken} applies after a\n * signature match.\n *\n * @remarks\n * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a\n * non-canonical base64url segment answers `undefined` rather than throwing),\n * reads it as UTF-8 JSON, narrows it to a record with a string `value` without\n * `as`, and rejects an expired `exp`. Total — any decode/shape/expiry failure\n * yields `undefined`, including invalid JSON (`parseJSON` answers `undefined`).\n *\n * @param encoded - The base64url-encoded payload segment (before the last `.`)\n * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`\n */\nexport function decodeTokenPayload(encoded: string): string | undefined {\n\tconst bytes = decodeBase64URL(encoded)\n\tif (bytes === undefined) return undefined\n\tconst payload = parseJSON(new TextDecoder().decode(bytes))\n\tif (!isRecord(payload)) return undefined\n\tif (!isString(payload.value)) return undefined\n\tif (payload.exp !== undefined && !isNumber(payload.exp)) return undefined\n\tif (payload.exp !== undefined && Date.now() >= payload.exp) return undefined\n\treturn payload.value\n}\n\n/**\n * Normalizes a {@link TokenSecret} to its `[current, ...older]` list — the list a\n * signer creates its keys from — refusing a malformed secret.\n *\n * @remarks\n * A single string becomes a one-element list; a rotation list is copied once\n * and its copy validated, each secret kept verbatim. A blank entry is refused,\n * never dropped, because dropping a blank current secret would make an older\n * key sign. The refusal names the blank or non-string positions in `context`\n * and carries no secret text.\n *\n * @param secret - The {@link TokenSecret} (a single string, or a rotation list)\n * @returns The secrets, current first\n * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of\n * strings, when the list is empty, or when any entry is blank\n *\n * @example\n * ```ts\n * normalizeSecret(['new', 'old']) // ['new', 'old']\n * normalizeSecret(['new', ' ']) // throws ServerError 'SECRET', context { entries: [1], count: 2 }\n * ```\n */\nexport function normalizeSecret(secret: TokenSecret): readonly [string, ...string[]] {\n\tconst copied = attempt((): readonly unknown[] | undefined =>\n\t\tisString(secret) ? [secret] : isArray(secret) ? Array.from(secret) : undefined,\n\t)\n\tconst entries = copied.success ? copied.value : undefined\n\tif (entries === undefined)\n\t\tthrow new ServerError(\n\t\t\t'SECRET',\n\t\t\t'the signing secret is not a string or a list of strings: pass a non-blank string or a non-empty list of non-blank strings',\n\t\t\t{ received: typeof secret },\n\t\t)\n\tconst blank = entries.flatMap((entry, index) =>\n\t\tisString(entry) && entry.trim().length > 0 ? [] : [index],\n\t)\n\tconst [current, ...older] = entries\n\tif (!isString(current) || blank.length > 0 || !older.every(isString))\n\t\tthrow new ServerError(\n\t\t\t'SECRET',\n\t\t\tentries.length === 0\n\t\t\t\t? 'the signing secret is an empty list: pass a non-blank string or a non-empty list of non-blank strings'\n\t\t\t\t: `the signing secret has blank or non-string entries at ${blank.join(', ')}: pass a non-blank string or a non-empty list of non-blank strings`,\n\t\t\t{ entries: blank, count: entries.length },\n\t\t)\n\treturn [current, ...older]\n}\n\n// The content-negotiation helpers (module-scope) — the one shared q-value\n// parser behind the `Negotiator` and any compression middleware's\n// `Accept-Encoding` pick.\n\n/**\n * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header\n * into its q-sorted entries.\n *\n * @remarks\n * Splits on `,`; for each part takes the token before the first `;`\n * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the\n * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls\n * back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must\n * honor). The result is sorted by `q` descending, a stable sort preserving\n * the header's own order within a tie — a single pass with no backtracking,\n * so parsing stays linear in the header length (ReDoS-safe). Total — an\n * empty/malformed header yields `[]`/best-effort entries, never throws.\n *\n * @param header - The raw weighted header value\n * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending\n *\n * @example\n * ```ts\n * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')\n * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]\n * ```\n */\nexport function parseAcceptHeader(header: string): readonly AcceptEntry[] {\n\tconst entries: AcceptEntry[] = []\n\tfor (const part of header.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.length === 0) continue\n\t\tconst semicolon = trimmed.indexOf(';')\n\t\tconst value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase()\n\t\tif (value.length === 0) continue\n\t\tconst match = semicolon === -1 ? null : /;\\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon))\n\t\tconst parsed = match === null ? undefined : Number(match[1])\n\t\tconst q = isFiniteNumber(parsed) ? Math.min(1, Math.max(0, parsed)) : 1\n\t\tentries.push({ value, q })\n\t}\n\treturn entries\n\t\t.map((entry, index) => ({ entry, index }))\n\t\t.sort((a, b) => b.entry.q - a.entry.q || a.index - b.index)\n\t\t.map((ranked) => ranked.entry)\n}\n\n/**\n * Computes the client's quality (q) for one content-coding from the parsed\n * `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over\n * each offered coding.\n *\n * @remarks\n * Prefers an exact named match (including an explicit `;q=0` rejection);\n * failing that, a bare `*` wildcard's q applies. A coding that is neither\n * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins\n * over a `*` (a specific rejection beats the wildcard), so it scores `0`.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param coding - The candidate coding to score\n * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5\n * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1\n * ```\n */\nexport function computeCodingQuality(entries: readonly AcceptEntry[], coding: string): number {\n\tconst named = entries.find((entry) => entry.value === coding)\n\tif (named !== undefined) return named.q\n\tconst wildcard = entries.find((entry) => entry.value === '*')\n\treturn wildcard?.q ?? 0\n}\n\n/**\n * Picks the highest-scoring content-coding the server offers against already\n * parsed `Accept-Encoding` entries — the shared selection leaf behind\n * {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.\n *\n * @remarks\n * The single selection leaf behind both doors onto this axis —\n * {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the\n * entity — so the scoring loop has one implementation. Scores each `available`\n * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`\n * keeps the earlier-offered coding on a client-side tie, which is what makes\n * `available` the server's preference order. An empty `available` list, and a\n * list the client rejects outright, both yield `undefined` (identity — no\n * compression). Total on malformed input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param entries - The parsed {@link AcceptEntry} list\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The winning coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'\n * resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined\n * ```\n */\nexport function resolveCoding<T extends string>(\n\tentries: readonly AcceptEntry[],\n\tavailable: readonly T[],\n): T | undefined {\n\tconst best = Iterator.from(available).reduce<\n\t\t{ readonly value: T; readonly quality: number } | undefined\n\t>((previous, coding) => {\n\t\tconst quality = computeCodingQuality(entries, coding)\n\t\treturn quality > (previous?.quality ?? 0) ? { value: coding, quality } : previous\n\t}, undefined)\n\treturn best?.value\n}\n\n/**\n * Selects the best content-coding for a raw `Accept-Encoding` header from the\n * codings the server offers.\n *\n * @remarks\n * Parses the header ({@link parseAcceptHeader}) and hands the entries to\n * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so\n * the two doors onto this axis cannot drift. Returns `undefined` when the\n * client accepts none of `available` (identity — no compression). Total on\n * malformed input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param header - The raw `Accept-Encoding` header value\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The negotiated coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * ```\n */\nexport function negotiateEncoding<T extends string>(\n\theader: string,\n\tavailable: readonly T[],\n): T | undefined {\n\tif (available.length === 0) return undefined\n\treturn resolveCoding(parseAcceptHeader(header), available)\n}\n\n/**\n * Reports the rank and quality of one `candidate` media type against the parsed `Accept`\n * entries — the generic media-type primitive the `Negotiator`'s `negotiate`\n * uses to score each `available` candidate.\n *\n * @remarks\n * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the\n * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact\n * `;q=0` entry explicitly rejects the candidate outright (returns\n * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own\n * (less specific) coverage, so a later more-specific match can still allow\n * it. Among multiple matching entries, the lowest `rank` wins, and among a\n * rank tie the highest `q` wins. The candidate matches case-insensitively, as\n * the entries do.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate media type to score (for example `'text/html'`)\n * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches\n *\n * @example\n * ```ts\n * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')\n * // { q: 1, rank: 0 }\n * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }\n * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined\n * ```\n */\nexport function matchMediaType(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): MediaMatch | undefined {\n\tconst matches = iterateMediaMatches(entries, candidate)\n\treturn matches.reduce<MediaMatch | undefined>((best, match) => {\n\t\tif (match.q === 0) return undefined\n\t\tconst preferred =\n\t\t\tbest === undefined || match.rank < best.rank || (match.rank === best.rank && match.q > best.q)\n\t\treturn preferred ? match : best\n\t}, undefined)\n}\n\n/**\n * Yields matching media ranges through the first exact rejection.\n *\n * @example\n * ```ts\n * Array.from(iterateMediaMatches([{ value: 'text/plain', q: 1 }], 'text/plain'))\n * // [{ q: 1, rank: 0 }]\n * ```\n */\nexport function* iterateMediaMatches(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): Generator<MediaMatch, void, unknown> {\n\t// `parseAcceptHeader` lower-cases each entry, and a media type matches case-insensitively.\n\tconst media = candidate.toLowerCase()\n\tconst slash = media.indexOf('/')\n\tconst type = slash === -1 ? media : media.slice(0, slash)\n\tfor (const entry of entries) {\n\t\tconst rank =\n\t\t\tentry.value === media\n\t\t\t\t? 0\n\t\t\t\t: entry.value === `${type}/*`\n\t\t\t\t\t? 1\n\t\t\t\t\t: entry.value === '*/*'\n\t\t\t\t\t\t? 2\n\t\t\t\t\t\t: undefined\n\t\tif (rank === undefined) continue\n\t\tif (entry.q === 0) {\n\t\t\t// An exact `;q=0` explicitly rejects this candidate outright; a\n\t\t\t// wildcard `;q=0` only rejects the wildcard's own (less specific)\n\t\t\t// coverage, so a later more-specific match can still allow it.\n\t\t\tif (rank === 0) {\n\t\t\t\tyield { q: 0, rank }\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tyield { q: entry.q, rank }\n\t}\n}\n\n/**\n * Yields the same lazily collected request-body promise on every read.\n *\n * @example\n * ```ts\n * const bodies = iterateRequestBody(new Request('http://localhost/'), 1024)\n * bodies.next().value === bodies.next().value // true\n * ```\n */\nexport function* iterateRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Generator<Promise<unknown>, never, unknown> {\n\tconst body = readBody(request, { limit })\n\tfor (;;) yield body\n}\n\n/**\n * Computes the client's quality for one `candidate` language from the parsed\n * `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`\n * axis runs over each offered tag.\n *\n * @remarks\n * Prefers an exact match, then a primary-tag prefix match (`en` accepts\n * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry\n * is an explicit rejection).\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate language tag to score (for example `'en-US'`)\n * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1\n * computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix\n * computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard\n * ```\n */\nexport function computeLanguageQuality(entries: readonly AcceptEntry[], candidate: string): number {\n\tconst lower = candidate.toLowerCase()\n\tconst primary = lower.split('-')[0]\n\tconst qualities = Iterator.from(entries).reduce<{\n\t\treadonly named?: number\n\t\treadonly prefixed?: number\n\t\treadonly wildcard?: number\n\t}>((previous, entry) => {\n\t\tconst entryPrimary = entry.value.split('-')[0]\n\t\tif (entry.value === lower) return { ...previous, named: entry.q }\n\t\tif (entryPrimary === primary) {\n\t\t\treturn previous.prefixed === undefined ? { ...previous, prefixed: entry.q } : previous\n\t\t}\n\t\treturn entry.value === '*' ? { ...previous, wildcard: entry.q } : previous\n\t}, {})\n\treturn qualities.named ?? qualities.prefixed ?? qualities.wildcard ?? 0\n}\n\n/**\n * Checks whether a `Content-Type` is worth compressing.\n *\n * @remarks\n * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`\n * type, a `+json`/`+xml` structured suffix, or one of the explicit\n * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed\n * binary (`image/png`, `application/zip`) is not compressible. An\n * absent/empty type is not compressible. Total.\n *\n * @param type - The response `Content-Type` header value (with or without parameters)\n * @returns True if the type is text-shaped and worth compressing; false otherwise\n *\n * @example\n * ```ts\n * isCompressibleType('application/json; charset=utf-8') // true\n * isCompressibleType('image/png') // false\n * ```\n */\nexport function isCompressibleType(type: string): boolean {\n\tconst semicolon = type.indexOf(';')\n\tconst bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase()\n\tif (bare.length === 0) return false\n\tif (bare.startsWith('text/')) return true\n\tif (bare.endsWith('+json') || bare.endsWith('+xml')) return true\n\treturn COMPRESSIBLE_TYPES.has(bare)\n}\n\n// The conditional-request helpers (module-scope) — ETag\n// compute/compare (RFC 7232 §2.3.2 weak comparison) and the total `Range`\n// parser.\n\n/**\n * Computes a content `ETag` over a fully-buffered response body by using WebCrypto.\n *\n * @remarks\n * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex\n * digest as a weak validator (`W/\"<hash>\"`) when `weak` is `true` — the\n * default, encoding-agnostic, so the tag survives a downstream content\n * re-encoding (gzip) and still matches on revalidation — or a strong one\n * (`\"<hash>\"`, byte-identity) when `weak` is `false`.\n *\n * @param body - The full (uncompressed) response body to hash\n * @param weak - If `true` (the default), returns a weak `W/\"…\"` validator; if\n * `false`, returns a strong `\"…\"` one.\n * @returns The `ETag` header value\n *\n * @example\n * ```ts\n * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/\"…sha256-hex…\"'\n * ```\n */\nexport async function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak = true): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', body)\n\tconst hex = encodeHex(new Uint8Array(digest))\n\treturn weak ? `W/\"${hex}\"` : `\"${hex}\"`\n}\n\n/**\n * Strips the weak indicator (`W/`) from an entity-tag, returning its opaque\n * comparison body — the reduction {@link matchesETag} applies to each side\n * before the RFC 7232 §2.3.2 weak comparison.\n *\n * @param tag - One entity-tag (`W/\"<body>\"` or `\"<body>\"`)\n * @returns The tag with any leading `W/` removed (the quotes preserved)\n *\n * @example\n * ```ts\n * unwrapETag('W/\"abc\"') // '\"abc\"'\n * ```\n */\nexport function unwrapETag(tag: string): string {\n\tconst trimmed = tag.trim()\n\treturn trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed\n}\n\n/**\n * Checks whether a request's `If-None-Match` header matches a resource's current\n * `ETag` — the RFC 7232 §2.3.2 weak comparison.\n *\n * @remarks\n * `If-None-Match` is a comma-separated list of entity-tags (matches if any\n * listed tag matches), or the `*` wildcard (matches any current\n * representation — only a list of exactly `*` is the wildcard). Comparison is\n * weak: `W/\"abc\"` and `\"abc\"` are equal (each side's weak prefix is stripped\n * through {@link unwrapETag} before comparing the opaque body). Total — a\n * malformed/empty header matches nothing, never throws.\n *\n * @param header - The raw `If-None-Match` header value\n * @param etag - The resource's current `ETag`\n * @returns True if the conditional matches (the caller answers `304`); false otherwise\n *\n * @example\n * ```ts\n * matchesETag('\"abc\", W/\"def\"', 'W/\"abc\"') // true — weak comparison\n * matchesETag('*', 'W/\"anything\"') // true — wildcard\n * ```\n */\nexport function matchesETag(header: string, etag: string): boolean {\n\tconst trimmed = header.trim()\n\tif (trimmed === '*') return true\n\tconst target = unwrapETag(etag)\n\tfor (const member of trimmed.split(',')) {\n\t\tconst candidate = member.trim()\n\t\tif (candidate.length === 0) continue\n\t\tif (unwrapETag(candidate) === target) return true\n\t}\n\treturn false\n}\n\n/**\n * Parses an HTTP `Range` request header against a known resource `size` —\n * total, returning a {@link RangeSpec} or `undefined`.\n *\n * @remarks\n * Reads the field value by RFC 9110 § 14.1:\n * `range-unit \"=\" OWS range-set`, where the unit matches `bytes`\n * case-insensitively and `range-set` is `1#range-spec` under the § 5.6.1 list\n * rule, so empty list elements are skipped. OWS is a space or a tab, and it\n * stands only around the field value, after `=`, and around a `,`; a range\n * holds none. A range is an `int-range` (`first-pos \"-\" [ last-pos ]`) or a\n * `suffix-range` (`\"-\" suffix-length`), each bound `1*DIGIT` ({@link\n * import('./constants.js').RANGE_BOUND_PATTERN}). A bound of any length is\n * compared with {@link compareDigits}, so none is misread through `Number`.\n * OWS is stripped with {@link stripOWS}, so the read is linear in the header's\n * length.\n *\n * Returns `{ satisfiable: true, start, end }` with the window clamped to\n * `[0, size - 1]` (the HTTP inclusive-end convention), and\n * `{ satisfiable: false }` when the range does not overlap the resource: a\n * `first-pos` at or past `size`, or a zero `suffix-length`.\n * Returns `undefined`, the § 14.2 \"ignore the field and serve the whole\n * resource\" answer, for an absent header, another unit, text outside the\n * grammar, a `last-pos` below its `first-pos`, more than one range (not\n * supported), a non-zero `suffix-length` on an empty resource (satisfiable by\n * § 14.1.2, but it selects no window to serve), and a `size` that is not a\n * non-negative safe integer. Never throws on a malformed header.\n *\n * @param header - The raw `Range` header value\n * @param size - The resource's total byte length\n * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource\n *\n * @example\n * ```ts\n * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }\n * parseRange('Bytes=-100,', 1000) // { satisfiable: true, start: 900, end: 999 }\n * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused\n * parseRange('bytes=0x10-', 1000) // undefined — not a decimal bound\n * parseRange('bytes=5 - 9', 1000) // undefined — no OWS inside a range\n * ```\n */\nexport function parseRange(header: string | undefined, size: number): RangeSpec | undefined {\n\tif (header === undefined || !isSafeInteger(size) || size < 0) return undefined\n\tconst field = stripOWS(header)\n\tconst equals = field.indexOf('=')\n\tif (equals < 0 || field.slice(0, equals).toLowerCase() !== 'bytes') return undefined\n\tconst specs = field\n\t\t.slice(equals + 1)\n\t\t.split(',')\n\t\t.map((item) => stripOWS(item))\n\t\t.filter((spec) => spec !== '')\n\tconst spec = specs[0]\n\tif (spec === undefined || specs.length > 1) return undefined\n\tconst dash = spec.indexOf('-')\n\tif (dash < 0) return undefined\n\tconst first = spec.slice(0, dash)\n\tconst last = spec.slice(dash + 1)\n\tconst extent = String(size)\n\tif (first === '') {\n\t\tif (!RANGE_BOUND_PATTERN.test(last)) return undefined\n\t\tif (compareDigits(last, '0') === 0) return { satisfiable: false }\n\t\tif (size === 0) return undefined\n\t\tconst start = compareDigits(last, extent) < 0 ? size - Number(last) : 0\n\t\treturn { satisfiable: true, start, end: size - 1 }\n\t}\n\tif (!RANGE_BOUND_PATTERN.test(first)) return undefined\n\tif (last !== '' && !RANGE_BOUND_PATTERN.test(last)) return undefined\n\tif (last !== '' && compareDigits(last, first) < 0) return undefined\n\tif (compareDigits(first, extent) >= 0) return { satisfiable: false }\n\tconst end = last === '' || compareDigits(last, extent) >= 0 ? size - 1 : Number(last)\n\treturn { satisfiable: true, start: Number(first), end }\n}\n\n/**\n * Strips the OWS of RFC 9110 § 5.6.3 — spaces and tabs, and no other\n * character — from both ends of a text, in time linear in its length.\n *\n * @remarks\n * Reads the leading run with one anchored match and the trailing run with one\n * scan from the end, so a long run of spaces followed by another character\n * costs one pass, where a search for a trailing run restarts at every space.\n * A Unicode space such as U+00A0 stays, unlike `trim`.\n *\n * @param text - The text to strip\n * @returns `text` without its leading and trailing spaces and tabs\n *\n * @example\n * ```ts\n * stripOWS(' \\tbytes=0-1 ') // 'bytes=0-1'\n * ```\n */\nexport function stripOWS(text: string): string {\n\tconst start = /^[ \\t]*/.exec(text)?.[0].length ?? 0\n\tconst end = text.split('').findLastIndex((char) => char !== ' ' && char !== '\\t') + 1\n\treturn end <= start ? '' : text.slice(start, end)\n}\n\n/**\n * Compares two `1*DIGIT` strings by their decimal value, at any length.\n *\n * @remarks\n * Drops leading zeros, then compares the digit counts and, at an equal count,\n * the digits in order, so a bound longer than any safe integer compares\n * exactly and never passes through `Number`. Both arguments must be\n * `1*DIGIT`; the answer for any other text is unspecified.\n *\n * @param left - The first digit string\n * @param right - The second digit string\n * @returns `-1` if `left` is less, `1` if it is greater, `0` if the two are equal\n *\n * @example\n * ```ts\n * compareDigits('9', '10') // -1\n * compareDigits('007', '7') // 0\n * ```\n */\nexport function compareDigits(left: string, right: string): number {\n\tconst a = left.replace(/^0+/, '')\n\tconst b = right.replace(/^0+/, '')\n\tif (a.length !== b.length) return a.length < b.length ? -1 : 1\n\treturn a < b ? -1 : a > b ? 1 : 0\n}\n\n// The security primitives (module-scope) — CORS origin\n// resolution, `Vary` merging, security-header resolution, request-id\n// validation, and the IPv6 `/64` rate-key collapse.\n\n/**\n * Resolves the `Access-Control-Allow-Origin` value for a request.\n *\n * @remarks\n * `'*'` and a single origin string pass straight through. An allow-list\n * echoes the request's `Origin` only when it is present in the list, else\n * `undefined` (no header set). Security: the literal `'null'` origin — sent\n * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is\n * never reflected even if `'null'` were listed, closing the opaque-origin\n * cross-origin-access hole.\n *\n * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list\n * @param requestOrigin - The request's `Origin` header value, if present\n * @returns The allow-origin value to send, or `undefined` to set no header\n *\n * @example\n * ```ts\n * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'\n * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected\n * ```\n */\nexport function resolveOrigin(\n\torigin: string | readonly string[],\n\trequestOrigin: string | undefined,\n): string | undefined {\n\tif (isString(origin)) return origin\n\tif (!isString(requestOrigin)) return undefined\n\tif (requestOrigin === 'null') return undefined\n\treturn origin.includes(requestOrigin) ? requestOrigin : undefined\n}\n\n/**\n * Merges a `Vary` value into an existing `Vary` header without duplication.\n *\n * @remarks\n * Splits `existing` on `,`, trims each member, and appends `value` only when\n * no existing member already matches it case-insensitively (`Vary` header\n * names are case-insensitive). Preserves the existing members' order and\n * appends the new one last.\n *\n * @param existing - The current `Vary` header value, if any\n * @param value - The header name to ensure is listed\n * @returns The merged `Vary` value\n *\n * @example\n * ```ts\n * mergeVary(undefined, 'Origin') // 'Origin'\n * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)\n * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'\n * ```\n */\nexport function mergeVary(existing: string | undefined, value: string): string {\n\tconst members =\n\t\texisting === undefined\n\t\t\t? []\n\t\t\t: existing\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((member) => member.trim())\n\t\t\t\t\t.filter((member) => member.length > 0)\n\tconst present = members.some((member) => member.toLowerCase() === value.toLowerCase())\n\treturn present ? members.join(', ') : [...members, value].join(', ')\n}\n\n/**\n * Resolves one opt-out, value-bearing security header.\n *\n * @remarks\n * The shared \"a `string` value, or `false` to omit, or a default when unset\"\n * resolution (a value-or-off union, not a behavioral toggle):\n * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that\n * override, `undefined` (unset) ⇒ `fallback` (the secure default).\n *\n * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default\n * @param fallback - The secure-default value used when `value` is unset\n * @returns The header value to set, or `undefined` to omit the header\n *\n * @example\n * ```ts\n * resolveSecurityHeader(undefined, 'DENY') // 'DENY'\n * resolveSecurityHeader(false, 'DENY') // undefined — omitted\n * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override\n * ```\n */\nexport function resolveSecurityHeader(\n\tvalue: string | false | undefined,\n\tfallback: string,\n): string | undefined {\n\tif (value === false) return undefined\n\treturn value ?? fallback\n}\n\n/**\n * Checks whether a client-supplied `X-Request-ID` is safe to echo into a response\n * header and `context.state`.\n *\n * @remarks\n * A request id is echoed raw into a response header and log lines, so an\n * untrusted one is a header-injection + log-injection + DoS vector. This\n * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}\n * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).\n * Total — never throws.\n *\n * @param value - The candidate incoming request id\n * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise\n *\n * @example\n * ```ts\n * isValidRequestId('req_abc-123') // true\n * isValidRequestId('bad\\r\\nheader') // false\n * ```\n */\nexport function isValidRequestId(value: string): boolean {\n\treturn REQUEST_ID_PATTERN.test(value)\n}\n\n/**\n * Computes the `/64` network of a full IPv6 address, or `undefined` when the\n * input is not a plain IPv6 address to collapse.\n *\n * @remarks\n * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4\n * is the identity) or any string that does not expand to exactly eight\n * hextets. Expands a single `::` into the missing zero hextets, takes the\n * first four (the `/64` prefix), normalizes each (lower-case, no leading\n * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped\n * first. Total — a malformed address returns `undefined`.\n *\n * @param address - The candidate IPv6 address\n * @returns The `/64` network string, or `undefined` when not a plain IPv6 address\n *\n * @example\n * ```ts\n * computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'\n * computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed\n * ```\n */\nexport function computeIPv6Network(address: string): string | undefined {\n\tif (/^::ffff:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i.test(address)) return undefined\n\tconst percent = address.indexOf('%')\n\tconst bare = percent === -1 ? address : address.slice(0, percent)\n\tconst halves = bare.split('::')\n\tif (halves.length > 2) return undefined\n\tconst first = halves[0]\n\tif (first === undefined) return undefined\n\tconst second = halves[1]\n\tif (halves.length === 2 && second === undefined) return undefined\n\tconst head = first === '' ? [] : first.split(':')\n\tconst tail = second === undefined || second === '' ? [] : second.split(':')\n\tconst missing = 8 - head.length - tail.length\n\tif (halves.length === 2 && missing < 0) return undefined\n\tconst groups =\n\t\thalves.length === 2 ? [...head, ...Array.from({ length: missing }, () => '0'), ...tail] : head\n\tif (groups.length !== 8) return undefined\n\tconst prefix: string[] = []\n\tfor (const group of groups.slice(0, 4)) {\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return undefined\n\t\tprefix.push(Number.parseInt(group, 16).toString(16))\n\t}\n\treturn `${prefix.join(':')}::/64`\n}\n\n/**\n * Collapses a client IP into its rate-limit bucket key — an IPv6 address to\n * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.\n *\n * @remarks\n * A residential/mobile IPv6 user is routinely handed a whole `/64`, so a\n * per-`/128` rate limit is trivially bypassed by rotating host bits — the\n * real identity is the `/64` network. Delegates the IPv6 collapse to\n * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,\n * a malformed string) is kept unchanged.\n *\n * @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})\n * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged\n *\n * @example\n * ```ts\n * computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'\n * computeClientKey('192.0.2.1') // '192.0.2.1'\n * ```\n */\nexport function computeClientKey(address: string): string {\n\treturn computeIPv6Network(address) ?? address\n}\n\n// The Server-Sent-Events seam (module-scope) — `serializeEvent` and\n// `serializeComment` are the wire encoders. A conforming SSE parser reads an\n// event back with each line break in its data as `\\n`, and exposes no\n// comment, so a comment dispatches nothing. The stream handle\n// that writes those events over a `ReadableStream` is the `Stream` entity,\n// reached through `createStream`.\n\n/**\n * Serializes one {@link SSEMessage} to the SSE wire.\n *\n * @remarks\n * Emits an `event:`/`id:`/`retry:` line for each present field, then one\n * `data:` line per CRLF-aware-split (`\\r\\n` / `\\r` / `\\n`) segment of `data`\n * (so a consuming parser's multi-`data` concat reproduces `data` with each\n * line break read as `\\n`, and no raw `\\r` or `\\n` can ever ride onto the wire\n * inside a `data:` line), then the terminating blank line.\n *\n * It refuses a field the wire cannot carry rather than emit a second field or\n * a second event: an `event` with a line break, an `id` with a line break or\n * a NUL (which a conforming parser drops), and a `retry` that is not a\n * non-negative safe integer.\n *\n * @param message - The event to serialize\n * @returns The SSE wire text for the event (terminated by a blank line)\n * @throws {ServerError} Thrown when a field is refused, with code `'EVENT'`\n * and `context.field` naming the field\n *\n * @example\n * ```ts\n * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\\ndata: hello\\n\\n'\n * serializeEvent({ data: 'multi\\nline' }) // 'data: multi\\ndata: line\\n\\n'\n * ```\n */\nexport function serializeEvent(message: SSEMessage): string {\n\tconst { event, id, retry } = message\n\tif (event !== undefined && /[\\r\\n]/.test(event))\n\t\tthrow new ServerError('EVENT', 'an SSE event type must be one line', { field: 'event' })\n\tif (id !== undefined && /[\\r\\n\\0]/.test(id))\n\t\tthrow new ServerError('EVENT', 'an SSE id must be one line with no NUL', { field: 'id' })\n\tif (retry !== undefined && !(isSafeInteger(retry) && retry >= 0))\n\t\tthrow new ServerError('EVENT', 'an SSE retry must be a non-negative safe integer', {\n\t\t\tfield: 'retry',\n\t\t})\n\tconst lines = [\n\t\t...(event === undefined ? [] : [`event: ${event}`]),\n\t\t...(id === undefined ? [] : [`id: ${id}`]),\n\t\t...(retry === undefined ? [] : [`retry: ${retry}`]),\n\t\t...message.data.split(SSE_LINE_PATTERN).map((segment) => `data: ${segment}`),\n\t]\n\treturn `${lines.join('\\n')}\\n\\n`\n}\n\n/**\n * Serializes a comment to the SSE wire, one `: ` line per line of `text`.\n *\n * @remarks\n * Splits `text` on `\\r\\n`, `\\r`, and `\\n`, so no line of the comment can\n * reach a parser as a field and no comment can dispatch an event.\n *\n * @example\n * ```ts\n * serializeComment('keep-alive') // ': keep-alive\\n\\n'\n * serializeComment('a\\nb') // ': a\\n: b\\n\\n'\n * ```\n */\nexport function serializeComment(text: string): string {\n\treturn `${text\n\t\t.split(SSE_LINE_PATTERN)\n\t\t.map((line) => `: ${line}`)\n\t\t.join('\\n')}\\n\\n`\n}\n\n// The body pipeline (module-scope) —\n// `readBody` collects a request body capped at `limit` bytes (413 over),\n// transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n// through a byte-counting `TransformStream` that aborts the instant\n// decompressed output exceeds `decompression` (the zip-bomb defense — fail\n// before materializing the bomb, because `DecompressionStream` has no\n// `maxOutputLength` knob), then decodes by content type. `scrubPrototype` /\n// `isDangerousKey` are the prototype-pollution scrub `readBody` applies to a\n// parsed JSON or urlencoded body.\n\n/**\n * Checks whether a key is a prototype-pollution vector — `__proto__`,\n * `constructor`, or `prototype`, each of which can reach and mutate\n * `Object.prototype` when it is assigned onto a normal object.\n *\n * @param key - The candidate object key\n * @returns True if `key` is one of the three prototype-pollution keys; false otherwise\n *\n * @example\n * ```ts\n * isDangerousKey('__proto__') // true\n * isDangerousKey('name') // false\n * ```\n */\nexport function isDangerousKey(key: string): boolean {\n\treturn key === '__proto__' || key === 'constructor' || key === 'prototype'\n}\n\n/**\n * Strips the prototype-pollution keys from a parsed value in place, at every depth.\n *\n * @remarks\n * `JSON.parse('{\"__proto__\":{…}}')` is benign on its own — it produces an own,\n * enumerable `__proto__` data property — but that own key becomes a\n * pollution gadget the moment a downstream deep-merge copies it onto a live\n * object. This walks the value and `delete`s any own {@link isDangerousKey}\n * key at every depth, into nested records and array elements.\n * Primitives/`null` pass through untouched. Total — never throws. Mutates the\n * freshly-parsed value (which nothing else holds yet).\n *\n * The walk keeps a worklist rather than the call stack, so a value nested as\n * deep as the body limit admits costs no stack depth, and it reads a node\n * reached twice once, so a self-referencing value terminates.\n *\n * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)\n * @returns The same `value`, with every dangerous key removed at every depth\n *\n * @example\n * ```ts\n * scrubPrototype(JSON.parse('{\"__proto__\":{\"polluted\":true},\"name\":\"ok\"}'))\n * // { name: 'ok' } — the __proto__ key is gone\n * ```\n */\nexport function scrubPrototype(value: unknown): unknown {\n\tconst nodes = new Set<unknown>([value])\n\tfor (const node of nodes) {\n\t\tif (isArray(node)) {\n\t\t\tfor (const member of node)\n\t\t\t\tif (isObject(member) && (isArray(member) || isRecord(member))) nodes.add(member)\n\t\t\tcontinue\n\t\t}\n\t\tif (!isRecord(node)) continue\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (isDangerousKey(key)) {\n\t\t\t\tReflect.deleteProperty(node, key)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst member = node[key]\n\t\t\tif (isObject(member) && (isArray(member) || isRecord(member))) nodes.add(member)\n\t\t}\n\t}\n\treturn value\n}\n\n/**\n * Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.\n *\n * @remarks\n * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,\n * throwing a {@link ContentTooLargeError} (413) the instant the running total\n * exceeds `limit` — before the rest of the stream is buffered — rather than\n * collecting an unbounded body. A bodyless request (`request.body === null`)\n * resolves an empty array. A non-positive `limit` means unbounded. When\n * `request.signal` aborts before the call or while a read waits, the body is\n * cancelled with the signal's reason and the promise rejects with that reason.\n *\n * @param request - The `Request` to drain\n * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded\n * @returns The full request body as one `Uint8Array`\n * @throws {ContentTooLargeError} When the body exceeds `limit`\n *\n * @example\n * ```ts\n * const bytes = await collectRequestBody(request, 1_048_576)\n * ```\n */\nexport async function collectRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst signal = request.signal\n\tsignal.throwIfAborted()\n\tif (request.body === null) return new Uint8Array(0)\n\tconst reader = request.body.getReader()\n\tconst chunks: Array<{ readonly bytes: Uint8Array; readonly total: number }> = []\n\tconst relay = addAbortListener(signal, () => reader.cancel(signal.reason).catch(() => undefined))\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tsignal.throwIfAborted()\n\t\t\tif (done) break\n\t\t\tconst total = (chunks.at(-1)?.total ?? 0) + value.byteLength\n\t\t\tif (limit > 0 && total > limit) {\n\t\t\t\tawait reader.cancel()\n\t\t\t\tthrow new ContentTooLargeError(limit)\n\t\t\t}\n\t\t\tchunks.push({ bytes: value, total })\n\t\t}\n\t} finally {\n\t\trelay[Symbol.dispose]()\n\t}\n\tconst merged = new Uint8Array(chunks.at(-1)?.total ?? 0)\n\tchunks.reduce((offset, chunk) => {\n\t\tmerged.set(chunk.bytes, offset)\n\t\treturn offset + chunk.bytes.byteLength\n\t}, 0)\n\treturn merged\n}\n\n/**\n * Parses a raw `Content-Encoding` header value into a decompressible\n * {@link Encoding} — the boundary {@link readBody} coerces through to decide\n * whether a request body needs transparent decompression.\n *\n * @remarks\n * Lower-cases + trims and returns the matching {@link Encoding} only for\n * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An\n * absent header, `identity`, an unknown value, or a\n * comma-joined multi-coding all yield `undefined` (the body is read as-is).\n * Total — never asserts the loose `string | null` header.\n *\n * @param header - The raw `Content-Encoding` header value\n * @returns The single decompressible {@link Encoding}, or `undefined` when none applies\n *\n * @example\n * ```ts\n * parseEncoding('gzip') // 'gzip'\n * parseEncoding('br') // undefined — unsupported by DecompressionStream\n * ```\n */\nexport function parseEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined {\n\tif (!isString(header)) return undefined\n\tconst value = header.trim().toLowerCase()\n\treturn value === 'gzip' || value === 'deflate' ? value : undefined\n}\n\n/**\n * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence\n * transparently through `DecompressionStream`, capping the decompressed output —\n * the zip-bomb defense.\n *\n * @remarks\n * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting\n * `TransformStream` that aborts the pipe the instant the running decompressed\n * total exceeds `cap` — fail-before-materialize, because `DecompressionStream`\n * has no `maxOutputLength` knob. A cap breach surfaces\n * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated\n * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}\n * (never conflated with the cap). A non-positive `cap` means uncapped.\n *\n * @param bytes - The compressed bytes to decompress\n * @param encoding - The {@link Encoding} the bytes are compressed with\n * @param cap - The maximum decompressed byte count; a non-positive value means uncapped\n * @returns The decompressed bytes\n * @throws {ContentTooLargeError} When decompressed output would exceed `cap`\n * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)\n */\nexport async function decompressRequestBody(\n\tbytes: Uint8Array<ArrayBuffer>,\n\tencoding: Exclude<Encoding, 'identity'>,\n\tcap: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst chunks: Array<{ readonly bytes: Uint8Array; readonly total: number }> = []\n\tconst capStream = new TransformStream<Uint8Array, Uint8Array>({\n\t\ttransform(chunk, controller) {\n\t\t\tconst total = (chunks.at(-1)?.total ?? 0) + chunk.byteLength\n\t\t\tif (cap > 0 && total > cap) {\n\t\t\t\tcontroller.error(new ContentTooLargeError(cap))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tchunks.push({ bytes: chunk, total })\n\t\t\tcontroller.enqueue(chunk)\n\t\t},\n\t})\n\tconst source = new ReadableStream<Uint8Array<ArrayBuffer>>({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(bytes)\n\t\t\tcontroller.close()\n\t\t},\n\t})\n\tconst decompressed = source.pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream)\n\tconst reader = decompressed.getReader()\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done } = await reader.read()\n\t\t\tif (done) break\n\t\t}\n\t} catch (error) {\n\t\tif (isInstance(error, ContentTooLargeError)) throw error\n\t\tthrow new HTTPError(400, 'malformed compressed request body')\n\t}\n\tconst merged = new Uint8Array(chunks.at(-1)?.total ?? 0)\n\tchunks.reduce((offset, chunk) => {\n\t\tmerged.set(chunk.bytes, offset)\n\t\treturn offset + chunk.bytes.byteLength\n\t}, 0)\n\treturn merged\n}\n\n/**\n * Collects and decodes a `Request` body — the shared body-collection pipeline\n * surfaced to middleware and handlers as the middleware context's cached\n * `body()`. An empty body and a malformed `application/json` body each decode to\n * `undefined`.\n *\n * @remarks\n * Collects the wire body capped at `options.limit` bytes ({@link\n * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),\n * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at\n * `options.decompression`, default {@link\n * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by\n * content type: `application/json` is parsed by using `@orkestrel/contract`'s\n * `parseJSON`, `application/x-www-form-urlencoded` is read through\n * `URLSearchParams` into a record whose repeated field keeps its last value,\n * and both are scrubbed of prototype-pollution keys ({@link scrubPrototype});\n * any other type decodes as UTF-8 text. The media type matches\n * case-insensitively and ignores its parameters.\n *\n * A malformed JSON body is total: it decodes rather than throwing, so a handler\n * that must reject one checks for `undefined` itself, and nothing in the returned\n * value tells an empty body from a malformed one.\n *\n * @param request - The `Request` to read the body from\n * @param options - The {@link BodyOptions} `limit` + `decompression` caps\n * @returns The parsed JSON value, the decoded form record, the raw text, or\n * `undefined` — for an empty body, and for an `application/json` body whose\n * text is not valid JSON\n * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap\n * @throws {HTTPError} When the compressed body is corrupt (400)\n *\n * @example\n * ```ts\n * const body = await readBody(request, { limit: 1_048_576 })\n * ```\n */\nexport async function readBody(request: Request, options?: BodyOptions): Promise<unknown> {\n\tconst limit = options?.limit ?? DEFAULT_BODY_LIMIT\n\tconst decompression = options?.decompression ?? DEFAULT_DECOMPRESSED_LIMIT\n\tconst wire = await collectRequestBody(request, limit)\n\tconst encoding = parseEncoding(request.headers.get('content-encoding'))\n\tconst bytes =\n\t\tencoding === undefined ? wire : await decompressRequestBody(wire, encoding, decompression)\n\tif (bytes.length === 0) return undefined\n\tconst contentType = request.headers.get('content-type')\n\tconst semicolon = contentType === null ? -1 : contentType.indexOf(';')\n\tconst bareType =\n\t\tcontentType === null\n\t\t\t? ''\n\t\t\t: (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase()\n\tconst text = new TextDecoder().decode(bytes)\n\tif (bareType === 'application/json') return scrubPrototype(parseJSON(text))\n\tif (bareType === 'application/x-www-form-urlencoded')\n\t\treturn scrubPrototype(Object.fromEntries(new URLSearchParams(text)))\n\treturn text\n}\n\n// ============================================================================\n// The node face — pure helpers. Every function here is genuinely\n// node-bound (a `node:net` probe) — everything\n// fetch/string-pure lives earlier in this same file and is consumed, never\n// duplicated (the socket-encrypted narrow and the `Request`/`Response`\n// conversion are `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` /\n// `sendResponse`).\n// ============================================================================\n\n/**\n * Binds and closes a throwaway TCP server to resolve one available port.\n *\n * @remarks\n * The probe always closes, including on the rejection path. A listener whose\n * address is not an {@link import('node:net').AddressInfo} — a pipe listener,\n * which a numeric `port` cannot request — has no port to report, so this\n * rejects rather than substituting a number.\n *\n * @param port - The requested port, with `0` selecting an ephemeral port\n * @returns The bound port after the probe server has closed\n * @throws {TypeError} When the bound listener's address carries no numeric port\n *\n * @example\n * ```ts\n * const port = await probePort(0)\n * ```\n */\nexport async function probePort(port: number): Promise<number> {\n\tconst probe = createNetServer()\n\tconst listening = once(probe, 'listening')\n\tprobe.listen(port)\n\tawait listening\n\tconst address = probe.address()\n\tconst closed = once(probe, 'close')\n\tprobe.close()\n\tawait closed\n\t// This branch is unreachable through `listen(port)` and exists for the other members of `address()`'s union.\n\tif (!isAddressInfo(address)) {\n\t\tthrow new TypeError('server bound a listener with no resolvable AddressInfo')\n\t}\n\treturn address.port\n}\n\n/**\n * Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`\n * port where one is given and on an ephemeral port otherwise, reads the bound\n * port, closes the server, and resolves that port.\n *\n * @remarks\n * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)\n * and returns it. With a `preferred` port it tries that port first and\n * returns it when free; if already in use (`EADDRINUSE`) it falls back to an\n * ephemeral free port rather than rejecting — a caller always gets a usable\n * port. It binds then immediately closes a probe server, so the returned\n * port is free at the instant of the probe (an inherent TOCTOU race — bind it\n * promptly). Rejects only on an unexpected listen error other than a taken\n * `preferred` port (for example, a permission fault). A listener whose address is not\n * an {@link import('node:net').AddressInfo} — a pipe listener, which this\n * package's options cannot request — rejects with a `TypeError` rather than\n * reporting `0`, because `0` is this package's own request for an ephemeral\n * port and never means an unknown one.\n *\n * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒\n * fall back to an ephemeral port\n * @returns A free TCP port number\n * @throws {TypeError} When the bound listener's address carries no numeric port\n *\n * @example\n * ```ts\n * import { createServer, discoverPort } from '@src/server'\n *\n * const port = await discoverPort() // a guaranteed-free ephemeral port\n * ```\n */\nexport async function discoverPort(preferred?: number): Promise<number> {\n\tif (preferred === undefined) return probePort(0)\n\tconst probed = await settle(() => probePort(preferred))\n\tif (probed.success) return probed.value\n\tif (isCodedError(probed.error) && probed.error.code === 'EADDRINUSE') return probePort(0)\n\tthrow probed.error\n}\n\n/**\n * Builds the response an error boundary sends for a thrown value: an `HTTPError` whose status the\n * `Response` constructor admits keeps that status, and every other value renders a 500 whose\n * message stays hidden unless `expose` is `true`.\n *\n * @remarks\n * The renderer is total: it returns a `Response` for every value and never throws.\n * - An `HTTPError` whose status the `Response` constructor admits renders that status with its\n * message as the body, and with no body for a null body status (204, 205, and 304).\n * - Every other value renders 500: a throw that is no `HTTPError`, and an `HTTPError` whose status\n * no `Response` carries (an integer below 200 or above 599, which includes 101 and 103, or a\n * status that is not an integer). Its body is `Internal Server Error`, or the error's own message\n * when `expose` is `true` and the value is an `Error`.\n * - A thrown value is a fault to report when it is no `HTTPError`, or when the rendered status\n * differs from its `status`. The server's boundary reports those values with their\n * `RequestLine`, except a throw after the peer disconnected, which is no fault and reports\n * nothing.\n *\n * @param error - The thrown value\n * @param expose - If `true`, a 500 carries the message of the `Error` it renders; if `false`, it\n * carries `Internal Server Error`\n * @returns The response to send\n *\n * @example\n * ```ts\n * import { buildErrorResponse, HTTPError } from '@src/server'\n *\n * buildErrorResponse(new HTTPError(404, 'no such lamp'), false).status // 404\n * buildErrorResponse(new HTTPError(600, 'past the range'), false).status // 500\n * buildErrorResponse(new Error('database offline'), true).status // 500, body 'database offline'\n * ```\n */\nexport function buildErrorResponse(error: unknown, expose: boolean): Response {\n\tif (isHTTPError(error)) {\n\t\tconst rendered = attempt(() => {\n\t\t\tconst status = error.status\n\t\t\tconst full = attempt(() => new Response(error.message, { status }))\n\t\t\tconst response = full.success ? full.value : new Response(null, { status })\n\t\t\treturn response.status === status ? response : undefined\n\t\t})\n\t\tif (rendered.success && rendered.value !== undefined) return rendered.value\n\t}\n\tconst message = attempt(() => (expose && isError(error) ? error.message : undefined))\n\treturn new Response(\n\t\tmessage.success && isString(message.value) ? message.value : 'Internal Server Error',\n\t\t{ status: 500 },\n\t)\n}\n","import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js'\nimport {\n\tcomputeLanguageQuality,\n\tmatchMediaType,\n\tmergeVary,\n\tparseAcceptHeader,\n\tresolveCoding,\n} from './helpers.js'\n\n/**\n * Represents the content-negotiation machine over the weighted `Accept` family — a\n * reusable, cross-middleware entity rather than a middleware. Implements exactly\n * {@link NegotiatorInterface}.\n *\n * @remarks\n * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /\n * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its\n * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the\n * rest of the substrate uses — one parser, never two. A media type matches\n * case-insensitively. `format` reads the request `Accept`, negotiates a\n * {@link FormatHandlerMap}'s keys, and invokes the winner — or answers\n * `406 Not Acceptable` — and sets `Vary: Accept` on either answer.\n *\n * @example\n * ```ts\n * const negotiator = new Negotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport class Negotiator implements NegotiatorInterface {\n\tnegotiate(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tconst best = Iterator.from(available).reduce<\n\t\t\t{ readonly value: string; readonly q: number; readonly rank: number } | undefined\n\t\t>((previous, candidate) => {\n\t\t\tconst match = matchMediaType(entries, candidate)\n\t\t\tif (match === undefined) return previous\n\t\t\tconst { q, rank } = match\n\t\t\treturn q > (previous?.q ?? 0) ||\n\t\t\t\t(q === (previous?.q ?? 0) && rank < (previous?.rank ?? Number.POSITIVE_INFINITY))\n\t\t\t\t? { value: candidate, q, rank }\n\t\t\t\t: previous\n\t\t}, undefined)\n\t\treturn best?.value\n\t}\n\n\tencoding(header: string, available: readonly Encoding[]): Encoding | undefined {\n\t\tif (available.length === 0) return undefined\n\t\treturn resolveCoding(parseAcceptHeader(header), available)\n\t}\n\n\tlanguage(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tconst best = Iterator.from(available).reduce<\n\t\t\t{ readonly value: string; readonly quality: number } | undefined\n\t\t>((previous, candidate) => {\n\t\t\tconst quality = computeLanguageQuality(entries, candidate)\n\t\t\treturn quality > (previous?.quality ?? 0) ? { value: candidate, quality } : previous\n\t\t}, undefined)\n\t\treturn best?.value\n\t}\n\n\t/**\n\t * Dispatches the request to the handler its `Accept` header negotiates,\n\t * answering 406 when none matches.\n\t *\n\t * @remarks\n\t * Errors thrown by the negotiated handler propagate unmodified — the\n\t * server boundary classifies them, never this negotiator. The answer is a\n\t * copy of the handler's response carrying `Vary: Accept`.\n\t */\n\tasync format<TState>(\n\t\trequest: Request,\n\t\tcontext: MiddlewareContext<TState>,\n\t\thandlers: FormatHandlerMap<TState>,\n\t): Promise<Response> {\n\t\tconst keys = Object.keys(handlers)\n\t\tconst header = request.headers.get('accept')\n\t\tconst type = header === null ? keys[0] : this.negotiate(header, keys)\n\t\tconst handler = type === undefined ? undefined : handlers[type]\n\t\tif (handler === undefined) {\n\t\t\treturn new Response('Not Acceptable', { status: 406, headers: { Vary: 'Accept' } })\n\t\t}\n\t\tconst response = await handler(request, context)\n\t\tconst headers = new Headers(response.headers)\n\t\theaders.set('Vary', mergeVary(headers.get('vary') ?? undefined, 'Accept'))\n\t\treturn new Response(response.body, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t\theaders,\n\t\t})\n\t}\n}\n","import type { Server as NodeHTTPServer } from 'node:http'\nimport { once } from 'node:events'\nimport { isAddressInfo } from './validators.js'\n\n/**\n * Owns one startup attempt's listening subscription and validated bound port.\n *\n * @remarks\n * Create an instance per bind attempt. Subscribe before calling the native server's\n * `listen`, retain `pending` for failure cleanup, and record the native address after\n * listening settles. Reading `port` before a valid address was recorded throws.\n */\nexport class ServerBinding {\n\t#pending: Promise<readonly unknown[]> | undefined\n\t#port: number | undefined\n\n\tget pending(): Promise<readonly unknown[]> | undefined {\n\t\treturn this.#pending\n\t}\n\n\tget port(): number {\n\t\tif (this.#port === undefined) {\n\t\t\tthrow new TypeError('server bound a listener with no resolvable AddressInfo')\n\t\t}\n\t\treturn this.#port\n\t}\n\n\tsubscribe(server: NodeHTTPServer, signal: AbortSignal): Promise<readonly unknown[]> {\n\t\tconst pending = once(server, 'listening', { signal })\n\t\tthis.#pending = pending\n\t\treturn pending\n\t}\n\n\trecord(address: unknown): void {\n\t\tif (!isAddressInfo(address)) {\n\t\t\tthrow new TypeError('server bound a listener with no resolvable AddressInfo')\n\t\t}\n\t\tthis.#port = address.port\n\t}\n}\n","import type {\n\tIncomingMessage,\n\tServer as NodeHTTPServer,\n\tServerOptions as NodeHTTPServerOptions,\n\tServerResponse,\n} from 'node:http'\nimport type { AddressInfo, Socket } from 'node:net'\nimport type { Duplex } from 'node:stream'\nimport type { AbortInterface } from '@orkestrel/abort'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnection,\n\tConnectionStateFunction,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tRequestLine,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { addAbortListener, once } from 'node:events'\nimport { createServer as createHTTPServer } from 'node:http'\nimport { createAbort, linkSignal } from '@orkestrel/abort'\nimport { createTimeout, isTimeoutDuration } from '@orkestrel/timeout'\nimport { buildRequest, isEncryptedSocket, sendResponse } from '@orkestrel/router/server'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tattempt,\n\tisFiniteNumber,\n\tisFunction,\n\tisInteger,\n\tisPromise,\n\trefuseValue,\n\tsettle,\n} from '@orkestrel/contract'\nimport { buildErrorResponse, compose, iterateRequestBody } from './helpers.js'\nimport { isAddressInfo } from './validators.js'\nimport {\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tDEFAULT_HEADERS_TIMEOUT_MS,\n\tDEFAULT_REQUEST_TIMEOUT_MS,\n} from './constants.js'\nimport { HTTPError, isHTTPError, ServerError } from './errors.js'\nimport { ServerBinding } from './ServerBinding.js'\n\n/**\n * Represents the HTTP server facade — an observable `node:http` lifecycle composing this\n * module's own middleware onion around a consumed `@orkestrel/router`\n * dispatcher. Implements exactly {@link ServerInterface}.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n *\n * @remarks\n * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`\n * server, binds the configured {@link ServerOptions.host} / {@link\n * ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the\n * bound address), exposes that {@link AddressInfo} through `address`, observes\n * caller cancellation plus the configured `timeouts.start` deadline while the\n * bind is pending, and transitions `idle → starting → listening`. A\n * cancelled or expired bind closes its partial server and resets to `idle` for\n * another start. `stop()` transitions\n * to `stopping`: aborts the signal of every in-flight request so handlers\n * observe cancellation (a request that arrives during the drain is served\n * with its signal already aborted), drains in-flight requests and\n * claimed upgraded sockets up to the `drain` deadline (event-driven, no\n * busy-loop), then closes → `stopped`. After a clean drain the close\n * destroys every connection that carries no open request exchange, and a\n * connection that still carries one ends when its last exchange completes\n * or the same `drain` deadline expires, whichever comes first.\n * A request or an upgrade that such a connection sends after the listener\n * closes is refused: its connection is destroyed before the request is\n * counted or a handler sees it, so the `stop()` call waits only on work\n * counted before the close. After an expired drain the close destroys every\n * socket. A `stop()` call made while a stop runs returns that stop's\n * promise. `destroy()` is the idempotent final teardown.\n * - **Per request.** The exchange's own `AbortController` joins the\n * in-flight registry until the response's `close`; the one\n * `Request` of the exchange is built through the router's `buildRequest`\n * with that controller's signal, so `request.signal` aborts on a peer\n * disconnect, on `context.abort(reason)`, or on `stop()`, and no request\n * signal links to a signal that outlives the exchange; `context.state` is\n * built through {@link ServerOptions.state} from the connection facts, which\n * `context.connection` carries as the same object; the composed middleware\n * onion runs, terminating in `dispatcher.handle`; the result is written\n * back through `sendResponse`.\n * - **The built-in boundary** wraps the whole per-request chain, including\n * setup: `buildRequest` runs behind its own inner boundary that maps a\n * throw (for example, a malformed `Host` header) to a silent `400` with no\n * `error` emit; everything after (connection\n * facts, `state`, the composed onion, and `dispatcher.handle`) runs\n * behind the outer boundary, which renders a throw through\n * `buildErrorResponse`: an `HTTPError` whose status `Response` admits\n * keeps that status, with no body for 204, 205, and 304, and every other\n * throw renders `500` (message hidden unless `expose`). Each fault, every\n * throw except an `HTTPError` whose status the response carries and a\n * throw after a peer disconnect the server read first (the peer's FIN or a\n * reset), reaches `error` and `report` with its\n * `RequestLine`; a fault on the inner phase's `400` path carries none,\n * because no `Request` exists there. A `report` that throws or rejects is\n * contained, except a rejected native promise whose species constructor\n * cannot build a promise, which reaches `unhandledRejection` (see\n * `ServerOptions.report`). A write that fails destroys the connection and is a fault, unless the peer disconnected first,\n * and a terminal catch over the whole exchange, the `400` path included,\n * holds a throw from any step.\n * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a\n * throwing handler is treated as declined and surfaced on `error`, an\n * unclaimed upgrade destroys the socket), bound per-run to this instance.\n * A claimed socket joins `#upgraded` until it closes: the claimant still\n * owns it, and the tracking exists because Node detaches an upgraded socket\n * from the set its own close calls walk, so nothing else can end it.\n * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}\n * exposed as `readonly emitter`; the emitter isolates a listener throw and\n * routes it to the `error` option rather than to the domain `error` event.\n */\nexport class Server<TState> implements ServerInterface<TState> {\n\treadonly #id: string\n\treadonly #dispatcher: DispatcherInterface<TState>\n\treadonly #state: ConnectionStateFunction<TState>\n\treadonly #middleware: Array<MiddlewareHandler<TState>>\n\treadonly #upgradeHandlers: UpgradeHandler[] = []\n\treadonly #upgraded = new Set<Duplex>()\n\treadonly #requests = new Set<AbortController>()\n\treadonly #exchanges = new Map<Socket, Map<ServerResponse, () => void>>()\n\treadonly #emitter: Emitter<ServerEventMap>\n\treadonly #host: string | undefined\n\treadonly #configuredPort: number | undefined\n\treadonly #drain: number\n\treadonly #limit: number\n\treadonly #expose: boolean\n\treadonly #report: ((error: unknown, request?: RequestLine) => void) | undefined\n\treadonly #startup: number | undefined\n\treadonly #options: NodeHTTPServerOptions\n\treadonly #sockets: {\n\t\treadonly connections?: number\n\t\treadonly headers?: number\n\t\treadonly requests?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#binding: AbortInterface | undefined\n\t#wakeup: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#stopping: Promise<void> | undefined\n\n\tconstructor(options: ServerOptions<TState>) {\n\t\trefuseValue(options.state, isFunction, 'Server', {\n\t\t\tpath: ['options', 'state'],\n\t\t\tlimit: 'a function',\n\t\t\tcode: 'placement',\n\t\t})\n\t\tif (options.report !== undefined) {\n\t\t\trefuseValue(options.report, isFunction, 'Server', {\n\t\t\t\tpath: ['options', 'report'],\n\t\t\t\tlimit: 'a function',\n\t\t\t\tcode: 'placement',\n\t\t\t})\n\t\t}\n\t\tconst drain = options.drain ?? DEFAULT_DRAIN_MS\n\t\trefuseValue(drain, isTimeoutDuration, 'Server', {\n\t\t\tpath: ['options', 'drain'],\n\t\t\tlimit: 'an integer from 0 through 2_147_483_647',\n\t\t\tcode: 'range',\n\t\t})\n\t\tconst limit = options.limit ?? DEFAULT_BODY_LIMIT\n\t\trefuseValue(limit, (value): value is number => isFiniteNumber(value) && value >= 0, 'Server', {\n\t\t\tpath: ['options', 'limit'],\n\t\t\tlimit: 'a non-negative finite number',\n\t\t\tcode: 'range',\n\t\t})\n\t\tconst timeouts = options.timeouts ?? {}\n\t\tfor (const [name, value] of Object.entries(timeouts)) {\n\t\t\t// Node arms `keepalive` plus its default 1_000 ms `keepAliveTimeoutBuffer` as one timer.\n\t\t\tif (value === undefined) continue\n\t\t\tif (name === 'keepalive') {\n\t\t\t\trefuseValue(\n\t\t\t\t\tvalue,\n\t\t\t\t\t(candidate): candidate is number =>\n\t\t\t\t\t\tisTimeoutDuration(candidate) && isTimeoutDuration(candidate + 1_000),\n\t\t\t\t\t'Server',\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: ['options', 'timeouts', name],\n\t\t\t\t\t\tlimit: 'an integer from 0 through 2_147_482_647',\n\t\t\t\t\t\tcode: 'range',\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\trefuseValue(value, isTimeoutDuration, 'Server', {\n\t\t\t\t\tpath: ['options', 'timeouts', name],\n\t\t\t\t\tlimit: 'an integer from 0 through 2_147_483_647',\n\t\t\t\t\tcode: 'range',\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\t// Node's own defaults, so the relation and the checking interval read the values Node enforces.\n\t\tconst request = timeouts.request ?? DEFAULT_REQUEST_TIMEOUT_MS\n\t\tconst headers = timeouts.headers ?? Math.min(DEFAULT_HEADERS_TIMEOUT_MS, request)\n\t\trefuseValue(\n\t\t\theaders,\n\t\t\t(value): value is number => !(request > 0 && Number(value) > request),\n\t\t\t'Server',\n\t\t\t{\n\t\t\t\tpath: ['options', 'timeouts', 'headers'],\n\t\t\t\tlimit:\n\t\t\t\t\t'no greater than options.timeouts.request (300_000 when omitted) while it is positive',\n\t\t\t\tcode: 'range',\n\t\t\t},\n\t\t)\n\t\tconst checked = [headers, request].filter((ms) => ms > 0)\n\t\tconst sockets = options.sockets ?? {}\n\t\tfor (const [name, value] of Object.entries(sockets)) {\n\t\t\tif (value === undefined) continue\n\t\t\trefuseValue(\n\t\t\t\tvalue,\n\t\t\t\t(candidate): candidate is number => isInteger(candidate) && candidate >= 0,\n\t\t\t\t'Server',\n\t\t\t\t{\n\t\t\t\t\tpath: ['options', 'sockets', name],\n\t\t\t\t\tlimit: 'a non-negative integer',\n\t\t\t\t\tcode: 'range',\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tthis.#id = crypto.randomUUID()\n\t\tthis.#dispatcher = options.dispatcher\n\t\tthis.#state = options.state\n\t\tthis.#middleware = options.middleware === undefined ? [] : [...options.middleware]\n\t\tthis.#host = options.host\n\t\tthis.#configuredPort = options.port\n\t\tthis.#drain = drain\n\t\tthis.#limit = limit\n\t\tthis.#expose = options.expose ?? false\n\t\tthis.#report = options.report\n\t\tthis.#startup = timeouts.start\n\t\tthis.#options = {\n\t\t\theadersTimeout: headers,\n\t\t\trequestTimeout: request,\n\t\t\t...(timeouts.keepalive === undefined ? {} : { keepAliveTimeout: timeouts.keepalive }),\n\t\t\t...(checked.length === 0\n\t\t\t\t? {}\n\t\t\t\t: { connectionsCheckingInterval: Math.ceil(Math.min(...checked) / 2) }),\n\t\t}\n\t\tthis.#sockets = sockets\n\t\tthis.#emitter = new Emitter<ServerEventMap>({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\tget id(): string {\n\t\treturn this.#id\n\t}\n\n\tget status(): ServerStatus {\n\t\treturn this.#status\n\t}\n\n\tget port(): number | undefined {\n\t\treturn this.#port\n\t}\n\n\tget address(): AddressInfo | undefined {\n\t\tconst address = this.#http?.address()\n\t\treturn isAddressInfo(address) ? address : undefined\n\t}\n\n\tget dispatcher(): DispatcherInterface<TState> {\n\t\treturn this.#dispatcher\n\t}\n\n\tget emitter(): EmitterInterface<ServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tuse(middleware: MiddlewareHandler<TState>): void\n\tuse(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void\n\tuse(middleware: MiddlewareHandler<TState> | ReadonlyArray<MiddlewareHandler<TState>>): void {\n\t\tif (typeof middleware === 'function') this.#middleware.push(middleware)\n\t\telse this.#middleware.push(...middleware)\n\t}\n\n\tupgrade(handler: UpgradeHandler): void {\n\t\tthis.#upgradeHandlers.push(handler)\n\t}\n\n\tstart(signal?: AbortSignal): Promise<number> {\n\t\tif (this.#status !== 'idle' && this.#status !== 'stopped') {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew ServerError('STATUS', `server cannot start from '${this.#status}'`, {\n\t\t\t\t\tstatus: this.#status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tthis.#status = 'starting'\n\t\tconst server = createHTTPServer(this.#options, (request, response) =>\n\t\t\tthis.#handle(request, response),\n\t\t)\n\t\tif (this.#sockets.connections !== undefined) server.maxConnections = this.#sockets.connections\n\t\tif (this.#sockets.headers !== undefined) server.maxHeadersCount = this.#sockets.headers\n\t\tif (this.#sockets.requests !== undefined) server.maxRequestsPerSocket = this.#sockets.requests\n\t\t// Bound to this run's server instance, discarded with it on stop/restart —\n\t\t// no manual removal needed (the same per-run lifecycle as the request\n\t\t// handler `createHTTPServer` takes).\n\t\tserver.on('upgrade', (request, socket, head) => this.#onUpgrade(request, socket, head))\n\t\tserver.on('connection', (socket) => this.#trackConnection(socket))\n\t\tthis.#http = server\n\t\treturn this.#listen(server, signal)\n\t}\n\n\t// A call during a stop returns the stop in flight, so every caller resolves\n\t// after the same close; the field is released only by the stop that set it.\n\t// The promise is published before the stop's synchronous prologue, because\n\t// that prologue emits `stop` and aborts every in-flight request's signal, and\n\t// a listener on either can call this method.\n\tstop(): Promise<void> {\n\t\tif (this.#status !== 'listening') return this.#stopping ?? Promise.resolve()\n\t\tconst { promise, resolve, reject } = Promise.withResolvers<void>()\n\t\tthis.#stopping = promise\n\t\tvoid this.#stopGracefully()\n\t\t\t.finally(() => {\n\t\t\t\tif (this.#stopping === promise) this.#stopping = undefined\n\t\t\t})\n\t\t\t.then(resolve, reject)\n\t\treturn promise\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#status === 'stopped' && this.#http === undefined) {\n\t\t\tthis.#emitter.destroy()\n\t\t\treturn\n\t\t}\n\t\tthis.#status = 'stopped'\n\t\tthis.#binding?.abort(\n\t\t\tnew ServerError('STATUS', 'server destroyed while starting', { status: 'starting' }),\n\t\t)\n\t\tfor (const exchange of this.#requests) exchange.abort()\n\t\tconst server = this.#http\n\t\tif (server !== undefined) await this.#close(server, true)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// One `drain` deadline bounds the whole stop: it bounds the drain, then\n\t// stays armed through the clean close's wait on open exchanges, and its\n\t// expiry cuts what is still held as an expired drain does. It is a pure\n\t// clock rather than a child of any signal, because a parent abort clears\n\t// a `Timeout` instead of expiring it.\n\tasync #stopGracefully(): Promise<void> {\n\t\tthis.#status = 'stopping'\n\t\tthis.#emitter.emit('stop')\n\t\tconst server = this.#http\n\t\tfor (const exchange of this.#requests) exchange.abort()\n\t\tconst deadline: TimeoutInterface = createTimeout({ ms: this.#drain })\n\t\tdeadline.start()\n\t\ttry {\n\t\t\tawait this.#drainPending(deadline.signal)\n\t\t\tconst pending = this.#requests.size\n\t\t\tconst upgraded = this.#upgraded.size\n\t\t\tthis.#emitter.emit('drain', pending, upgraded)\n\t\t\tif (server !== undefined) {\n\t\t\t\tconst relay = addAbortListener(deadline.signal, () => this.#cut(server))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#close(server, pending + upgraded > 0)\n\t\t\t\t} finally {\n\t\t\t\t\trelay[Symbol.dispose]()\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tdeadline.clear()\n\t\t}\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t}\n\n\t// Register the exchange's abort handle for draining first — before anything\n\t// that can throw — so the sync listener itself never throws; the rest of\n\t// setup (which can throw on a malformed request) is deferred into the async\n\t// `#accept` entry, kept behind the built-in boundary. A request that arrives\n\t// while the drain runs is registered already aborted. A request parsed after\n\t// the close on a connection an open exchange still holds is not counted\n\t// work, so its connection is destroyed before the request counts or runs.\n\t#handle(message: IncomingMessage, response: ServerResponse): void {\n\t\tif (this.#closed) {\n\t\t\tmessage.socket.destroy()\n\t\t\treturn\n\t\t}\n\t\tconst exchange = new AbortController()\n\t\tconst disconnect = new AbortController()\n\t\tconst release = this.#register(exchange)\n\t\tif (this.#status === 'stopping') exchange.abort()\n\t\t// Only the connection tells a peer disconnect from a close the server or Node made.\n\t\tconst socket = message.socket\n\t\tresponse.once('close', () => this.#latch(socket, response, disconnect, release))\n\t\tvoid this.#trackExchange(message, response, () => {\n\t\t\tthis.#latch(socket, response, disconnect, release)\n\t\t\texchange.abort()\n\t\t})\n\t\tvoid this.#accept(message, response, exchange, disconnect.signal)\n\t}\n\n\t// Latch the peer disconnect the socket shows, an error on the response excluded, then release the exchange.\n\t#latch(\n\t\tsocket: Socket,\n\t\tresponse: ServerResponse,\n\t\tdisconnect: AbortController,\n\t\trelease: () => void,\n\t): void {\n\t\tconst failure = socket.errored\n\t\tconst reset = failure !== null && 'code' in failure && failure.code === 'ECONNRESET'\n\t\tif (!response.writableEnded && response.errored === null && (socket.readableEnded || reset))\n\t\t\tdisconnect.abort()\n\t\trelease()\n\t}\n\n\t// The terminal catch: a throw here, the inner phase's `400` included, has no `RequestLine`.\n\tasync #accept(\n\t\tmessage: IncomingMessage,\n\t\tresponse: ServerResponse,\n\t\texchange: AbortController,\n\t\tdisconnect: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tconst created = attempt(() => buildRequest(message, { response, signal: exchange.signal }))\n\t\t\tif (created.success) await this.#serve(created.value, message, response, exchange, disconnect)\n\t\t\telse\n\t\t\t\tawait this.#respond(\n\t\t\t\t\tbuildErrorResponse(new HTTPError(400, 'invalid request'), false),\n\t\t\t\t\tresponse,\n\t\t\t\t)\n\t\t} catch (error) {\n\t\t\tresponse.destroy()\n\t\t\tthis.#fault(error, undefined)\n\t\t}\n\t}\n\n\t// The terminal catch of an exchange whose `Request` exists, so its faults carry the line.\n\tasync #serve(\n\t\trequest: Request,\n\t\tmessage: IncomingMessage,\n\t\tresponse: ServerResponse,\n\t\texchange: AbortController,\n\t\tdisconnect: AbortSignal,\n\t): Promise<void> {\n\t\tconst line: RequestLine = { method: request.method, url: new URL(request.url) }\n\t\tconst start = performance.now()\n\t\ttry {\n\t\t\tthis.#emitter.emit('request', line.method, line.url.pathname)\n\t\t\tconst result = await this.#run(request, line, message, exchange, disconnect)\n\t\t\tconst sent = await this.#respond(result, response, line, disconnect)\n\t\t\t// A body-less answer after a disconnect still reaches `finish`, so the latch decides.\n\t\t\tif (sent && !disconnect.aborted) {\n\t\t\t\tthis.#emitter.emit('response', {\n\t\t\t\t\tmethod: line.method,\n\t\t\t\t\tpathname: line.url.pathname,\n\t\t\t\t\tstatus: result.status,\n\t\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresponse.destroy()\n\t\t\tthis.#fault(error, line)\n\t\t}\n\t}\n\n\t// A returned status no `Response` carries, as from `Response.error()`, is thrown to render 500.\n\tasync #run(\n\t\trequest: Request,\n\t\tline: RequestLine,\n\t\tmessage: IncomingMessage,\n\t\texchange: AbortController,\n\t\tdisconnect: AbortSignal,\n\t): Promise<Response> {\n\t\ttry {\n\t\t\tconst ip = message.socket.remoteAddress\n\t\t\tconst connection: Connection = {\n\t\t\t\t...(ip === undefined ? {} : { ip }),\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl: line.url,\n\t\t\t\tmethod: line.method,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tconnection,\n\t\t\t\tbody: this.#createBody(request),\n\t\t\t\tabort: exchange.abort.bind(exchange),\n\t\t\t}\n\t\t\tconst runner = compose(this.#middleware, (currentRequest, currentContext) =>\n\t\t\t\tthis.#dispatcher.handle(currentRequest, currentContext.state),\n\t\t\t)\n\t\t\tconst result = await runner(request, context)\n\t\t\tconst status = result.status\n\t\t\tif (isInteger(status) && status >= 200 && status <= 599) return result\n\t\t\tthrow new HTTPError(status, `a handler returned status ${String(status)}`)\n\t\t} catch (error) {\n\t\t\treturn this.#boundary(error, line, disconnect.aborted)\n\t\t}\n\t}\n\n\t// A failed write destroys the connection and is a fault, unless the peer disconnected first.\n\tasync #respond(\n\t\tresult: Response,\n\t\tresponse: ServerResponse,\n\t\tline?: RequestLine,\n\t\tdisconnect?: AbortSignal,\n\t): Promise<boolean> {\n\t\tconst sent = await settle(() => sendResponse(result, response))\n\t\tif (!sent.success) {\n\t\t\tresponse.destroy()\n\t\t\tif (disconnect?.aborted !== true) this.#fault(sent.error, line)\n\t\t\treturn false\n\t\t}\n\t\treturn response.writableFinished\n\t}\n\n\t#boundary(error: unknown, line: RequestLine, disconnected: boolean): Response {\n\t\tconst rendered = buildErrorResponse(error, this.#expose)\n\t\tconst carried = attempt(() => isHTTPError(error) && error.status === rendered.status)\n\t\tif (!disconnected && !(carried.success && carried.value)) this.#fault(error, line)\n\t\treturn rendered\n\t}\n\n\t// `then.call` skips a promise's own `then`; `attempt` holds a throwing `constructor` getter.\n\t#fault(error: unknown, line: RequestLine | undefined): void {\n\t\tif (line === undefined) this.#emitter.emit('error', error)\n\t\telse this.#emitter.emit('error', error, line)\n\t\tconst report = this.#report\n\t\tif (report === undefined) return\n\t\tconst reported = attempt((): unknown => report(error, line))\n\t\tif (!reported.success) return\n\t\tconst value = reported.value\n\t\tattempt(() =>\n\t\t\tisPromise(value)\n\t\t\t\t? Promise.prototype.then.call(value, undefined, () => undefined)\n\t\t\t\t: Promise.resolve(value).catch(() => undefined),\n\t\t)\n\t}\n\n\t// Fan a raw protocol-upgrade out to the registered handlers in\n\t// registration order: the first to return `true` claims the socket. A\n\t// throwing handler is treated as declined — surfaced on `error` — and the\n\t// fan-out continues so a later handler can still claim. Unclaimed ⇒ the\n\t// socket is destroyed so an unhandled upgrade never leaks a connection.\n\t// An upgrade parsed after the close is refused the way the `#handle` method\n\t// refuses a request: its socket is destroyed before any handler sees it.\n\t#onUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {\n\t\tif (this.#closed) {\n\t\t\tsocket.destroy()\n\t\t\treturn\n\t\t}\n\t\tconst handled = Iterator.from(this.#upgradeHandlers).some((handler) => {\n\t\t\ttry {\n\t\t\t\treturn handler(request, socket, head)\n\t\t\t} catch (error) {\n\t\t\t\tthis.#emitter.emit('error', error)\n\t\t\t\treturn false\n\t\t\t}\n\t\t})\n\t\tif (handled) this.#trackSocket(socket)\n\t\telse socket.destroy()\n\t\tthis.#emitter.emit('upgrade', request, handled)\n\t}\n\n\tasync #listen(server: NodeHTTPServer, signal?: AbortSignal): Promise<number> {\n\t\tconst deadline = this.#startup === undefined ? undefined : createTimeout({ ms: this.#startup })\n\t\tconst startup = deadline === undefined ? signal : linkSignal(deadline.signal, signal)\n\t\tconst binding = createAbort()\n\t\tthis.#binding = binding\n\t\tconst relay =\n\t\t\tstartup === undefined\n\t\t\t\t? undefined\n\t\t\t\t: addAbortListener(startup, () => binding.abort(startup.reason))\n\t\tconst operation = new ServerBinding()\n\t\t// The bound port, read inside the `try` so an address carrying none takes\n\t\t// the same cleanup path a failed bind takes. `0` is this package's request\n\t\t// for an ephemeral port, so it can never stand in for an unknown one.\n\t\ttry {\n\t\t\tsignal?.throwIfAborted()\n\t\t\tdeadline?.start()\n\t\t\tif (deadline?.ms === 0 && startup !== undefined) await once(startup, 'abort')\n\t\t\tstartup?.throwIfAborted()\n\t\t\tconst listening = operation.subscribe(server, binding.signal)\n\t\t\tif (startup === undefined) server.listen(this.#configuredPort ?? 0, this.#host)\n\t\t\telse {\n\t\t\t\tserver.listen({\n\t\t\t\t\tport: this.#configuredPort ?? 0,\n\t\t\t\t\t...(this.#host === undefined ? {} : { host: this.#host }),\n\t\t\t\t\tsignal: binding.signal,\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait listening\n\t\t\tif (this.#status !== 'starting') {\n\t\t\t\tthrow new ServerError('STATUS', 'server destroyed while starting', {\n\t\t\t\t\tstatus: this.#status,\n\t\t\t\t})\n\t\t\t}\n\t\t\toperation.record(server.address())\n\t\t} catch (error) {\n\t\t\tconst destroyed = this.#status === 'stopped'\n\t\t\tconst expired = deadline?.expired === true\n\t\t\tconst cancelled = startup?.aborted === true\n\t\t\t// A cancellation removes `events.once`'s temporary error listener. Keep\n\t\t\t// the discarded server guarded while a simultaneous late bind error\n\t\t\t// settles so it cannot escape as an uncaught process error.\n\t\t\tserver.on('error', () => undefined)\n\t\t\tbinding.abort(error)\n\t\t\tconst listening = operation.pending\n\t\t\tif (listening !== undefined) await listening.catch(() => undefined)\n\t\t\tif (!destroyed) {\n\t\t\t\tawait this.#close(server, true)\n\t\t\t\tthis.#http = undefined\n\t\t\t\tthis.#port = undefined\n\t\t\t\tthis.#status = 'idle'\n\t\t\t}\n\t\t\tif (destroyed) {\n\t\t\t\tthrow new ServerError('STATUS', 'server destroyed while starting', { status: 'starting' })\n\t\t\t}\n\t\t\tif (expired && deadline !== undefined) {\n\t\t\t\tthrow new DOMException(\n\t\t\t\t\t`Server startup exceeded ${deadline.ms} milliseconds`,\n\t\t\t\t\t'TimeoutError',\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (cancelled && startup !== undefined) throw startup.reason\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tif (this.#binding === binding) this.#binding = undefined\n\t\t\trelay?.[Symbol.dispose]()\n\t\t\tdeadline?.clear()\n\t\t}\n\t\tconst port = operation.port\n\t\tthis.#port = port\n\t\tthis.#status = 'listening'\n\t\tthis.#emitter.emit('start', port)\n\t\treturn port\n\t}\n\n\t#createBody(request: Request): () => Promise<unknown> {\n\t\tconst bodies = iterateRequestBody(request, this.#limit)\n\t\treturn () => bodies.next().value\n\t}\n\n\t// Close the underlying server, resolving after the listener closes, which\n\t// Node does only after every connection has closed. A clean close (the\n\t// drain settled) destroys every connection with no open exchange: one that\n\t// never sent a request, one partway through a header block, and an idle\n\t// keep-alive one. That covers every connection `closeIdleConnections()`\n\t// ends, which `server.close()` also calls itself. A connection with an open\n\t// exchange, such as one whose body still uploads after its response, stays\n\t// open, because destroying it can reset the connection and lose that\n\t// response; the `#trackExchange` method ends it when its count returns to\n\t// zero, and the stop's deadline cuts it if that comes first. A forced close\n\t// (the drain deadline expired, `destroy`, or a failed bind) cuts at once.\n\t#close(server: NodeHTTPServer, force: boolean): Promise<void> {\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tserver.close(() => resolve())\n\t\t\tif (force) this.#cut(server)\n\t\t\telse for (const [socket, open] of this.#exchanges) if (open.size === 0) socket.destroy()\n\t\t})\n\t}\n\n\t// Destroy every socket. A protocol-upgraded socket needs the extra loop:\n\t// Node detaches it from the connection set `closeAllConnections()` walks,\n\t// so that call never reaches it while `server.close()` still waits on it.\n\t#cut(server: NodeHTTPServer): void {\n\t\tserver.closeAllConnections()\n\t\tfor (const socket of this.#upgraded) socket.destroy()\n\t}\n\n\t// Count a connection's open exchanges from its accept to its close, so a\n\t// clean close can find the connections that carry none.\n\t// Node never closes a queued (pipelined) response whose connection ended, so the socket's close\n\t// settles each exchange that still has no socket assigned; an active response settles from its own close.\n\t#trackConnection(socket: Socket): void {\n\t\tconst open = new Map<ServerResponse, () => void>()\n\t\tthis.#exchanges.set(socket, open)\n\t\tsocket.once('close', () => {\n\t\t\tfor (const [response, release] of open) if (response.socket === null) release()\n\t\t\tthis.#exchanges.delete(socket)\n\t\t})\n\t}\n\n\t// Count one exchange open on its connection until both its request message\n\t// and its response have closed; a count, not a flag, because a pipelining\n\t// client holds several at once. Each closes after it ends or is destroyed,\n\t// so one `close` listener apiece covers both paths and leaves when it fires.\n\t// While a clean close waits, the connection ends as its count returns to\n\t// zero. Node's `requestTimeout` bounds an upload that keeps sending after\n\t// its response unless `timeouts.request` is 0; then only the stop's\n\t// deadline does.\n\tasync #trackExchange(\n\t\tmessage: IncomingMessage,\n\t\tresponse: ServerResponse,\n\t\trelease: () => void,\n\t): Promise<void> {\n\t\tconst socket = message.socket\n\t\tconst open = this.#exchanges.get(socket)\n\t\tif (open === undefined) return\n\t\topen.set(response, release)\n\t\tawait Promise.all([\n\t\t\tnew Promise((resolve) => message.once('close', resolve)),\n\t\t\tnew Promise((resolve) => response.once('close', resolve)),\n\t\t])\n\t\topen.delete(response)\n\t\tif (open.size === 0 && this.#exchanges.get(socket) === open && this.#closed) socket.destroy()\n\t}\n\n\t// The listener has closed while the server stops, so the drain has settled\n\t// and no further request or upgrade is counted work. Derived, so it cannot\n\t// drift from the status and the listener it reads.\n\tget #closed(): boolean {\n\t\treturn this.#status === 'stopping' && this.#http?.listening === false\n\t}\n\n\t// Everything `stop()` has to drain: in-flight requests plus the upgraded\n\t// sockets handlers claimed. Derived, so the two counters can never drift\n\t// out of step with a third stored flag.\n\tget #inflight(): number {\n\t\treturn this.#requests.size + this.#upgraded.size\n\t}\n\n\t// Arm a fresh drain wakeup when the server goes from settled to busy.\n\t// Called before the new unit is counted, so a zero here means nothing was\n\t// in flight yet. The invariant this pair holds — `#wakeup` is un-aborted\n\t// whenever `#inflight` is positive — is what lets `#drainPending` park on\n\t// it without racing a wakeup that already fired.\n\t#enter(): void {\n\t\tif (this.#inflight === 0) this.#wakeup = createAbort()\n\t}\n\n\t// Fire the current drain wakeup after the last unit of drainable work has\n\t// left. Called after that unit is uncounted — event-driven, never a\n\t// busy-loop.\n\t#settle(): void {\n\t\tif (this.#inflight === 0) this.#wakeup.abort()\n\t}\n\n\t// Register one in-flight exchange's abort handle; returns the idempotent\n\t// removal its response's `close` runs.\n\t#register(exchange: AbortController): () => void {\n\t\tthis.#enter()\n\t\tthis.#requests.add(exchange)\n\t\treturn () => {\n\t\t\tif (this.#requests.delete(exchange)) this.#settle()\n\t\t}\n\t}\n\n\t// Track one claimed upgraded socket for the duration of its life. The\n\t// claiming handler still owns the socket — this only watches it, so the\n\t// stop path can drain it like a request and cut it if the deadline wins.\n\t// An already-dead socket never enters (nothing would ever untrack it).\n\t#trackSocket(socket: Duplex): void {\n\t\tif (socket.destroyed || this.#upgraded.has(socket)) return\n\t\tthis.#enter()\n\t\tthis.#upgraded.add(socket)\n\t\tsocket.once('close', () => {\n\t\t\tthis.#upgraded.delete(socket)\n\t\t\tthis.#settle()\n\t\t})\n\t}\n\n\t// Park until every in-flight request and claimed upgraded socket is gone\n\t// OR `signal` fires — event-driven (wake-park), no polling.\n\tasync #drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#inflight === 0 || signal.aborted) return\n\t\tawait once(AbortSignal.any([signal, this.#wakeup.signal]), 'abort')\n\t}\n}\n","import type { KeyObject } from 'node:crypto'\nimport type { SignerInterface, TokenSecret } from './types.js'\nimport { createHmac, createSecretKey, timingSafeEqual } from 'node:crypto'\nimport { decodeBase64URL, encodeBase64URL } from '@orkestrel/codec'\nimport { normalizeSecret } from './helpers.js'\n\n/**\n * Represents an HMAC-SHA256 signer that creates one `node:crypto` key per secret at\n * construction and reuses it on every call. Implements exactly {@link SignerInterface}.\n *\n * @remarks\n * The constructor normalizes the secret through {@link normalizeSecret}, so it\n * throws a {@link ServerError} of code `'SECRET'` for a secret that is not a\n * string or a list of strings, an empty list, or a list holding a blank entry.\n * `verify` compares signature bytes only through `timingSafeEqual`, after a\n * length check.\n *\n * @example\n * ```ts\n * import { Signer } from '@orkestrel/server'\n *\n * const signer = new Signer(['current-secret', 'previous-secret'])\n * await signer.verify('payload', await signer.sign('payload')) // true\n * ```\n */\nexport class Signer implements SignerInterface {\n\treadonly #keys: readonly [KeyObject, ...KeyObject[]]\n\n\tconstructor(secret: TokenSecret) {\n\t\tconst [current, ...older] = normalizeSecret(secret)\n\t\tthis.#keys = [\n\t\t\tcreateSecretKey(current, 'utf8'),\n\t\t\t...older.map((entry) => createSecretKey(entry, 'utf8')),\n\t\t]\n\t}\n\n\tasync sign(message: string): Promise<string> {\n\t\tconst [key] = this.#keys\n\t\treturn encodeBase64URL(createHmac('sha256', key).update(message, 'utf8').digest())\n\t}\n\n\tasync verify(message: string, signature: string): Promise<boolean> {\n\t\tconst bytes = decodeBase64URL(signature)\n\t\t// 32 is the byte length of an HMAC-SHA256; `timingSafeEqual` throws on unequal lengths.\n\t\tif (bytes === undefined || bytes.byteLength !== 32) return false\n\t\treturn this.#keys.some((key) =>\n\t\t\ttimingSafeEqual(createHmac('sha256', key).update(message, 'utf8').digest(), bytes),\n\t\t)\n\t}\n}\n","import type { SSEMessage, SSEStreamInterface, StreamOptions } from './types.js'\nimport { serializeComment, serializeEvent } from './helpers.js'\nimport { SSE_HEADERS } from './constants.js'\n\n/**\n * Represents the Server-Sent-Events handle over an open, fetch-standard streaming\n * `Response`. Implements exactly {@link SSEStreamInterface}.\n *\n * @remarks\n * Builds the `Response` at construction from\n * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`\n * merged over them, at `options.status` (default `200`). A caller repeating one\n * of those keys therefore replaces the seam's value, in any casing. The\n * instance owns the stream's\n * controller, its text encoder, the closed flag, and the parked producer's\n * wakeup, so the whole handle is one entity rather than a closure over four\n * bindings.\n *\n * The stream opens with one comment line ({@link serializeComment}), so the\n * response pump has a first chunk and the headers leave before any event.\n * `write` serializes one message ({@link serializeEvent}), enqueues it, and\n * returns whether the controller still has positive desired size; on an open\n * stream it throws the `ServerError` `serializeEvent` raises for a refused\n * field and enqueues nothing. A producer\n * receiving `false` awaits `drain()`; that promise resolves on the next\n * consumer pull restoring capacity, or on stream closure. `comment` writes a\n * `: text` keep-alive line per line of its text, which a conforming SSE parser\n * ignores; `end` closes the stream. Every method is a safe no-op while `closed`\n * (ended by `end()`, or the consumer cancelled the stream), so a late write\n * never throws.\n *\n * The readiness signal reflects only the process-local `ReadableStream`\n * queue — it is not proof that a remote peer consumed bytes. When the response\n * pump honors its socket sink's drain state, socket pressure stops body pulls\n * and therefore keeps this queue full, letting a cooperative producer bound\n * its buffering. Ignoring the return value preserves an unconditional-enqueue\n * producer. The default stream strategy counts chunks rather than their byte\n * length, so a byte-bounded producer must also cap each message. Return\n * `response` before awaiting a `false` write or `drain()`, because the consumer\n * cannot pull until it receives the response, and the opening comment fills\n * the queue, so a `drain()` before any write also waits on that pull.\n *\n * @example\n * ```ts\n * import { Stream } from '@src/server'\n *\n * const stream = new Stream()\n * void Promise.resolve().then(async () => {\n * \tif (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()\n * \tstream.comment('keep-alive')\n * \tstream.end()\n * })\n * // return stream.response from the route handler\n * ```\n */\nexport class Stream implements SSEStreamInterface {\n\treadonly #encoder = new TextEncoder()\n\treadonly #response: Response\n\t#controller: ReadableStreamDefaultController<Uint8Array> | undefined\n\t#closed = false\n\t#wakeup: PromiseWithResolvers<void> | undefined\n\n\tconstructor(options?: StreamOptions) {\n\t\t// The underlying source is a table of bound methods rather than inline\n\t\t// callbacks: every branch it names reaches `#` state, and instance-bound\n\t\t// work belongs in a method rather than in a function nested here.\n\t\tconst body = new ReadableStream<Uint8Array>({\n\t\t\tstart: this.#attach.bind(this),\n\t\t\tpull: this.#pull.bind(this),\n\t\t\tcancel: this.#cancel.bind(this),\n\t\t})\n\t\t// `Headers.set` matches a field name case-insensitively and replaces every\n\t\t// existing value, so any spelling of a seam-owned key wins. An object\n\t\t// spread would resolve the collision case-sensitively and leave `Headers`\n\t\t// to append the re-cased spelling into one comma-joined value.\n\t\tconst headers = new Headers(SSE_HEADERS)\n\t\tfor (const [name, value] of Object.entries(options?.headers ?? {})) headers.set(name, value)\n\t\tthis.#response = new Response(body, { status: options?.status ?? 200, headers })\n\t}\n\n\tget response(): Response {\n\t\treturn this.#response\n\t}\n\n\tget closed(): boolean {\n\t\treturn this.#closed\n\t}\n\n\twrite(message: SSEMessage): boolean {\n\t\tif (this.#closed || this.#controller === undefined) return false\n\t\tthis.#enqueue(serializeEvent(message))\n\t\treturn this.#controller.desiredSize !== null && this.#controller.desiredSize > 0\n\t}\n\n\tcomment(text: string): void {\n\t\tthis.#enqueue(serializeComment(text))\n\t}\n\n\tdrain(): Promise<void> {\n\t\tconst desired = this.#controller?.desiredSize\n\t\tif (this.#closed || (desired !== undefined && desired !== null && desired > 0)) {\n\t\t\treturn Promise.resolve()\n\t\t}\n\t\tthis.#wakeup ??= Promise.withResolvers<void>()\n\t\treturn this.#wakeup.promise\n\t}\n\n\tend(): void {\n\t\tif (this.#closed) return\n\t\tthis.#closed = true\n\t\tthis.#controller?.close()\n\t\tthis.#settle()\n\t}\n\n\t// The stream hands its controller over at start; every write path reads it\n\t// and treats an absent one as \"not yet writable\".\n\t#attach(controller: ReadableStreamDefaultController<Uint8Array>): void {\n\t\tthis.#controller = controller\n\t\t// The opening comment is the pump's first chunk, so the headers leave before any event.\n\t\tcontroller.enqueue(this.#encoder.encode(serializeComment('')))\n\t}\n\n\t// A pull that restored positive desired size is the wakeup a parked\n\t// producer is waiting on; a pull that did not restore it changes nothing.\n\t#pull(controller: ReadableStreamDefaultController<Uint8Array>): void {\n\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) return\n\t\tthis.#settle()\n\t}\n\n\t// The consumer cancelled the stream: the handle is closed from the far end,\n\t// so a parked producer settles rather than waiting for a pull that cannot come.\n\t#cancel(): void {\n\t\tthis.#closed = true\n\t\tthis.#settle()\n\t}\n\n\t// Encode and enqueue one wire fragment, ignoring a closed or unstarted stream.\n\t#enqueue(text: string): void {\n\t\tif (this.#closed || this.#controller === undefined) return\n\t\tthis.#controller.enqueue(this.#encoder.encode(text))\n\t}\n\n\t// Release a parked producer and drop the spent wakeup, so the next park\n\t// allocates a fresh one.\n\t#settle(): void {\n\t\tthis.#wakeup?.resolve()\n\t\tthis.#wakeup = undefined\n\t}\n}\n","import type {\n\tNegotiatorInterface,\n\tServerInterface,\n\tServerOptions,\n\tSignerInterface,\n\tSSEStreamInterface,\n\tStreamOptions,\n\tTokenSecret,\n} from './types.js'\nimport { Negotiator } from './Negotiator.js'\nimport { Server } from './Server.js'\nimport { Signer } from './Signer.js'\nimport { Stream } from './Stream.js'\n\n/**\n * Creates a {@link NegotiatorInterface} — the reusable content-negotiation\n * machine over the weighted `Accept` family.\n *\n * @returns A {@link NegotiatorInterface}\n *\n * @example\n * ```ts\n * import type { MiddlewareContext } from '@src/server'\n * import { createNegotiator } from '@src/server'\n *\n * declare const context: MiddlewareContext<Record<string, never>>\n *\n * const negotiator = createNegotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'\n * negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'\n * await negotiator.format(new Request('http://x'), context, {\n * \t'application/json': (_request, _context) => Response.json({ ok: true }),\n * })\n * ```\n */\nexport function createNegotiator(): NegotiatorInterface {\n\treturn new Negotiator()\n}\n\n/**\n * Creates a {@link ServerInterface} — the node face's HTTP server facade over\n * a consumed `@orkestrel/router` dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param options - {@link ServerOptions}\n * @returns A {@link ServerInterface}, not yet started\n *\n * @example Quickstart: dispatcher, middleware, lifecycle\n * ```ts\n * import type { MiddlewareHandler } from '@orkestrel/server'\n * import { createServer } from '@orkestrel/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * interface State {\n * \treadonly requestId: string\n * \treadonly ip: string | undefined\n * }\n *\n * const dispatcher = createDispatcher<State>()\n * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })\n *\n * const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Request-ID', context.state.requestId)\n * \treturn response\n * }\n *\n * const server = createServer<State>({\n * \tdispatcher,\n * \tstate: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),\n * })\n * server.use(logRequestId)\n * const port = await server.start()\n * await server.stop()\n * await server.destroy()\n * ```\n */\nexport function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState> {\n\treturn new Server(options)\n}\n\n/**\n * Creates a {@link SignerInterface} that holds one HMAC-SHA256 key per secret, each\n * created at this call.\n *\n * @param secret - A secret, or a `[current, ...older]` rotation list; see {@link TokenSecret}\n * @returns A {@link SignerInterface} whose first key signs and whose every key verifies\n * @throws {ServerError} `'SECRET'` when `secret` is not a string or a list of strings,\n * when the list is empty, or when any entry is blank\n *\n * @example\n * ```ts\n * import { createSigner, signToken, verifyToken } from '@orkestrel/server'\n *\n * const signer = createSigner(['current-secret', 'previous-secret'])\n * const token = await signToken('session-7f3a', { signer, ttl: 60_000 })\n * await verifyToken(token, signer) // 'session-7f3a'\n * ```\n */\nexport function createSigner(secret: TokenSecret): SignerInterface {\n\treturn new Signer(secret)\n}\n\n/**\n * Creates an {@link SSEStreamInterface} — a generic Server-Sent-Events stream whose\n * `response` is a fetch-standard streaming `Response` a route returns.\n *\n * @param options - {@link StreamOptions}\n * @returns An {@link SSEStreamInterface} whose stream is open\n *\n * @example\n * ```ts\n * import { createStream } from '@src/server'\n *\n * const stream = createStream()\n * void Promise.resolve().then(async () => {\n * \tif (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()\n * \tstream.comment('keep-alive')\n * \tstream.end()\n * })\n * // return stream.response from the route handler\n * ```\n */\nexport function createStream(options?: StreamOptions): SSEStreamInterface {\n\treturn new Stream(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,mBAAmB;;;;;AAMhC,IAAa,6BAA6B;;;;;;AAO1C,IAAa,6BAA6B;;;;;;;;;;;;;;;AAgB1C,IAAa,mBAAmB,OAAO,IAAI,6BAA6B;;;;;AAMxE,IAAa,qBAAqB;;;;;;;;;;;;;;;;;AAkBlC,IAAa,6BAA6B;;;;;;;;;;;;;AAc1C,IAAa,cAAgD,OAAO,OAAO;CAC1E,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,qBAAqB;AACtB,CAAC;;;;;;;;;;;;AAaD,IA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