@orkestrel/server 0.0.16 → 0.0.18

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.
@@ -2,16 +2,20 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _orkestrel_contract = require("@orkestrel/contract");
3
3
  let node_events = require("node:events");
4
4
  let node_net = require("node:net");
5
+ let _orkestrel_codec = require("@orkestrel/codec");
5
6
  let node_http = require("node:http");
6
7
  let _orkestrel_abort = require("@orkestrel/abort");
7
8
  let _orkestrel_timeout = require("@orkestrel/timeout");
8
9
  let _orkestrel_router_server = require("@orkestrel/router/server");
9
10
  let _orkestrel_emitter = require("@orkestrel/emitter");
10
11
  //#region src/server/constants.ts
11
- /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
12
+ /**
13
+ * Names the default graceful-stop deadline (ms) the server gives in-flight
14
+ * requests on `stop()`.
15
+ */
12
16
  var DEFAULT_DRAIN_MS = 1e4;
13
17
  /**
14
- * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
18
+ * Names the `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
15
19
  * an instance thrown by ANOTHER copy of this package (the dual-package
16
20
  * hazard — a version-skewed or workspace-linked duplicate install), where
17
21
  * `instanceof` alone fails because the two copies' `HTTPError` constructors
@@ -24,10 +28,10 @@ var DEFAULT_DRAIN_MS = 1e4;
24
28
  * unequal symbol per copy and defeat the whole point of a cross-copy brand.
25
29
  */
26
30
  var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
27
- /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
31
+ /** Names the default maximum request body size (bytes) `readBody` accepts before a 413. */
28
32
  var DEFAULT_BODY_LIMIT = 1048576;
29
33
  /**
30
- * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
34
+ * Names the default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
31
35
  * the body pipeline's byte-counting `TransformStream` enforces when
32
36
  * transparently decompressing a `Content-Encoding` request body.
33
37
  *
@@ -38,21 +42,22 @@ var DEFAULT_BODY_LIMIT = 1048576;
38
42
  * output would exceed this, BEFORE the full bomb is materialized, so the
39
43
  * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
40
44
  * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
41
- * consumer raises it via {@link import('./types.js').BodyOptions}
45
+ * consumer raises it through {@link import('./types.js').BodyOptions}
42
46
  * `decompression` for a workload that genuinely ships larger decompressed
43
47
  * bodies.
44
48
  */
45
49
  var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
46
50
  /**
47
- * The SSE response headers the `openStream` seam always sets.
51
+ * Holds the SSE response headers a `Stream` always sets on its response.
48
52
  *
49
53
  * @remarks
50
54
  * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
51
55
  * keeps a proxy from caching the stream; `keep-alive` holds the connection
52
56
  * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
53
57
  * events flush promptly rather than batching. Frozen so a consumer can read
54
- * but never mutate the shared default; `openStream` merges any
55
- * {@link import('./types.js').StreamOptions.headers} UNDER these.
58
+ * but never mutate the shared default; a `Stream` merges any
59
+ * {@link import('./types.js').StreamOptions.headers} OVER these, so a caller
60
+ * repeating one of these keys replaces its value.
56
61
  */
57
62
  var SSE_HEADERS = Object.freeze({
58
63
  "Content-Type": "text/event-stream; charset=utf-8",
@@ -61,16 +66,15 @@ var SSE_HEADERS = Object.freeze({
61
66
  "X-Accel-Buffering": "no"
62
67
  });
63
68
  /**
64
- * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
69
+ * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
65
70
  * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
66
71
  * / control-char-bearing incoming id is REJECTED (a fresh id is minted
67
- * instead) rather than ever riding into a response header or `context.state`
68
- * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
69
- * shared default.
72
+ * instead) rather than ever riding into a response header or `context.state`.
73
+ * Frozen so a consumer can read but never mutate the shared default.
70
74
  */
71
75
  var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
72
76
  /**
73
- * The set of bare `Content-Type`s `isCompressibleType` treats as
77
+ * Holds the set of bare `Content-Type`s `isCompressibleType` treats as
74
78
  * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
75
79
  * `+xml`) rules that helper also applies.
76
80
  *
@@ -78,10 +82,11 @@ var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
78
82
  * The text-shaped application types worth compressing (JSON / JavaScript /
79
83
  * XML / SVG / WASM / a few document formats) — NOT already-compressed
80
84
  * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
81
- * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
82
- * but never mutates the shared default.
85
+ * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
86
+ * withholds `add` / `delete` / `clear` from the shared default, so a consumer
87
+ * reads it without reaching a mutator.
83
88
  */
84
- var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
89
+ var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
85
90
  "application/json",
86
91
  "application/javascript",
87
92
  "application/xml",
@@ -94,9 +99,9 @@ var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
94
99
  "application/wasm",
95
100
  "image/svg+xml",
96
101
  "application/pdf"
97
- ]);
102
+ ]));
98
103
  /**
99
- * The default {@link Encoding} content-codings the substrate offers, in
104
+ * Lists the default {@link Encoding} content-codings the substrate offers, in
100
105
  * PREFERENCE order — `gzip` / `deflate`.
101
106
  *
102
107
  * @remarks
@@ -110,7 +115,7 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
110
115
  //#endregion
111
116
  //#region src/server/errors.ts
112
117
  /**
113
- * An error a handler (or middleware) throws to produce an HTTP response of a
118
+ * Represents an error a handler (or middleware) throws to produce an HTTP response of a
114
119
  * specific status.
115
120
  *
116
121
  * @remarks
@@ -121,7 +126,8 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
121
126
  * deliberate signal), unlike a generic throw whose message is hidden unless
122
127
  * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
123
128
  * specific statuses, or throw it directly. Narrow a caught value with
124
- * {@link isHTTPError}.
129
+ * {@link isHTTPError}. The machine-readable discriminator is `status`; there is
130
+ * no separate `code`.
125
131
  *
126
132
  * @example
127
133
  * ```ts
@@ -146,7 +152,7 @@ var HTTPError = class extends Error {
146
152
  }
147
153
  };
148
154
  /**
149
- * The {@link HTTPError} thrown when a request body exceeds the body
155
+ * Represents the {@link HTTPError} thrown when a request body exceeds the body
150
156
  * pipeline's size limit — a `413 Content Too Large`.
151
157
  *
152
158
  * @remarks
@@ -173,18 +179,18 @@ var ContentTooLargeError = class extends HTTPError {
173
179
  }
174
180
  };
175
181
  /**
176
- * Narrow an unknown caught value to an {@link HTTPError} (including its
182
+ * Narrows an unknown caught value to an {@link HTTPError} (including its
177
183
  * subclasses, e.g. {@link ContentTooLargeError}).
178
184
  *
179
185
  * @param value - The value to test (typically a `catch` binding)
180
- * @returns `true` when `value` is an {@link HTTPError}
186
+ * @returns True if `value` is an {@link HTTPError}; false otherwise
181
187
  *
182
188
  * @remarks
183
189
  * Tries `instanceof` first, then falls back to a total structural check for
184
190
  * an instance built by a DIFFERENT copy of this package (the dual-package
185
191
  * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
186
192
  * constructor is a distinct object from this copy's: the value must carry
187
- * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the
193
+ * the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
188
194
  * same key) AND expose the exact fields the server's error boundary reads off
189
195
  * a recognized `HTTPError` — a numeric `status` and a string `message`. A
190
196
  * plain object that merely carries a `status` WITHOUT the brand is rejected.
@@ -207,11 +213,101 @@ function isHTTPError(value) {
207
213
  if (!("status" in value) || !("message" in value)) return false;
208
214
  return (0, _orkestrel_contract.isNumber)(value.status) && (0, _orkestrel_contract.isString)(value.message);
209
215
  }
216
+ /**
217
+ * Represents the error this package raises when a caller programmed a call the
218
+ * entity refuses.
219
+ *
220
+ * @remarks
221
+ * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
222
+ * record naming the offending facts. This is a PROGRAMMER error, so it carries
223
+ * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
224
+ * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
225
+ * middleware into the request boundary, which reaches it as a generic 500 with
226
+ * the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
227
+ * client-facing fault instead. Narrow a caught value with
228
+ * {@link isServerError}.
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * import { ServerError } from '@src/server'
233
+ *
234
+ * const error = new ServerError('STATUS', "server cannot start from 'listening'", {
235
+ * status: 'listening',
236
+ * })
237
+ * error.code // 'STATUS'
238
+ * ```
239
+ */
240
+ var ServerError = class extends Error {
241
+ code;
242
+ context;
243
+ constructor(code, message, context) {
244
+ super(message);
245
+ this.name = "ServerError";
246
+ this.code = code;
247
+ if (context !== void 0) this.context = context;
248
+ }
249
+ };
250
+ /**
251
+ * Narrows an unknown caught value to a {@link ServerError}.
252
+ *
253
+ * @param value - The value to test (typically a `catch` binding)
254
+ * @returns True if `value` is a {@link ServerError}; false otherwise
255
+ *
256
+ * @remarks
257
+ * Recognizes an instance built by THIS copy of the package. A `ServerError`
258
+ * is raised by a `Server` to the caller that just invoked it, so both sides
259
+ * hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
260
+ * consumer here.
261
+ *
262
+ * @example
263
+ * ```ts
264
+ * import { createServer, isServerError } from '@src/server'
265
+ * import { createDispatcher } from '@orkestrel/router'
266
+ *
267
+ * const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })
268
+ * await server.start()
269
+ * try {
270
+ * await server.start()
271
+ * } catch (error) {
272
+ * if (isServerError(error)) console.log(error.code) // 'STATUS'
273
+ * }
274
+ * await server.stop()
275
+ * ```
276
+ */
277
+ function isServerError(value) {
278
+ return value instanceof ServerError;
279
+ }
280
+ //#endregion
281
+ //#region src/server/validators.ts
282
+ /**
283
+ * Checks whether a `node:net` `server.address()` return is the structured
284
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
285
+ * or `null` — the total, never-throwing narrow `discoverPort`
286
+ * and the `Server`'s own port resolution read the bound port through.
287
+ *
288
+ * @remarks
289
+ * Checks the `address`, `family`, and `port` members `node:net` declares as
290
+ * `string`, `string`, and `number`.
291
+ *
292
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
293
+ * @returns True if `value` is an `AddressInfo`; false otherwise
294
+ *
295
+ * @example
296
+ * ```ts
297
+ * import { isAddressInfo } from '@src/server'
298
+ *
299
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
300
+ * isAddressInfo(null) // false
301
+ * ```
302
+ */
303
+ function isAddressInfo(value) {
304
+ return (0, _orkestrel_contract.isRecord)(value) && (0, _orkestrel_contract.isString)(value.address) && (0, _orkestrel_contract.isString)(value.family) && (0, _orkestrel_contract.isNumber)(value.port);
305
+ }
210
306
  //#endregion
