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