211
307
  //#region src/server/helpers.ts
212
308
  /**
213
- * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
214
- * handler into one request handler — the frozen middleware seam (§5.1).
309
+ * Composes an ordered chain of {@link MiddlewareHandler}s around a `terminal`
310
+ * handler into one request handler — the frozen middleware seam.
215
311
  *
216
312
  * @remarks
217
313
  * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
@@ -245,7 +341,7 @@ function compose(middleware, terminal) {
245
341
  return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
246
342
  }
247
343
  /**
248
- * Wrap one middleware layer around its downstream handler.
344
+ * Wraps one middleware layer around its downstream handler.
249
345
  *
250
346
  * @remarks
251
347
  * The returned handler enforces the one-call `next` invariant while preserving
@@ -268,14 +364,14 @@ function wrapMiddleware(layer, next) {
268
364
  return async (request, context) => {
269
365
  let called = false;
270
366
  return Promise.resolve(layer(request, context, (nextRequest) => {
271
- if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
367
+ if (called) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
272
368
  called = true;
273
369
  return next(nextRequest ?? request, context);
274
370
  }));
275
371
  };
276
372
  }
277
373
  /**
278
- * Parse a raw `Cookie:` request header into a `name → value` lookup.
374
+ * Parses a raw `Cookie:` request header into a `name → value` lookup.
279
375
  *
280
376
  * @remarks
281
377
  * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
@@ -285,7 +381,7 @@ function wrapMiddleware(layer, next) {
285
381
  * {@link isCookieName} rather than silently reconciling into a
286
382
  * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
287
383
  * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
288
- * malformed header yields an empty record, never throws (AGENTS §14).
384
+ * malformed header yields an empty record, never throws.
289
385
  *
290
386
  * @param header - The raw `Cookie` header value (possibly `undefined`)
291
387
  * @returns A record of every parsed cookie, `name → decoded value`
@@ -311,7 +407,7 @@ function parseCookies(header) {
311
407
  return out;
312
408
  }
313
409
  /**
314
- * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
410
+ * Checks whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
315
411
  * cookie-token chars with NO surrounding (or interior) whitespace.
316
412
  *
317
413
  * @remarks
@@ -321,7 +417,7 @@ function parseCookies(header) {
321
417
  * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
322
418
  *
323
419
  * @param value - The candidate cookie name
324
- * @returns `true` when `value` is a valid, whitespace-free cookie token
420
+ * @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
325
421
  *
326
422
  * @example
327
423
  * ```ts
@@ -333,7 +429,7 @@ function isCookieName(value) {
333
429
  return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
334
430
  }
335
431
  /**
336
- * Decode a cookie value with `decodeURIComponent`, falling back to the raw
432
+ * Decodes a cookie value with `decodeURIComponent`, falling back to the raw
337
433
  * text when the value is not valid percent-encoding.
338
434
  *
339
435
  * @param raw - The raw (trimmed) cookie value
@@ -353,7 +449,7 @@ function decodeCookieValue(raw) {
353
449
  }
354
450
  }
355
451
  /**
356
- * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
452
+ * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
357
453
  * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
358
454
  * attributes with before emitting them.
359
455
  *
@@ -364,7 +460,7 @@ function decodeCookieValue(raw) {
364
460
  * directive. Total — never throws (a bad value returns `false`).
365
461
  *
366
462
  * @param value - The candidate attribute value (a `Domain` or `Path`)
367
- * @returns `true` when `value` carries no separator / whitespace / control char
463
+ * @returns True if `value` carries no separator / whitespace / control char; false otherwise
368
464
  *
369
465
  * @example
370
466
  * ```ts
@@ -381,7 +477,7 @@ function isCookieAttribute(value) {
381
477
  return true;
382
478
  }
383
479
  /**
384
- * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
480
+ * Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
385
481
  *
386
482
  * @remarks
387
483
  * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
@@ -389,10 +485,9 @@ function isCookieAttribute(value) {
389
485
  * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
390
486
  * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
391
487
  * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
392
- * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
393
- * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
488
+ * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
394
489
  * the `secure` option (the spec requires it); an un-resolved `undefined`
395
- * `secure` here falls to OFF — request-aware callers resolve it first via
490
+ * `secure` here falls to OFF — request-aware callers resolve it first through
396
491
  * {@link resolveSecure}.
397
492
  *
398
493
  * @param name - The cookie name
@@ -423,7 +518,7 @@ function serializeCookie(name, value, options) {
423
518
  return parts.join("; ");
424
519
  }
425
520
  /**
426
- * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
521
+ * Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
427
522
  * `secure` setting and whether the request arrived over TLS.
428
523
  *
429
524
  * @remarks
@@ -433,7 +528,10 @@ function serializeCookie(name, value, options) {
433
528
  * gets `Secure` automatically while local-dev HTTP still works.
434
529
  *
435
530
  * @param secure - The {@link CookieOptions} `secure` setting
436
- * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
531
+ * @param encrypted - The connection's TLS flag
532
+ * ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted
533
+ * `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to
534
+ * no `Secure` attribute.
437
535
  * @returns The concrete `Secure` flag to emit
438
536
  *
439
537
  * @example
@@ -448,39 +546,15 @@ function resolveSecure(secure, encrypted) {
448
546
  return encrypted;
449
547
  }
450
548
  /**
451
- * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
452
- * clobbering a prior one.
453
- *
454
- * @remarks
455
- * `Headers.append` already accumulates repeated headers (unlike node's
456
- * `setHeader`), so this is a thin, self-documenting wrapper naming the
457
- * cookie-append intent — the primitive {@link writeSignedCookie} /
458
- * {@link clearCookie} use.
459
- *
460
- * @param headers - The response `Headers` to write into
461
- * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
462
- *
463
- * @example
464
- * ```ts
465
- * const headers = new Headers()
466
- * appendCookie(headers, serializeCookie('a', '1'))
467
- * appendCookie(headers, serializeCookie('b', '2'))
468
- * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
469
- * ```
470
- */
471
- function appendCookie(headers, cookie) {
472
- headers.append("set-cookie", cookie);
473
- }
474
- /**
475
- * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
476
- * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
549
+ * Writes a SIGNED cookie — HMAC-signs `value` with {@link signToken} and
550
+ * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
477
551
  *
478
552
  * @remarks
479
553
  * The cookie value is `await signToken(value, { secret })`
480
554
  * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
481
555
  * cookie — the same secret rotation and tamper rejection, no second HMAC
482
- * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
483
- * signing is asynchronous (§3 of the proposal).
556
+ * scheme. Appends (never clobbers) through `Headers.append`, which accumulates
557
+ * repeated headers. Async — WebCrypto signing is asynchronous.
484
558
  *
485
559
  * @param headers - The response `Headers` to write into
486
560
  * @param name - The cookie name
@@ -495,10 +569,10 @@ function appendCookie(headers, cookie) {
495
569
  * ```
496
570
  */
497
571
  async function writeSignedCookie(headers, name, value, secret, options) {
498
- appendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options));
572
+ headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
499
573
  }
500
574
  /**
501
- * Read + verify a SIGNED cookie off a request — TOTAL, returning the
575
+ * Reads + verifies a SIGNED cookie off a request — TOTAL, returning the
502
576
  * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
503
577
  *
504
578
  * @remarks
@@ -522,7 +596,7 @@ async function readSignedCookie(request, name, secret) {
522
596
  return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
523
597
  }
524
598
  /**
525
- * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
599
+ * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
526
600
  *
527
601
  * @remarks
528
602
  * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
@@ -540,66 +614,23 @@ async function readSignedCookie(request, name, secret) {
540
614
  * ```
541
615
  */
542
616
  function clearCookie(headers, name, options) {
543
- appendCookie(headers, serializeCookie(name, "", {
617
+ headers.append("set-cookie", serializeCookie(name, "", {
544
618
  ...options,
545
619
  maxAge: 0
546
620
  }));
547
621
  }
548
622
  /**
549
- * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
550
- * {@link verifyToken} use, and the signature encoding for the HMAC.
551
- *
552
- * @param bytes - The bytes to encode
553
- * @returns The base64url string (no padding)
554
- *
555
- * @example
556
- * ```ts
557
- * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
558
- * ```
559
- */
560
- function encodeBase64Url(bytes) {
561
- let binary = "";
562
- for (const byte of bytes) binary += String.fromCharCode(byte);
563
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
564
- }
565
- /**
566
- * Decode a base64url string back into its bytes — the inverse of
567
- * {@link encodeBase64Url}.
568
- *
569
- * @remarks
570
- * Restores the standard base64 alphabet + padding before decoding with
571
- * `atob`. THROWS `DOMException` on a malformed input — callers on the
572
- * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
573
- *
574
- * @param value - The base64url string to decode
575
- * @returns The decoded bytes
576
- * @throws {DOMException} When `value` is not valid base64url
577
- *
578
- * @example
579
- * ```ts
580
- * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
581
- * ```
582
- */
583
- function decodeBase64Url(value) {
584
- const restored = value.replace(/-/g, "+").replace(/_/g, "/");
585
- const padding = restored.length % 4 === 0 ? "" : "=".repeat(4 - restored.length % 4);
586
- const binary = atob(restored + padding);
587
- const bytes = new Uint8Array(binary.length);
588
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
589
- return bytes;
590
- }
591
- /**
592
- * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
623
+ * Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
593
624
  *
594
625
  * @remarks
595
626
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
596
627
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
597
628
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
598
- * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
629
+ * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the FIRST
599
630
  * {@link TokenSecret} (the current secret, or the head of a rotation list).
600
631
  * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
601
632
  * misconfigured secret with no usable entry THROWS an {@link HTTPError}
602
- * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
633
+ * (`500`) — fail-closed, a programmer error. Verify with
603
634
  * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
604
635
  *
605
636
  * @param value - The opaque value to embed (a session id, a deployment marker)
@@ -617,7 +648,7 @@ async function signToken(value, options) {
617
648
  const secret = normalizeSecret(options.secret)[0];
618
649
  if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
619
650
  const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
620
- const encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({
651
+ const encoded = (0, _orkestrel_codec.encodeBase64URL)(new TextEncoder().encode(JSON.stringify({
621
652
  value,
622
653
  exp
623
654
  })));
@@ -626,20 +657,22 @@ async function signToken(value, options) {
626
657
  hash: "SHA-256"
627
658
  }, false, ["sign"]);
628
659
  const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
629
- return `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`;
660
+ return `${encoded}.${(0, _orkestrel_codec.encodeBase64URL)(new Uint8Array(signature))}`;
630
661
  }
631
662
  /**
632
- * Verify a stateless token and return its embedded value — TOTAL, never throws.
663
+ * Verifies a stateless token and returns its embedded value — TOTAL, never throws.
633
664
  *
634
665
  * @remarks
635
666
  * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
636
- * value containing dots survives), and checks the payload's HMAC-SHA256
637
- * signature against EACH {@link TokenSecret} candidate via
667
+ * value containing dots survives), decodes the signature with
668
+ * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
669
+ * base64url is refused there, before any key import — and checks the payload's
670
+ * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate through
638
671
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
639
- * retired, §3 of the proposal), accepting the token on the first match (the
672
+ * retired), accepting the token on the first match (the
640
673
  * rotation path). It then decodes + narrows the payload (`isRecord` +
641
- * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
642
- * rejects an expired token. ANY failure — a malformed token, a bad signature,
674
+ * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
675
+ * token. ANY failure — a malformed token, a bad signature,
643
676
  * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
644
677
  * yields `undefined` rather than throwing.
645
678
  *
@@ -658,10 +691,10 @@ async function verifyToken(token, secret) {
658
691
  const dot = token.lastIndexOf(".");
659
692
  if (dot < 0) return void 0;
660
693
  const encoded = token.slice(0, dot);
661
- const signatureText = token.slice(dot + 1);
694
+ const signature = (0, _orkestrel_codec.decodeBase64URL)(token.slice(dot + 1));
695
+ if (signature === void 0) return void 0;
696
+ const data = new TextEncoder().encode(encoded);
662
697
  try {
663
- const signature = decodeBase64Url(signatureText);
664
- const data = new TextEncoder().encode(encoded);
665
698
  for (const candidate of secrets) {
666
699
  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
667
700
  name: "HMAC",
@@ -675,22 +708,26 @@ async function verifyToken(token, secret) {
675
708
  }
676
709
  }
677
710
  /**
678
- * Decode + narrow a signed token's base64url JSON payload, honoring its
711
+ * Decodes + narrows a signed token's base64url JSON payload, honoring its
679
712
  * expiry — the shared decode step {@link verifyToken} applies after a
680
713
  * signature match.
681
714
  *
682
715
  * @remarks
683
- * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
684
- * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
685
- * TOTAL — any decode/shape/expiry failure yields `undefined`.
716
+ * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
717
+ * non-canonical base64url segment answers `undefined` rather than throwing),
718
+ * reads it as UTF-8 JSON, narrows it to a record with a string `value` without
719
+ * `as`, and rejects an expired `exp`. TOTAL — any
720
+ * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
721
+ * throws, and its `catch` answers `undefined` too.
686
722
  *
687
723
  * @param encoded - The base64url-encoded payload segment (before the last `.`)
688
724
  * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
689
725
  */
690
726
  function decodeTokenPayload(encoded) {
727
+ const bytes = (0, _orkestrel_codec.decodeBase64URL)(encoded);
728
+ if (bytes === void 0) return void 0;
691
729
  try {
692
- const text = new TextDecoder().decode(decodeBase64Url(encoded));
693
- const payload = JSON.parse(text);
730
+ const payload = JSON.parse(new TextDecoder().decode(bytes));
694
731
  if (!(0, _orkestrel_contract.isRecord)(payload)) return void 0;
695
732
  if (typeof payload.value !== "string") return void 0;
696
733
  if (payload.exp !== void 0 && typeof payload.exp !== "number") return void 0;
@@ -701,7 +738,7 @@ function decodeTokenPayload(encoded) {
701
738
  }
702
739
  }
703
740
  /**
704
- * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
741
+ * Normalizes a {@link TokenSecret} to a concrete list of USABLE secrets —
705
742
  * backs both {@link signToken} and {@link verifyToken}.
706
743
  *
707
744
  * @remarks
@@ -722,7 +759,7 @@ function normalizeSecret(secret) {
722
759
  return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
723
760
  }
724
761
  /**
725
- * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
762
+ * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
726
763
  * into its q-sorted entries.
727
764
  *
728
765
  * @remarks
@@ -771,9 +808,9 @@ function parseAcceptHeader(header) {
771
808
  })).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
772
809
  }
773
810
  /**
774
- * The client's quality (q) for one content-coding from the parsed
775
- * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
776
- * server-preference selection.
811
+ * Computes the client's quality (q) for one content-coding from the parsed
812
+ * `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over
813
+ * each offered coding.
777
814
  *
778
815
  * @remarks
779
816
  * Prefers an EXACT named match (including an explicit `;q=0` rejection);
@@ -787,43 +824,45 @@ function parseAcceptHeader(header) {
787
824
  *
788
825
  * @example
789
826
  * ```ts
790
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
791
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
827
+ * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
828
+ * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
792
829
  * ```
793
830
  */
794
- function codingQuality(entries, coding) {
831
+ function computeCodingQuality(entries, coding) {
795
832
  const named = entries.find((entry) => entry.value === coding);
796
833
  if (named !== void 0) return named.q;
797
834
  return entries.find((entry) => entry.value === "*")?.q ?? 0;
798
835
  }
799
836
  /**
800
- * Select the best content-coding for an `Accept-Encoding` header from the
801
- * codings the server offers.
837
+ * Picks the highest-scoring content-coding the server offers against already
838
+ * parsed `Accept-Encoding` entries.
802
839
  *
803
840
  * @remarks
804
- * Parses the header ({@link parseAcceptHeader}) and scores each `available`
805
- * coding in the SERVER's preference order ({@link codingQuality}), keeping
806
- * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
807
- * client-side tie). Returns `undefined` when the client accepts none of
808
- * `available` (identity — no compression). TOTAL on hostile input.
841
+ * The single selection leaf behind both doors onto this axis —
842
+ * {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the
843
+ * entity — so the scoring loop has one implementation. Scores each `available`
844
+ * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
845
+ * keeps the earlier-offered coding on a client-side tie, which is what makes
846
+ * `available` the SERVER's preference order. An empty `available` list, and a
847
+ * list the client rejects outright, both yield `undefined` (identity — no
848
+ * compression). TOTAL on hostile input.
809
849
  *
810
850
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
811
- * @param header - The raw `Accept-Encoding` header value
851
+ * @param entries - The parsed {@link AcceptEntry} list
812
852
  * @param available - The codings the server offers, in preference (tie-break) order
813
- * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
853
+ * @returns The winning coding, or `undefined` when none of `available` is acceptable
814
854
  *
815
855
  * @example
816
856
  * ```ts
817
- * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
857
+ * resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
858
+ * resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
818
859
  * ```
819
860
  */
820
- function negotiateEncoding(header, available) {
821
- if (available.length === 0) return void 0;
822
- const entries = parseAcceptHeader(header);
861
+ function resolveCoding(entries, available) {
823
862
  let best;
824
863
  let bestQuality = 0;
825
864
  for (const coding of available) {
826
- const quality = codingQuality(entries, coding);
865
+ const quality = computeCodingQuality(entries, coding);
827
866
  if (quality > bestQuality) {
828
867
  best = coding;
829
868
  bestQuality = quality;
@@ -832,7 +871,32 @@ function negotiateEncoding(header, available) {
832
871
  return best;
833
872
  }
834
873
  /**
835
- * Rank + quality of one `candidate` media type against the parsed `Accept`
874
+ * Selects the best content-coding for a raw `Accept-Encoding` header from the
875
+ * codings the server offers.
876
+ *
877
+ * @remarks
878
+ * Parses the header ({@link parseAcceptHeader}) and hands the entries to
879
+ * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
880
+ * the two doors onto this axis cannot drift. Returns `undefined` when the
881
+ * client accepts none of `available` (identity — no compression). TOTAL on
882
+ * hostile input.
883
+ *
884
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
885
+ * @param header - The raw `Accept-Encoding` header value
886
+ * @param available - The codings the server offers, in preference (tie-break) order
887
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
888
+ *
889
+ * @example
890
+ * ```ts
891
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
892
+ * ```
893
+ */
894
+ function negotiateEncoding(header, available) {
895
+ if (available.length === 0) return void 0;
896
+ return resolveCoding(parseAcceptHeader(header), available);
897
+ }
898
+ /**
899
+ * Reports the rank + quality of one `candidate` media type against the parsed `Accept`
836
900
  * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
837
901
  * uses to score each `available` candidate.
838
902
  *
@@ -847,7 +911,7 @@ function negotiateEncoding(header, available) {
847
911
  *
848
912
  * @param entries - The parsed {@link AcceptEntry} list
849
913
  * @param candidate - The candidate media type to score (e.g. `'text/html'`)
850
- * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
914
+ * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
851
915
  *
852
916
  * @example
853
917
  * ```ts
@@ -879,8 +943,9 @@ function matchMediaType(entries, candidate) {
879
943
  return best;
880
944
  }
881
945
  /**
882
- * The client's quality for one `candidate` language from the parsed
883
- * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
946
+ * Computes the client's quality for one `candidate` language from the parsed
947
+ * `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`
948
+ * axis runs over each offered tag.
884
949
  *
885
950
  * @remarks
886
951
  * Prefers an exact match, then a primary-tag prefix match (`en` accepts
@@ -893,12 +958,12 @@ function matchMediaType(entries, candidate) {
893
958
  *
894
959
  * @example
895
960
  * ```ts
896
- * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
897
- * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
898
- * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
961
+ * computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
962
+ * computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
963
+ * computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
899
964
  * ```
900
965
  */
901
- function languageQuality(entries, candidate) {
966
+ function computeLanguageQuality(entries, candidate) {
902
967
  const lower = candidate.toLowerCase();
903
968
  const primary = lower.split("-")[0];
904
969
  let named;
@@ -916,7 +981,7 @@ function languageQuality(entries, candidate) {
916
981
  return wildcard ?? 0;
917
982
  }
918
983
  /**
919
- * Whether a `Content-Type` is worth compressing.
984
+ * Checks whether a `Content-Type` is worth compressing.
920
985
  *
921
986
  * @remarks
922
987
  * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
@@ -926,7 +991,7 @@ function languageQuality(entries, candidate) {
926
991
  * absent/empty type is not compressible. TOTAL.
927
992
  *
928
993
  * @param type - The response `Content-Type` header value (with or without parameters)
929
- * @returns `true` when the type is text-shaped and worth compressing
994
+ * @returns True if the type is text-shaped and worth compressing; false otherwise
930
995
  *
931
996
  * @example
932
997
  * ```ts
@@ -943,7 +1008,7 @@ function isCompressibleType(type) {
943
1008
  return COMPRESSIBLE_TYPES.has(bare);
944
1009
  }
945
1010
  /**
946
- * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
1011
+ * Computes a CONTENT `ETag` over a fully-buffered response body by using WebCrypto.
947
1012
  *
948
1013
  * @remarks
949
1014
  * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
@@ -953,7 +1018,8 @@ function isCompressibleType(type) {
953
1018
  * (`"<hash>"`, byte-identity) when `weak` is `false`.
954
1019
  *
955
1020
  * @param body - The full (uncompressed) response body to hash
956
- * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
1021
+ * @param weak - If `true` (the default), returns a weak `W/"…"` validator; if
1022
+ * `false`, returns a strong `"…"` one.
957
1023
  * @returns The `ETag` header value
958
1024
  *
959
1025
  * @example
@@ -963,11 +1029,11 @@ function isCompressibleType(type) {
963
1029
  */
964
1030
  async function computeBodyETag(body, weak = true) {
965
1031
  const digest = await crypto.subtle.digest("SHA-256", body);
966
- const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1032
+ const hex = (0, _orkestrel_codec.encodeHex)(new Uint8Array(digest));
967
1033
  return weak ? `W/"${hex}"` : `"${hex}"`;
968
1034
  }
969
1035
  /**
970
- * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
1036
+ * Strips the WEAK indicator (`W/`) from an entity-tag, returning its opaque
971
1037
  * comparison body — the reduction {@link matchesETag} applies to both sides
972
1038
  * before the RFC 7232 §2.3.2 weak comparison.
973
1039
  *
@@ -984,7 +1050,7 @@ function unwrapETag(tag) {
984
1050
  return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
985
1051
  }
986
1052
  /**
987
- * Whether a request's `If-None-Match` header matches a resource's current
1053
+ * Checks whether a request's `If-None-Match` header matches a resource's current
988
1054
  * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
989
1055
  *
990
1056
  * @remarks
@@ -992,12 +1058,12 @@ function unwrapETag(tag) {
992
1058
  * listed tag matches), or the `*` wildcard (matches ANY current
993
1059
  * representation — only a list of exactly `*` is the wildcard). Comparison is
994
1060
  * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
995
- * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
1061
+ * through {@link unwrapETag} before comparing the opaque body). TOTAL — a
996
1062
  * malformed/empty header matches nothing, never throws.
997
1063
  *
998
1064
  * @param header - The raw `If-None-Match` header value
999
1065
  * @param etag - The resource's current `ETag`
1000
- * @returns `true` when the conditional matches (the caller answers `304`)
1066
+ * @returns True if the conditional matches (the caller answers `304`); false otherwise
1001
1067
  *
1002
1068
  * @example
1003
1069
  * ```ts
@@ -1017,7 +1083,7 @@ function matchesETag(header, etag) {
1017
1083
  return false;
1018
1084
  }
1019
1085
  /**
1020
- * Parse an HTTP `Range` request header against a known resource `size` —
1086
+ * Parses an HTTP `Range` request header against a known resource `size` —
1021
1087
  * TOTAL, returning a {@link RangeSpec} or `undefined`.
1022
1088
  *
1023
1089
  * @remarks
@@ -1080,7 +1146,7 @@ function parseRange(header, size) {
1080
1146
  };
1081
1147
  }
1082
1148
  /**
1083
- * Resolve the `Access-Control-Allow-Origin` value for a request.
1149
+ * Resolves the `Access-Control-Allow-Origin` value for a request.
1084
1150
  *
1085
1151
  * @remarks
1086
1152
  * `'*'` and a single origin string pass straight through. An allow-list
@@ -1107,7 +1173,7 @@ function resolveOrigin(origin, requestOrigin) {
1107
1173
  return origin.includes(requestOrigin) ? requestOrigin : void 0;
1108
1174
  }
1109
1175
  /**
1110
- * Merge a `Vary` value into an existing `Vary` header without duplication.
1176
+ * Merges a `Vary` value into an existing `Vary` header without duplication.
1111
1177
  *
1112
1178
  * @remarks
1113
1179
  * Splits `existing` on `,`, trims each member, and appends `value` only when
@@ -1131,11 +1197,11 @@ function mergeVary(existing, value) {
1131
1197
  return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
1132
1198
  }
1133
1199
  /**
1134
- * Resolve one opt-out, value-bearing security header.
1200
+ * Resolves one opt-out, value-bearing security header.
1135
1201
  *
1136
1202
  * @remarks
1137
1203
  * The shared "a `string` value, or `false` to omit, or a default when unset"
1138
- * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1204
+ * resolution (a value-or-off union, not a behavioral toggle):
1139
1205
  * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1140
1206
  * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1141
1207
  *
@@ -1155,7 +1221,7 @@ function resolveSecurityHeader(value, fallback) {
1155
1221
  return value ?? fallback;
1156
1222
  }
1157
1223
  /**
1158
- * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1224
+ * Checks whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1159
1225
  * header + `context.state`.
1160
1226
  *
1161
1227
  * @remarks
@@ -1166,7 +1232,7 @@ function resolveSecurityHeader(value, fallback) {
1166
1232
  * TOTAL — never throws.
1167
1233
  *
1168
1234
  * @param value - The candidate incoming request id
1169
- * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
1235
+ * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
1170
1236
  *
1171
1237
  * @example
1172
1238
  * ```ts
@@ -1178,7 +1244,7 @@ function isValidRequestId(value) {
1178
1244
  return REQUEST_ID_PATTERN.test(value);
1179
1245
  }
1180
1246
  /**
1181
- * Compute the `/64` network of a full IPv6 address, or `undefined` when the
1247
+ * Computes the `/64` network of a full IPv6 address, or `undefined` when the
1182
1248
  * input is not a plain IPv6 address to collapse.
1183
1249
  *
1184
1250
  * @remarks
@@ -1194,11 +1260,11 @@ function isValidRequestId(value) {
1194
1260
  *
1195
1261
  * @example
1196
1262
  * ```ts
1197
- * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1198
- * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1263
+ * computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1264
+ * computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1199
1265
  * ```
1200
1266
  */
1201
- function ipv6Network(address) {
1267
+ function computeIPv6Network(address) {
1202
1268
  if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
1203
1269
  const percent = address.indexOf("%");
1204
1270
  const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
@@ -1228,30 +1294,30 @@ function ipv6Network(address) {
1228
1294
  return `${prefix.join(":")}::/64`;
1229
1295
  }
1230
1296
  /**
1231
- * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
1297
+ * Collapses a client IP into its rate-limit BUCKET key — an IPv6 address to
1232
1298
  * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1233
1299
  *
1234
1300
  * @remarks
1235
1301
  * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1236
1302
  * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1237
1303
  * real identity is the `/64` network. Delegates the IPv6 collapse to
1238
- * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
1304
+ * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
1239
1305
  * a malformed string) is kept unchanged.
1240
1306
  *
1241
- * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
1307
+ * @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})
1242
1308
  * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
1243
1309
  *
1244
1310
  * @example
1245
1311
  * ```ts
1246
- * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1247
- * clientRateKey('192.0.2.1') // '192.0.2.1'
1312
+ * computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1313
+ * computeClientKey('192.0.2.1') // '192.0.2.1'
1248
1314
  * ```
1249
1315
  */
1250
- function clientRateKey(address) {
1251
- return ipv6Network(address) ?? address;
1316
+ function computeClientKey(address) {
1317
+ return computeIPv6Network(address) ?? address;
1252
1318
  }
1253
1319
  /**
1254
- * Serialize one {@link SSEMessage} to the SSE wire.
1320
+ * Serializes one {@link SSEMessage} to the SSE wire.
1255
1321
  *
1256
1322
  * @remarks
1257
1323
  * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
@@ -1278,129 +1344,12 @@ function serializeEvent(message) {
1278
1344
  return `${lines.join("\n")}\n\n`;
1279
1345
  }
1280
1346
  /**
1281
- * Enqueue encoded text into an open byte stream.
1282
- *
1283
- * @param controller - The stream controller, when the stream has started
1284
- * @param encoder - The encoder used for the stream's byte representation
1285
- * @param closed - Whether the stream has already ended or been cancelled
1286
- * @param text - The text to encode and enqueue
1287
- * @returns Nothing
1288
- *
1289
- * @example
1290
- * ```ts
1291
- * const body = new ReadableStream<Uint8Array>({
1292
- * start(controller) {
1293
- * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
1294
- * },
1295
- * })
1296
- * ```
1297
- */
1298
- function enqueueStreamText(controller, encoder, closed, text) {
1299
- if (closed || controller === void 0) return;
1300
- controller.enqueue(encoder.encode(text));
1301
- }
1302
- /**
1303
- * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1304
- * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1305
- *
1306
- * @remarks
1307
- * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1308
- * merged under any `options.headers` (a seam-owned key is never overridden),
1309
- * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1310
- * `write` serializes one message ({@link serializeEvent}), enqueues it, and
1311
- * returns whether the controller still has positive desired size. A producer
1312
- * receiving `false` can await `drain()`; its event-driven promise resolves on
1313
- * the next consumer pull that restores capacity, or on stream closure.
1314
- * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1315
- * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1316
- * by `end()`, or the consumer cancelled the stream), so a late write never
1317
- * throws.
1318
- *
1319
- * This readiness reflects only the process-local `ReadableStream` queue — it
1320
- * is not proof that a remote peer consumed bytes. When the response pump
1321
- * honors its socket sink's drain state, socket pressure stops body pulls and
1322
- * therefore keeps this queue full, allowing a cooperative producer to bound
1323
- * buffering. Ignoring the return value preserves the prior unconditional-
1324
- * enqueue behavior. The default stream strategy counts chunks rather than
1325
- * their byte length, so a byte-bounded producer must also cap each message.
1326
- * Return `response` before awaiting a `false` write, because the consumer
1327
- * cannot pull until it receives the response.
1328
- *
1329
- * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1330
- * @returns The {@link StreamInterface} handle
1331
- *
1332
- * @example
1333
- * ```ts
1334
- * const stream = openStream()
1335
- * void Promise.resolve().then(async () => {
1336
- * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
1337
- * stream.end()
1338
- * })
1339
- * // return stream.response from the route handler
1340
- * ```
1341
- */
1342
- function openStream(options) {
1343
- const encoder = new TextEncoder();
1344
- let closed = false;
1345
- let controller;
1346
- let wakeup;
1347
- const body = new ReadableStream({
1348
- start(streamController) {
1349
- controller = streamController;
1350
- },
1351
- pull(streamController) {
1352
- if (streamController.desiredSize === null || streamController.desiredSize <= 0) return;
1353
- wakeup?.resolve();
1354
- wakeup = void 0;
1355
- },
1356
- cancel() {
1357
- closed = true;
1358
- wakeup?.resolve();
1359
- wakeup = void 0;
1360
- }
1361
- });
1362
- const headers = new Headers({
1363
- ...SSE_HEADERS,
1364
- ...options?.headers
1365
- });
1366
- return {
1367
- response: new Response(body, {
1368
- status: options?.status ?? 200,
1369
- headers
1370
- }),
1371
- get closed() {
1372
- return closed;
1373
- },
1374
- write(message) {
1375
- if (closed || controller === void 0) return false;
1376
- enqueueStreamText(controller, encoder, closed, serializeEvent(message));
1377
- return controller.desiredSize !== null && controller.desiredSize > 0;
1378
- },
1379
- comment(text) {
1380
- enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
1381
- },
1382
- drain() {
1383
- const desired = controller?.desiredSize;
1384
- if (closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
1385
- wakeup ??= Promise.withResolvers();
1386
- return wakeup.promise;
1387
- },
1388
- end() {
1389
- if (closed) return;
1390
- closed = true;
1391
- controller?.close();
1392
- wakeup?.resolve();
1393
- wakeup = void 0;
1394
- }
1395
- };
1396
- }
1397
- /**
1398
- * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1347
+ * Checks whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1399
1348
  * or `prototype` — the three keys that, assigned onto a normal object, can
1400
1349
  * reach and mutate `Object.prototype`.
1401
1350
  *
1402
1351
  * @param key - The candidate object key
1403
- * @returns `true` when `key` is one of the three prototype-pollution keys
1352
+ * @returns True if `key` is one of the three prototype-pollution keys; false otherwise
1404
1353
  *
1405
1354
  * @example
1406
1355
  * ```ts
@@ -1412,8 +1361,8 @@ function isDangerousKey(key) {
1412
1361
  return key === "__proto__" || key === "constructor" || key === "prototype";
1413
1362
  }
1414
1363
  /**
1415
- * Recursively STRIP the prototype-pollution keys from a parsed value IN
1416
- * PLACE.
1364
+ * Strips the prototype-pollution keys from a parsed value IN PLACE,
1365
+ * recursively.
1417
1366
  *
1418
1367
  * @remarks
1419
1368
  * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
@@ -1435,7 +1384,7 @@ function isDangerousKey(key) {
1435
1384
  */
1436
1385
  function scrubPrototype(value) {
1437
1386
  if (Array.isArray(value)) {
1438
- for (const item of value) scrubPrototype(item);
1387
+ for (const member of value) scrubPrototype(member);
1439
1388
  return value;
1440
1389
  }
1441
1390
  if ((0, _orkestrel_contract.isRecord)(value)) {
@@ -1451,7 +1400,7 @@ function scrubPrototype(value) {
1451
1400
  return value;
1452
1401
  }
1453
1402
  /**
1454
- * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
1403
+ * Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.
1455
1404
  *
1456
1405
  * @remarks
1457
1406
  * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
@@ -1494,14 +1443,14 @@ async function collectRequestBody(request, limit) {
1494
1443
  return merged;
1495
1444
  }
1496
1445
  /**
1497
- * Narrow a raw `Content-Encoding` header value to a decompressible
1498
- * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1446
+ * Parses a raw `Content-Encoding` header value into a decompressible
1447
+ * {@link Encoding} — the boundary {@link readBody} coerces through to decide
1499
1448
  * whether a request body needs transparent decompression.
1500
1449
  *
1501
1450
  * @remarks
1502
1451
  * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1503
- * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1504
- * the proposal). An absent header, `identity`, an unknown value, or a
1452
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
1453
+ * absent header, `identity`, an unknown value, or a
1505
1454
  * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1506
1455
  * TOTAL — never asserts the loose `string | null` header.
1507
1456
  *
@@ -1510,25 +1459,25 @@ async function collectRequestBody(request, limit) {
1510
1459
  *
1511
1460
  * @example
1512
1461
  * ```ts
1513
- * requestEncoding('gzip') // 'gzip'
1514
- * requestEncoding('br') // undefined — unsupported by DecompressionStream
1462
+ * parseEncoding('gzip') // 'gzip'
1463
+ * parseEncoding('br') // undefined — unsupported by DecompressionStream
1515
1464
  * ```
1516
1465
  */
1517
- function requestEncoding(header) {
1466
+ function parseEncoding(header) {
1518
1467
  if (!(0, _orkestrel_contract.isString)(header)) return void 0;
1519
1468
  const value = header.trim().toLowerCase();
1520
1469
  return value === "gzip" || value === "deflate" ? value : void 0;
1521
1470
  }
1522
1471
  /**
1523
- * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
1524
- * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
1472
+ * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
1473
+ * transparently through `DecompressionStream`, capping the DECOMPRESSED output —
1525
1474
  * the zip-bomb defense.
1526
1475
  *
1527
1476
  * @remarks
1528
1477
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1529
1478
  * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1530
1479
  * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1531
- * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
1480
+ * has no `maxOutputLength` knob. A cap breach surfaces
1532
1481
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1533
1482
  * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
1534
1483
  * (never conflated with the cap). A non-positive `cap` means uncapped.
@@ -1576,7 +1525,7 @@ async function decompressRequestBody(bytes, encoding, cap) {
1576
1525
  return merged;
1577
1526
  }
1578
1527
  /**
1579
- * Collect + decode a `Request` body — the shared body-collection pipeline
1528
+ * Collects + decodes a `Request` body — the shared body-collection pipeline
1580
1529
  * surfaced to middleware and handlers as the middleware context's cached
1581
1530
  * `body()`.
1582
1531
  *
@@ -1587,14 +1536,20 @@ async function decompressRequestBody(bytes, encoding, cap) {
1587
1536
  * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1588
1537
  * `options.decompression`, default {@link
1589
1538
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1590
- * content type: `application/json` is parsed via `@orkestrel/contract`'s
1539
+ * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1591
1540
  * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1592
1541
  * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1593
1542
  * decodes to `undefined`.
1594
1543
  *
1544
+ * A malformed JSON body is total: it decodes to `undefined` rather than
1545
+ * throwing, so a handler that must reject one checks for `undefined` itself.
1546
+ * That makes `undefined` the answer for two distinct inputs, and nothing in the
1547
+ * returned value tells them apart.
1548
+ *
1595
1549
  * @param request - The `Request` to read the body from
1596
1550
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1597
- * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1551
+ * @returns The parsed JSON value, the raw text, or `undefined` — for an empty
1552
+ * body, and for an `application/json` body whose text is not valid JSON
1598
1553
  * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1599
1554
  * @throws {HTTPError} When the compressed body is corrupt (400)
1600
1555
  *
@@ -1607,7 +1562,7 @@ async function readBody(request, options) {
1607
1562
  const limit = options?.limit ?? 1048576;
1608
1563
  const decompression = options?.decompression ?? 16777216;
1609
1564
  const wire = await collectRequestBody(request, limit);
1610
- const encoding = requestEncoding(request.headers.get("content-encoding"));
1565
+ const encoding = parseEncoding(request.headers.get("content-encoding"));
1611
1566
  const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
1612
1567
  if (bytes.length === 0) return void 0;
1613
1568
  const contentType = request.headers.get("content-type");
@@ -1618,30 +1573,17 @@ async function readBody(request, options) {
1618
1573
  return text;
1619
1574
  }
1620
1575
  /**
1621
- * Whether a `node:net` `server.address()` return is the structured
1622
- * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
1623
- * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
1624
- * and the `Server`'s own port resolution read the bound port through.
1576
+ * Binds and closes a throwaway TCP server to resolve one available port.
1625
1577
  *
1626
- * @param value - The `server.address()` return (`AddressInfo | string | null`)
1627
- * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
1628
- *
1629
- * @example
1630
- * ```ts
1631
- * import { isAddressInfo } from '@src/server'
1632
- *
1633
- * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
1634
- * isAddressInfo(null) // false
1635
- * ```
1636
- */
1637
- function isAddressInfo(value) {
1638
- return (0, _orkestrel_contract.isRecord)(value) && (0, _orkestrel_contract.isNumber)(value.port);
1639
- }
1640
- /**
1641
- * Bind and close a throwaway TCP server to resolve one available port.
1578
+ * @remarks
1579
+ * The probe always closes, including on the rejection path. A listener whose
1580
+ * address is not an {@link import('node:net').AddressInfo} — a pipe listener,
1581
+ * which a numeric `port` cannot request — has no port to report, so this
1582
+ * rejects rather than substituting a number.
1642
1583
  *
1643
1584
  * @param port - The requested port, with `0` selecting an ephemeral port
1644
1585
  * @returns The bound port after the probe server has closed
1586
+ * @throws {TypeError} When the bound listener's address carries no numeric port
1645
1587
  *
1646
1588
  * @example
1647
1589
  * ```ts
@@ -1654,15 +1596,15 @@ async function probePort(port) {
1654
1596
  probe.listen(port);
1655
1597
  await listening;
1656
1598
  const address = probe.address();
1657
- const resolved = isAddressInfo(address) ? address.port : 0;
1658
1599
  const closed = (0, node_events.once)(probe, "close");
1659
1600
  probe.close();
1660
1601
  await closed;
1661
- return resolved;
1602
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
1603
+ return address.port;
1662
1604
  }
1663
1605
  /**
1664
- * Find a FREE TCP port — bind a throwaway `node:net` server, read the
1665
- * OS-assigned port, close it, and resolve that port.
1606
+ * Finds a FREE TCP port — binds a throwaway `node:net` server, reads the
1607
+ * OS-assigned port, closes it, and resolves that port.
1666
1608
  *
1667
1609
  * @remarks
1668
1610
  * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
@@ -1672,11 +1614,16 @@ async function probePort(port) {
1672
1614
  * port. It binds then immediately closes a probe server, so the returned
1673
1615
  * port is free at the instant of the probe (an inherent TOCTOU race — bind it
1674
1616
  * promptly). Rejects only on an unexpected listen error other than a taken
1675
- * `preferred` port (e.g. a permission fault).
1617
+ * `preferred` port (e.g. a permission fault). A listener whose address is not
1618
+ * an {@link import('node:net').AddressInfo} — a pipe listener, which this
1619
+ * package's options cannot request — rejects with a `TypeError` rather than
1620
+ * reporting `0`, because `0` is this package's own request for an ephemeral
1621
+ * port and never means an unknown one.
1676
1622
  *
1677
1623
  * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
1678
1624
  * fall back to an ephemeral port
1679
1625
  * @returns A free TCP port number
1626
+ * @throws {TypeError} When the bound listener's address carries no numeric port
1680
1627
  *
1681
1628
  * @example
1682
1629
  * ```ts
@@ -1697,7 +1644,7 @@ async function discoverPort(preferred) {
1697
1644
  //#endregion
1698
1645
  //#region src/server/Negotiator.ts
1699
1646
  /**
1700
- * The content-negotiation machine over the weighted `Accept` family — a
1647
+ * Represents the content-negotiation machine over the weighted `Accept` family — a
1701
1648
  * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1702
1649
  * {@link NegotiatorInterface}.
1703
1650
  *
@@ -1737,7 +1684,8 @@ var Negotiator = class {
1737
1684
  return best;
1738
1685
  }
1739
1686
  encoding(header, available) {
1740
- return negotiateEncoding(header, available);
1687
+ if (available.length === 0) return void 0;
1688
+ return resolveCoding(parseAcceptHeader(header), available);
1741
1689
  }
1742
1690
  language(header, available) {
1743
1691
  if (available.length === 0) return void 0;
@@ -1746,7 +1694,7 @@ var Negotiator = class {
1746
1694
  let best;
1747
1695
  let bestQuality = 0;
1748
1696
  for (const candidate of available) {
1749
- const quality = languageQuality(entries, candidate);
1697
+ const quality = computeLanguageQuality(entries, candidate);
1750
1698
  if (quality > bestQuality) {
1751
1699
  best = candidate;
1752
1700
  bestQuality = quality;
@@ -1755,6 +1703,9 @@ var Negotiator = class {
1755
1703
  return best;
1756
1704
  }
1757
1705
  /**
1706
+ * Dispatches the request to the handler its `Accept` header negotiates,
1707
+ * answering 406 when none matches.
1708
+ *
1758
1709
  * @remarks
1759
1710
  * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1760
1711
  * server boundary classifies them, never this negotiator.
@@ -1772,14 +1723,14 @@ var Negotiator = class {
1772
1723
  //#endregion
1773
1724
  //#region src/server/Server.ts
1774
1725
  /**
1775
- * The HTTP server facade — an observable `node:http` lifecycle composing this
1726
+ * Represents the HTTP server facade — an observable `node:http` lifecycle composing this
1776
1727
  * module's own middleware onion around a consumed `@orkestrel/router`
1777
1728
  * dispatcher.
1778
1729
  *
1779
1730
  * @typeParam TState - The consumer's opaque per-request state type
1780
1731
  *
1781
1732
  * @remarks
1782
- * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1733
+ * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
1783
1734
  * server, binds the configured {@link ServerOptions.host} / {@link
1784
1735
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1785
1736
  * bound address), exposes that {@link AddressInfo} through `address`, observes
@@ -1793,15 +1744,15 @@ var Negotiator = class {
1793
1744
  * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1794
1745
  * still open. `destroy()` is the idempotent final teardown.
1795
1746
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1796
- * `close`); a `Request` is built via the router's `buildRequest`, its
1797
- * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
1747
+ * `close`); a `Request` is built through the router's `buildRequest`, its
1748
+ * `signal` LINKED to this run's stop signal through `@orkestrel/abort`'s
1798
1749
  * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1799
1750
  * `buildRequest`'s own abort, armed by BOTH request-side and response-side
1800
- * teardown, composes with the server's stop signal via `AbortSignal.any`,
1801
- * so a handler awaiting `request.signal` observes BOTH); `context.state` is built via
1751
+ * teardown, composes with the server's stop signal through `AbortSignal.any`,
1752
+ * so a handler awaiting `request.signal` observes BOTH); `context.state` is built through
1802
1753
  * {@link ServerOptions.state} from the connection facts; the composed
1803
1754
  * middleware onion runs, terminating in `dispatcher.handle`; the result is
1804
- * written back via `sendResponse`.
1755
+ * written back through `sendResponse`.
1805
1756
  * - **The built-in boundary** wraps the WHOLE per-request chain, including
1806
1757
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1807
1758
  * throw (e.g. a malformed `Host` header) to a silent `400` with no
@@ -1819,12 +1770,12 @@ var Negotiator = class {
1819
1770
  * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1820
1771
  * owns it, and the tracking exists because node detaches an upgraded socket
1821
1772
  * from the set its own close calls walk, so nothing else can end it.
1822
- * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1773
+ * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1823
1774
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1824
1775
  * routes it to the `error` OPTION (not the domain `error` event).
1825
1776
  */
1826
1777
  var Server = class {
1827
- id = crypto.randomUUID();
1778
+ #id;
1828
1779
  #dispatcher;
1829
1780
  #state;
1830
1781
  #middleware;
@@ -1857,6 +1808,7 @@ var Server = class {
1857
1808
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1858
1809
  const sockets = options.sockets ?? {};
1859
1810
  for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!(0, _orkestrel_contract.isInteger)(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1811
+ this.#id = crypto.randomUUID();
1860
1812
  this.#dispatcher = options.dispatcher;
1861
1813
  this.#state = options.state;
1862
1814
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1873,8 +1825,8 @@ var Server = class {
1873
1825
  ...options.error === void 0 ? {} : { error: options.error }
1874
1826
  });
1875
1827
  }
1876
- get #inflight() {
1877
- return this.#pending + this.#upgraded.size;
1828
+ get id() {
1829
+ return this.#id;
1878
1830
  }
1879
1831
  get status() {
1880
1832
  return this.#status;
@@ -1900,7 +1852,7 @@ var Server = class {
1900
1852
  this.#upgradeHandlers.push(handler);
1901
1853
  }
1902
1854
  start(signal) {
1903
- if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1855
+ if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
1904
1856
  this.#status = "starting";
1905
1857
  this.#abort = (0, _orkestrel_abort.createAbort)();
1906
1858
  const server = (0, node_http.createServer)((request, response) => this.#handle(request, response));
@@ -2034,17 +1986,13 @@ var Server = class {
2034
1986
  else socket.destroy();
2035
1987
  this.#emitter.emit("upgrade", request, handled);
2036
1988
  }
2037
- #resolvePort(server) {
2038
- const address = server.address();
2039
- if (isAddressInfo(address)) return address.port;
2040
- return 0;
2041
- }
2042
1989
  async #listen(server, signal) {
2043
1990
  const deadline = this.#timeouts.start === void 0 ? void 0 : (0, _orkestrel_timeout.createTimeout)({ ms: this.#timeouts.start });
2044
1991
  const startup = deadline === void 0 ? signal : (0, _orkestrel_abort.linkSignal)(deadline.signal, signal);
2045
1992
  const binding = (0, _orkestrel_abort.createAbort)();
2046
1993
  const relay = startup === void 0 ? void 0 : (0, node_events.addAbortListener)(startup, () => binding.abort(startup.reason));
2047
1994
  let listening;
1995
+ let port;
2048
1996
  try {
2049
1997
  signal?.throwIfAborted();
2050
1998
  deadline?.start();
@@ -2058,6 +2006,9 @@ var Server = class {
2058
2006
  signal: binding.signal
2059
2007
  });
2060
2008
  await listening;
2009
+ const address = server.address();
2010
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
2011
+ port = address.port;
2061
2012
  } catch (error) {
2062
2013
  const expired = deadline?.expired === true;
2063
2014
  const cancelled = startup?.aborted === true;
@@ -2075,7 +2026,6 @@ var Server = class {
2075
2026
  relay?.[Symbol.dispose]();
2076
2027
  deadline?.clear();
2077
2028
  }
2078
- const port = this.#resolvePort(server);
2079
2029
  this.#port = port;
2080
2030
  this.#status = "listening";
2081
2031
  this.#emitter.emit("start", port);
@@ -2097,6 +2047,9 @@ var Server = class {
2097
2047
  } else server.closeIdleConnections();
2098
2048
  });
2099
2049
  }
2050
+ get #inflight() {
2051
+ return this.#pending + this.#upgraded.size;
2052
+ }
2100
2053
  #enter() {
2101
2054
  if (this.#inflight === 0) this.#wakeup = (0, _orkestrel_abort.createAbort)();
2102
2055
  }
@@ -2129,14 +2082,122 @@ var Server = class {
2129
2082
  }
2130
2083
  };
2131
2084
  //#endregion
2132
- //#region src/server/factories.ts
2085
+ //#region src/server/Stream.ts
2133
2086
  /**
2134
- * Create a {@link NegotiatorInterface} — the reusable content-negotiation
2135
- * machine over the weighted `Accept` family.
2087
+ * Represents the Server-Sent-Events handle over an open, fetch-standard streaming
2088
+ * `Response`. Implements exactly {@link StreamInterface}.
2136
2089
  *
2137
2090
  * @remarks
2138
- * Prefer this over `new Negotiator()` at call sites that only need the
2139
- * interface.
2091
+ * Builds the `Response` at construction from
2092
+ * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
2093
+ * merged OVER them, at `options.status` (default `200`). A caller repeating one
2094
+ * of those keys therefore replaces the seam's value, in any casing. The
2095
+ * instance owns the stream's
2096
+ * controller, its text encoder, the closed flag, and the parked producer's
2097
+ * wakeup, so the whole handle is one entity rather than a closure over four
2098
+ * bindings.
2099
+ *
2100
+ * `write` serializes one message ({@link serializeEvent}), enqueues it, and
2101
+ * returns whether the controller still has positive desired size. A producer
2102
+ * receiving `false` awaits `drain()`; that promise resolves on the next
2103
+ * consumer pull restoring capacity, or on stream closure. `comment` writes a
2104
+ * `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
2105
+ * stream. Every method is a SAFE NO-OP once `closed` (ended by `end()`, or
2106
+ * the consumer cancelled the stream), so a late write never throws.
2107
+ *
2108
+ * The readiness signal reflects only the process-local `ReadableStream`
2109
+ * queue — it is not proof that a remote peer consumed bytes. When the response
2110
+ * pump honors its socket sink's drain state, socket pressure stops body pulls
2111
+ * and therefore keeps this queue full, letting a cooperative producer bound
2112
+ * its buffering. Ignoring the return value preserves an unconditional-enqueue
2113
+ * producer. The default stream strategy counts chunks rather than their byte
2114
+ * length, so a byte-bounded producer must also cap each message. Return
2115
+ * `response` before awaiting a `false` write, because the consumer cannot pull
2116
+ * until it receives the response.
2117
+ *
2118
+ * @example
2119
+ * ```ts
2120
+ * import { Stream } from '@src/server'
2121
+ *
2122
+ * const stream = new Stream()
2123
+ * void Promise.resolve().then(async () => {
2124
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
2125
+ * stream.comment('keep-alive')
2126
+ * stream.end()
2127
+ * })
2128
+ * // return stream.response from the route handler
2129
+ * ```
2130
+ */
2131
+ var Stream = class {
2132
+ #encoder = new TextEncoder();
2133
+ #response;
2134
+ #controller;
2135
+ #closed = false;
2136
+ #wakeup;
2137
+ constructor(options) {
2138
+ const body = new ReadableStream({
2139
+ start: this.#attach.bind(this),
2140
+ pull: this.#pull.bind(this),
2141
+ cancel: this.#cancel.bind(this)
2142
+ });
2143
+ const headers = new Headers(SSE_HEADERS);
2144
+ for (const [name, value] of Object.entries(options?.headers ?? {})) headers.set(name, value);
2145
+ this.#response = new Response(body, {
2146
+ status: options?.status ?? 200,
2147
+ headers
2148
+ });
2149
+ }
2150
+ get response() {
2151
+ return this.#response;
2152
+ }
2153
+ get closed() {
2154
+ return this.#closed;
2155
+ }
2156
+ write(message) {
2157
+ if (this.#closed || this.#controller === void 0) return false;
2158
+ this.#enqueue(serializeEvent(message));
2159
+ return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
2160
+ }
2161
+ comment(text) {
2162
+ this.#enqueue(`: ${text}\n\n`);
2163
+ }
2164
+ drain() {
2165
+ const desired = this.#controller?.desiredSize;
2166
+ if (this.#closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
2167
+ this.#wakeup ??= Promise.withResolvers();
2168
+ return this.#wakeup.promise;
2169
+ }
2170
+ end() {
2171
+ if (this.#closed) return;
2172
+ this.#closed = true;
2173
+ this.#controller?.close();
2174
+ this.#settle();
2175
+ }
2176
+ #attach(controller) {
2177
+ this.#controller = controller;
2178
+ }
2179
+ #pull(controller) {
2180
+ if (controller.desiredSize === null || controller.desiredSize <= 0) return;
2181
+ this.#settle();
2182
+ }
2183
+ #cancel() {
2184
+ this.#closed = true;
2185
+ this.#settle();
2186
+ }
2187
+ #enqueue(text) {
2188
+ if (this.#closed || this.#controller === void 0) return;
2189
+ this.#controller.enqueue(this.#encoder.encode(text));
2190
+ }
2191
+ #settle() {
2192
+ this.#wakeup?.resolve();
2193
+ this.#wakeup = void 0;
2194
+ }
2195
+ };
2196
+ //#endregion
2197
+ //#region src/server/factories.ts
2198
+ /**
2199
+ * Creates a {@link NegotiatorInterface} — the reusable content-negotiation
2200
+ * machine over the weighted `Accept` family.
2140
2201
  *
2141
2202
  * @returns A {@link NegotiatorInterface}
2142
2203
  *
@@ -2153,7 +2214,7 @@ function createNegotiator() {
2153
2214
  return new Negotiator();
2154
2215
  }
2155
2216
  /**
2156
- * Create a {@link ServerInterface} — the node face's HTTP server facade over
2217
+ * Creates a {@link ServerInterface} — the node face's HTTP server facade over
2157
2218
  * a consumed `@orkestrel/router` dispatcher.
2158
2219
  *
2159
2220
  * @typeParam TState - The consumer's opaque per-request state type
@@ -2179,6 +2240,29 @@ function createNegotiator() {
2179
2240
  function createServer(options) {
2180
2241
  return new Server(options);
2181
2242
  }
2243
+ /**
2244
+ * Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
2245
+ * `response` is a fetch-standard streaming `Response` a route returns.
2246
+ *
2247
+ * @param options - {@link StreamOptions}
2248
+ * @returns A {@link StreamInterface} whose stream is open
2249
+ *
2250
+ * @example
2251
+ * ```ts
2252
+ * import { createStream } from '@src/server'
2253
+ *
2254
+ * const stream = createStream()
2255
+ * void Promise.resolve().then(async () => {
2256
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
2257
+ * stream.comment('keep-alive')
2258
+ * stream.end()
2259
+ * })
2260
+ * // return stream.response from the route handler
2261
+ * ```
2262
+ */
2263
+ function createStream(options) {
2264
+ return new Stream(options);
2265
+ }
2182
2266
  //#endregion
2183
2267
  exports.COMPRESSIBLE_TYPES = COMPRESSIBLE_TYPES;
2184
2268
  exports.ContentTooLargeError = ContentTooLargeError;
@@ -2192,44 +2276,44 @@ exports.Negotiator = Negotiator;
2192
2276
  exports.REQUEST_ID_PATTERN = REQUEST_ID_PATTERN;
2193
2277
  exports.SSE_HEADERS = SSE_HEADERS;
2194
2278
  exports.Server = Server;
2195
- exports.appendCookie = appendCookie;
2279
+ exports.ServerError = ServerError;
2280
+ exports.Stream = Stream;
2196
2281
  exports.clearCookie = clearCookie;
2197
- exports.clientRateKey = clientRateKey;
2198
- exports.codingQuality = codingQuality;
2199
2282
  exports.collectRequestBody = collectRequestBody;
2200
2283
  exports.compose = compose;
2201
2284
  exports.computeBodyETag = computeBodyETag;
2285
+ exports.computeClientKey = computeClientKey;
2286
+ exports.computeCodingQuality = computeCodingQuality;
2287
+ exports.computeIPv6Network = computeIPv6Network;
2288
+ exports.computeLanguageQuality = computeLanguageQuality;
2202
2289
  exports.createNegotiator = createNegotiator;
2203
2290
  exports.createServer = createServer;
2204
- exports.decodeBase64Url = decodeBase64Url;
2291
+ exports.createStream = createStream;
2205
2292
  exports.decodeCookieValue = decodeCookieValue;
2206
2293
  exports.decodeTokenPayload = decodeTokenPayload;
2207
2294
  exports.decompressRequestBody = decompressRequestBody;
2208
2295
  exports.discoverPort = discoverPort;
2209
- exports.encodeBase64Url = encodeBase64Url;
2210
- exports.enqueueStreamText = enqueueStreamText;
2211
- exports.ipv6Network = ipv6Network;
2212
2296
  exports.isAddressInfo = isAddressInfo;
2213
2297
  exports.isCompressibleType = isCompressibleType;
2214
2298
  exports.isCookieAttribute = isCookieAttribute;
2215
2299
  exports.isCookieName = isCookieName;
2216
2300
  exports.isDangerousKey = isDangerousKey;
2217
2301
  exports.isHTTPError = isHTTPError;
2302
+ exports.isServerError = isServerError;
2218
2303
  exports.isValidRequestId = isValidRequestId;
2219
- exports.languageQuality = languageQuality;
2220
2304
  exports.matchMediaType = matchMediaType;
2221
2305
  exports.matchesETag = matchesETag;
2222
2306
  exports.mergeVary = mergeVary;
2223
2307
  exports.negotiateEncoding = negotiateEncoding;
2224
2308
  exports.normalizeSecret = normalizeSecret;
2225
- exports.openStream = openStream;
2226
2309
  exports.parseAcceptHeader = parseAcceptHeader;
2227
2310
  exports.parseCookies = parseCookies;
2311
+ exports.parseEncoding = parseEncoding;
2228
2312
  exports.parseRange = parseRange;
2229
2313
  exports.probePort = probePort;
2230
2314
  exports.readBody = readBody;
2231
2315
  exports.readSignedCookie = readSignedCookie;
2232
- exports.requestEncoding = requestEncoding;
2316
+ exports.resolveCoding = resolveCoding;
2233
2317
  exports.resolveOrigin = resolveOrigin;
2234
2318
  exports.resolveSecure = resolveSecure;
2235
2319
  exports.resolveSecurityHeader = resolveSecurityHeader;