@orkestrel/server 0.0.18 → 0.0.19

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.
@@ -10,36 +10,40 @@ let _orkestrel_router_server = require("@orkestrel/router/server");
10
10
  let _orkestrel_emitter = require("@orkestrel/emitter");
11
11
  //#region src/server/constants.ts
12
12
  /**
13
- * Names the default graceful-stop deadline (ms) the server gives in-flight
14
- * requests on `stop()`.
13
+ * Names the default graceful-stop deadline `stop()` gives in-flight requests and
14
+ * claimed upgraded sockets, `10_000` ms.
15
15
  */
16
16
  var DEFAULT_DRAIN_MS = 1e4;
17
17
  /**
18
- * Names the `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
19
- * an instance thrown by ANOTHER copy of this package (the dual-package
20
- * hazard — a version-skewed or workspace-linked duplicate install), where
21
- * `instanceof` alone fails because the two copies' `HTTPError` constructors
22
- * are distinct objects.
18
+ * Names the `Symbol.for`-interned brand `HTTPError` carries,
19
+ * `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
20
+ * package copies. A consumer never sets it by hand.
23
21
  *
24
22
  * @remarks
25
- * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every
26
- * copy of this package that evaluates this key resolves the SAME symbol
23
+ * The brand exists for the dual-package hazard — a version-skewed or
24
+ * workspace-linked duplicate install — where `instanceof` alone fails because
25
+ * each copy's `HTTPError` constructor is a distinct object.
26
+ * `Symbol.for` interns the symbol on the global symbol registry, so every
27
+ * copy of this package that evaluates this key resolves the same symbol
27
28
  * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
28
29
  * unequal symbol per copy and defeat the whole point of a cross-copy brand.
29
30
  */
30
31
  var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
31
- /** Names the default maximum request body size (bytes) `readBody` accepts before a 413. */
32
+ /**
33
+ * Names the default maximum request body size `readBody` accepts before a 413,
34
+ * `1_048_576` bytes.
35
+ */
32
36
  var DEFAULT_BODY_LIMIT = 1048576;
33
37
  /**
34
- * Names the default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
35
- * the body pipeline's byte-counting `TransformStream` enforces when
36
- * transparently decompressing a `Content-Encoding` request body.
38
+ * Names the default maximum decompressed request body size, `16_777_216` bytes — the
39
+ * zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when
40
+ * it transparently decompresses a `Content-Encoding` request body.
37
41
  *
38
42
  * @remarks
39
43
  * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
40
44
  * can inflate by many orders of magnitude — a classic decompression bomb.
41
- * Capping the decompressed byte count makes the pipe ABORT the moment the
42
- * output would exceed this, BEFORE the full bomb is materialized, so the
45
+ * Capping the decompressed byte count makes the pipe abort the moment the
46
+ * output would exceed this, before the full bomb is materialized, so the
43
47
  * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
44
48
  * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
45
49
  * consumer raises it through {@link import('./types.js').BodyOptions}
@@ -48,16 +52,16 @@ var DEFAULT_BODY_LIMIT = 1048576;
48
52
  */
49
53
  var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
50
54
  /**
51
- * Holds the SSE response headers a `Stream` always sets on its response.
55
+ * Holds the SSE response headers a `Stream` sets on its response, merged under any
56
+ * caller `headers` so a caller repeating one of these keys replaces its value.
52
57
  *
53
58
  * @remarks
54
59
  * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
55
60
  * keeps a proxy from caching the stream; `keep-alive` holds the connection
56
61
  * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
57
62
  * events flush promptly rather than batching. Frozen so a consumer can read
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.
63
+ * but never mutate the shared default; the merged keys are
64
+ * {@link import('./types.js').StreamOptions.headers}.
61
65
  */
62
66
  var SSE_HEADERS = Object.freeze({
63
67
  "Content-Type": "text/event-stream; charset=utf-8",
@@ -67,20 +71,24 @@ var SSE_HEADERS = Object.freeze({
67
71
  });
68
72
  /**
69
73
  * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
70
- * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
71
- * / control-char-bearing incoming id is REJECTED (a fresh id is minted
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.
74
+ * to match, `^[A-Za-z0-9_-]{1,200}$`.
75
+ *
76
+ * @remarks
77
+ * An incoming id carrying CRLF, a log-injection payload, a control character,
78
+ * or more characters than the pattern admits fails the match and is rejected —
79
+ * a fresh id is minted instead — so it never rides into a response header or
80
+ * `context.state`. Frozen so a consumer can read but never mutate the shared
81
+ * default.
74
82
  */
75
83
  var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
76
84
  /**
77
- * Holds the set of bare `Content-Type`s `isCompressibleType` treats as
78
- * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
79
- * `+xml`) rules that helper also applies.
85
+ * Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
86
+ * beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
87
+ * helper also applies.
80
88
  *
81
89
  * @remarks
82
90
  * The text-shaped application types worth compressing (JSON / JavaScript /
83
- * XML / SVG / WASM / a few document formats) — NOT already-compressed
91
+ * XML / SVG / WASM / a few document formats) — never already-compressed
84
92
  * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
85
93
  * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
86
94
  * withholds `add` / `delete` / `clear` from the shared default, so a consumer
@@ -102,10 +110,10 @@ var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
102
110
  ]));
103
111
  /**
104
112
  * Lists the default {@link Encoding} content-codings the substrate offers, in
105
- * PREFERENCE order — `gzip` / `deflate`.
113
+ * preference order — `gzip` then `deflate`.
106
114
  *
107
115
  * @remarks
108
- * `identity` (no compression) is always implicitly acceptable and is NOT
116
+ * `identity` (no compression) is always implicitly acceptable and is not
109
117
  * listed here — it is the fall-through when a client accepts none of these.
110
118
  * Brotli is omitted per the core's `CompressionStream`-only decision (see
111
119
  * {@link Encoding}). Frozen so a consumer can read but never mutate the
@@ -122,7 +130,7 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
122
130
  * Carries the HTTP `status` to send and an optional `context` record (the
123
131
  * offending field / value). The server's built-in error boundary catches it
124
132
  * and renders a response of `status` with the error's `message` as the body
125
- * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
133
+ * — so an `HTTPError`'s message is always client-facing (it is the handler's
126
134
  * deliberate signal), unlike a generic throw whose message is hidden unless
127
135
  * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
128
136
  * specific statuses, or throw it directly. Narrow a caught value with
@@ -179,21 +187,22 @@ var ContentTooLargeError = class extends HTTPError {
179
187
  }
180
188
  };
181
189
  /**
182
- * Narrows an unknown caught value to an {@link HTTPError} (including its
183
- * subclasses, e.g. {@link ContentTooLargeError}).
190
+ * Narrows an unknown caught value to an {@link HTTPError}, including a subclass such
191
+ * as {@link ContentTooLargeError}, and recognizes an instance from another copy of
192
+ * this package through a structural brand fallback.
184
193
  *
185
194
  * @param value - The value to test (typically a `catch` binding)
186
195
  * @returns True if `value` is an {@link HTTPError}; false otherwise
187
196
  *
188
197
  * @remarks
189
198
  * Tries `instanceof` first, then falls back to a total structural check for
190
- * an instance built by a DIFFERENT copy of this package (the dual-package
199
+ * an instance built by a different copy of this package (the dual-package
191
200
  * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
192
201
  * constructor is a distinct object from this copy's: the value must carry
193
202
  * the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
194
- * same key) AND expose the exact fields the server's error boundary reads off
203
+ * same key) and expose the exact fields the server's error boundary reads off
195
204
  * a recognized `HTTPError` — a numeric `status` and a string `message`. A
196
- * plain object that merely carries a `status` WITHOUT the brand is rejected.
205
+ * plain object that merely carries a `status` without the brand is rejected.
197
206
  *
198
207
  * @example
199
208
  * ```ts
@@ -215,11 +224,11 @@ function isHTTPError(value) {
215
224
  }
216
225
  /**
217
226
  * Represents the error this package raises when a caller programmed a call the
218
- * entity refuses.
227
+ * entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
219
228
  *
220
229
  * @remarks
221
230
  * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
222
- * record naming the offending facts. This is a PROGRAMMER error, so it carries
231
+ * record naming the offending facts. This is a programmer error, so it carries
223
232
  * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
224
233
  * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
225
234
  * middleware into the request boundary, which reaches it as a generic 500 with
@@ -248,14 +257,15 @@ var ServerError = class extends Error {
248
257
  }
249
258
  };
250
259
  /**
251
- * Narrows an unknown caught value to a {@link ServerError}.
260
+ * Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal
261
+ * of a call the caller programmed.
252
262
  *
253
263
  * @param value - The value to test (typically a `catch` binding)
254
264
  * @returns True if `value` is a {@link ServerError}; false otherwise
255
265
  *
256
266
  * @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
267
+ * Recognizes an instance built by this copy of the package. A `ServerError`
268
+ * is raised by a `Server` to the caller that invoked it directly, so both sides
259
269
  * hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
260
270
  * consumer here.
261
271
  *
@@ -306,18 +316,18 @@ function isAddressInfo(value) {
306
316
  //#endregion
307
317
  //#region src/server/helpers.ts
308
318
  /**
309
- * Composes an ordered chain of {@link MiddlewareHandler}s around a `terminal`
319
+ * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
310
320
  * handler into one request handler — the frozen middleware seam.
311
321
  *
312
322
  * @remarks
313
- * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
314
- * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
323
+ * `middleware[0]` runs outermost: it is invoked first, and its call to `next`
324
+ * runs `middleware[1]`, and so on until the last middleware's `next` invokes
315
325
  * `terminal`. Each middleware's `next` may be called with a substituted
316
326
  * `Request` (the downstream chain then sees that request instead of the
317
327
  * original), called with no argument (the original request continues
318
- * downstream), or NOT called at all (a short-circuit — the middleware's own
328
+ * downstream), or not called at all (a short-circuit — the middleware's own
319
329
  * returned `Response` is sent, and everything downstream never runs). A
320
- * SECOND call to the same `next` within one middleware invocation REJECTS —
330
+ * second call to the same `next` within one middleware invocation rejects —
321
331
  * each link runs the chain at most once, so a middleware cannot fork the
322
332
  * request into two divergent downstream runs.
323
333
  *
@@ -341,7 +351,8 @@ function compose(middleware, terminal) {
341
351
  return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
342
352
  }
343
353
  /**
344
- * Wraps one middleware layer around its downstream handler.
354
+ * Wraps one middleware layer around its downstream handler, enforcing the one-call
355
+ * `next` invariant.
345
356
  *
346
357
  * @remarks
347
358
  * The returned handler enforces the one-call `next` invariant while preserving
@@ -374,13 +385,13 @@ function wrapMiddleware(layer, next) {
374
385
  * Parses a raw `Cookie:` request header into a `name → value` lookup.
375
386
  *
376
387
  * @remarks
377
- * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
388
+ * Splits on `;`; the first segment keeps any leading whitespace (a genuine
378
389
  * cookie-pair separator never precedes it), while every later segment has its
379
390
  * inter-pair separator (ASCII space/tab) stripped before parsing — so a
380
- * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
391
+ * whitespace-padded name (`' __Host-x=evil'`) is rejected by
381
392
  * {@link isCookieName} rather than silently reconciling into a
382
393
  * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
383
- * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
394
+ * name, is skipped; a later duplicate name wins. Total — an absent/empty/
384
395
  * malformed header yields an empty record, never throws.
385
396
  *
386
397
  * @param header - The raw `Cookie` header value (possibly `undefined`)
@@ -407,8 +418,8 @@ function parseCookies(header) {
407
418
  return out;
408
419
  }
409
420
  /**
410
- * Checks whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
411
- * cookie-token chars with NO surrounding (or interior) whitespace.
421
+ * Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
422
+ * cookie-token characters with no surrounding or interior whitespace.
412
423
  *
413
424
  * @remarks
414
425
  * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
@@ -449,9 +460,9 @@ function decodeCookieValue(raw) {
449
460
  }
450
461
  }
451
462
  /**
452
- * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
453
- * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
454
- * attributes with before emitting them.
463
+ * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —
464
+ * the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it
465
+ * emits them.
455
466
  *
456
467
  * @remarks
457
468
  * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
@@ -483,11 +494,11 @@ function isCookieAttribute(value) {
483
494
  * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
484
495
  * appends the present {@link CookieOptions} attributes in canonical order:
485
496
  * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
486
- * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
487
- * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
488
- * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
497
+ * (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated
498
+ * with {@link isCookieAttribute} and throw an {@link HTTPError} on an
499
+ * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of
489
500
  * the `secure` option (the spec requires it); an un-resolved `undefined`
490
- * `secure` here falls to OFF — request-aware callers resolve it first through
501
+ * `secure` here falls to off — request-aware callers resolve it first through
491
502
  * {@link resolveSecure}.
492
503
  *
493
504
  * @param name - The cookie name
@@ -546,7 +557,7 @@ function resolveSecure(secure, encrypted) {
546
557
  return encrypted;
547
558
  }
548
559
  /**
549
- * Writes a SIGNED cookie — HMAC-signs `value` with {@link signToken} and
560
+ * Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
550
561
  * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
551
562
  *
552
563
  * @remarks
@@ -572,13 +583,13 @@ async function writeSignedCookie(headers, name, value, secret, options) {
572
583
  headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
573
584
  }
574
585
  /**
575
- * Reads + verifies a SIGNED cookie off a request — TOTAL, returning the
586
+ * Reads and verifies a signed cookie off a request — total, returning the
576
587
  * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
577
588
  *
578
589
  * @remarks
579
590
  * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
580
591
  * and verifies it with {@link verifyToken} against `secret` (a rotation list
581
- * accepts a cookie signed by any of its secrets). ANY failure — an absent
592
+ * accepts a cookie signed by any of its secrets). Any failure — an absent
582
593
  * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
583
594
  *
584
595
  * @param request - The `Request` to read the `Cookie` header from
@@ -601,7 +612,7 @@ async function readSignedCookie(request, name, secret) {
601
612
  * @remarks
602
613
  * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
603
614
  * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
604
- * a cookie when those MATCH the one it set).
615
+ * a cookie when those match the one it set).
605
616
  *
606
617
  * @param headers - The response `Headers` to write into
607
618
  * @param name - The cookie name to clear
@@ -626,10 +637,10 @@ function clearCookie(headers, name, options) {
626
637
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
627
638
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
628
639
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
629
- * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the FIRST
640
+ * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
630
641
  * {@link TokenSecret} (the current secret, or the head of a rotation list).
631
- * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
632
- * misconfigured secret with no usable entry THROWS an {@link HTTPError}
642
+ * Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
643
+ * misconfigured secret with no usable entry throws an {@link HTTPError}
633
644
  * (`500`) — fail-closed, a programmer error. Verify with
634
645
  * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
635
646
  *
@@ -660,19 +671,19 @@ async function signToken(value, options) {
660
671
  return `${encoded}.${(0, _orkestrel_codec.encodeBase64URL)(new Uint8Array(signature))}`;
661
672
  }
662
673
  /**
663
- * Verifies a stateless token and returns its embedded value — TOTAL, never throws.
674
+ * Verifies a stateless token and returns its embedded value — total, never throws.
664
675
  *
665
676
  * @remarks
666
- * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
677
+ * The inverse of {@link signToken}: splits the token on its last `.` (so a
667
678
  * value containing dots survives), decodes the signature with
668
679
  * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
669
680
  * base64url is refused there, before any key import — and checks the payload's
670
- * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate through
681
+ * HMAC-SHA256 signature against each {@link TokenSecret} candidate through
671
682
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
672
683
  * retired), accepting the token on the first match (the
673
684
  * rotation path). It then decodes + narrows the payload (`isRecord` +
674
685
  * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
675
- * token. ANY failure — a malformed token, a bad signature,
686
+ * token. Any failure — a malformed token, a bad signature,
676
687
  * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
677
688
  * yields `undefined` rather than throwing.
678
689
  *
@@ -708,7 +719,7 @@ async function verifyToken(token, secret) {
708
719
  }
709
720
  }
710
721
  /**
711
- * Decodes + narrows a signed token's base64url JSON payload, honoring its
722
+ * Decodes and narrows a signed token's base64url JSON payload, honoring its
712
723
  * expiry — the shared decode step {@link verifyToken} applies after a
713
724
  * signature match.
714
725
  *
@@ -716,7 +727,7 @@ async function verifyToken(token, secret) {
716
727
  * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
717
728
  * non-canonical base64url segment answers `undefined` rather than throwing),
718
729
  * 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
730
+ * `as`, and rejects an expired `exp`. Total — any
720
731
  * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
721
732
  * throws, and its `catch` answers `undefined` too.
722
733
  *
@@ -738,13 +749,13 @@ function decodeTokenPayload(encoded) {
738
749
  }
739
750
  }
740
751
  /**
741
- * Normalizes a {@link TokenSecret} to a concrete list of USABLE secrets —
742
- * backs both {@link signToken} and {@link verifyToken}.
752
+ * Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
753
+ * behind both {@link signToken} and {@link verifyToken}.
743
754
  *
744
755
  * @remarks
745
756
  * A single string becomes a one-element list; a rotation list is copied. Any
746
- * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
747
- * emptiness test; each kept secret is stored VERBATIM). The first kept
757
+ * blank/whitespace-only entry is dropped (`.trim()` is used only for that
758
+ * emptiness test; each kept secret is stored verbatim). The first kept
748
759
  * element is the signing secret; all kept are accepted on verify.
749
760
  *
750
761
  * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
@@ -766,10 +777,10 @@ function normalizeSecret(secret) {
766
777
  * Splits on `,`; for each part takes the token before the first `;`
767
778
  * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
768
779
  * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
769
- * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
770
- * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
780
+ * back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must
781
+ * honor). The result is sorted by `q` descending, a stable sort preserving
771
782
  * the header's own order within a tie — a single pass with no backtracking,
772
- * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
783
+ * so parsing stays linear in the header length (ReDoS-safe). Total — an
773
784
  * empty/malformed header yields `[]`/best-effort entries, never throws.
774
785
  *
775
786
  * @param header - The raw weighted header value
@@ -813,7 +824,7 @@ function parseAcceptHeader(header) {
813
824
  * each offered coding.
814
825
  *
815
826
  * @remarks
816
- * Prefers an EXACT named match (including an explicit `;q=0` rejection);
827
+ * Prefers an exact named match (including an explicit `;q=0` rejection);
817
828
  * failing that, a bare `*` wildcard's q applies. A coding that is neither
818
829
  * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
819
830
  * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
@@ -835,7 +846,8 @@ function computeCodingQuality(entries, coding) {
835
846
  }
836
847
  /**
837
848
  * Picks the highest-scoring content-coding the server offers against already
838
- * parsed `Accept-Encoding` entries.
849
+ * parsed `Accept-Encoding` entries — the shared selection leaf behind
850
+ * {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.
839
851
  *
840
852
  * @remarks
841
853
  * The single selection leaf behind both doors onto this axis —
@@ -843,9 +855,9 @@ function computeCodingQuality(entries, coding) {
843
855
  * entity — so the scoring loop has one implementation. Scores each `available`
844
856
  * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
845
857
  * 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
858
+ * `available` the server's preference order. An empty `available` list, and a
847
859
  * list the client rejects outright, both yield `undefined` (identity — no
848
- * compression). TOTAL on hostile input.
860
+ * compression). Total on hostile input.
849
861
  *
850
862
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
851
863
  * @param entries - The parsed {@link AcceptEntry} list
@@ -878,7 +890,7 @@ function resolveCoding(entries, available) {
878
890
  * Parses the header ({@link parseAcceptHeader}) and hands the entries to
879
891
  * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
880
892
  * the two doors onto this axis cannot drift. Returns `undefined` when the
881
- * client accepts none of `available` (identity — no compression). TOTAL on
893
+ * client accepts none of `available` (identity — no compression). Total on
882
894
  * hostile input.
883
895
  *
884
896
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
@@ -896,7 +908,7 @@ function negotiateEncoding(header, available) {
896
908
  return resolveCoding(parseAcceptHeader(header), available);
897
909
  }
898
910
  /**
899
- * Reports the rank + quality of one `candidate` media type against the parsed `Accept`
911
+ * Reports the rank and quality of one `candidate` media type against the parsed `Accept`
900
912
  * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
901
913
  * uses to score each `available` candidate.
902
914
  *
@@ -910,7 +922,7 @@ function negotiateEncoding(header, available) {
910
922
  * rank tie the highest `q` wins.
911
923
  *
912
924
  * @param entries - The parsed {@link AcceptEntry} list
913
- * @param candidate - The candidate media type to score (e.g. `'text/html'`)
925
+ * @param candidate - The candidate media type to score (for example `'text/html'`)
914
926
  * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
915
927
  *
916
928
  * @example
@@ -953,7 +965,7 @@ function matchMediaType(entries, candidate) {
953
965
  * is an explicit rejection).
954
966
  *
955
967
  * @param entries - The parsed {@link AcceptEntry} list
956
- * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
968
+ * @param candidate - The candidate language tag to score (for example `'en-US'`)
957
969
  * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
958
970
  *
959
971
  * @example
@@ -987,8 +999,8 @@ function computeLanguageQuality(entries, candidate) {
987
999
  * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
988
1000
  * type, a `+json`/`+xml` structured suffix, or one of the explicit
989
1001
  * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
990
- * binary (`image/png`, `application/zip`) is NOT compressible. An
991
- * absent/empty type is not compressible. TOTAL.
1002
+ * binary (`image/png`, `application/zip`) is not compressible. An
1003
+ * absent/empty type is not compressible. Total.
992
1004
  *
993
1005
  * @param type - The response `Content-Type` header value (with or without parameters)
994
1006
  * @returns True if the type is text-shaped and worth compressing; false otherwise
@@ -1008,13 +1020,13 @@ function isCompressibleType(type) {
1008
1020
  return COMPRESSIBLE_TYPES.has(bare);
1009
1021
  }
1010
1022
  /**
1011
- * Computes a CONTENT `ETag` over a fully-buffered response body by using WebCrypto.
1023
+ * Computes a content `ETag` over a fully-buffered response body by using WebCrypto.
1012
1024
  *
1013
1025
  * @remarks
1014
1026
  * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
1015
- * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
1016
- * default, encoding-AGNOSTIC, so the tag survives a downstream content
1017
- * re-encoding (gzip) and still matches on revalidation — or a STRONG one
1027
+ * digest as a weak validator (`W/"<hash>"`) when `weak` is `true` — the
1028
+ * default, encoding-agnostic, so the tag survives a downstream content
1029
+ * re-encoding (gzip) and still matches on revalidation — or a strong one
1018
1030
  * (`"<hash>"`, byte-identity) when `weak` is `false`.
1019
1031
  *
1020
1032
  * @param body - The full (uncompressed) response body to hash
@@ -1033,8 +1045,8 @@ async function computeBodyETag(body, weak = true) {
1033
1045
  return weak ? `W/"${hex}"` : `"${hex}"`;
1034
1046
  }
1035
1047
  /**
1036
- * Strips the WEAK indicator (`W/`) from an entity-tag, returning its opaque
1037
- * comparison body — the reduction {@link matchesETag} applies to both sides
1048
+ * Strips the weak indicator (`W/`) from an entity-tag, returning its opaque
1049
+ * comparison body — the reduction {@link matchesETag} applies to each side
1038
1050
  * before the RFC 7232 §2.3.2 weak comparison.
1039
1051
  *
1040
1052
  * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
@@ -1051,14 +1063,14 @@ function unwrapETag(tag) {
1051
1063
  }
1052
1064
  /**
1053
1065
  * Checks whether a request's `If-None-Match` header matches a resource's current
1054
- * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
1066
+ * `ETag` — the RFC 7232 §2.3.2 weak comparison.
1055
1067
  *
1056
1068
  * @remarks
1057
- * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
1058
- * listed tag matches), or the `*` wildcard (matches ANY current
1069
+ * `If-None-Match` is a comma-separated list of entity-tags (matches if any
1070
+ * listed tag matches), or the `*` wildcard (matches any current
1059
1071
  * representation — only a list of exactly `*` is the wildcard). Comparison is
1060
- * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
1061
- * through {@link unwrapETag} before comparing the opaque body). TOTAL — a
1072
+ * weak: `W/"abc"` and `"abc"` are equal (each side's weak prefix is stripped
1073
+ * through {@link unwrapETag} before comparing the opaque body). Total — a
1062
1074
  * malformed/empty header matches nothing, never throws.
1063
1075
  *
1064
1076
  * @param header - The raw `If-None-Match` header value
@@ -1084,17 +1096,17 @@ function matchesETag(header, etag) {
1084
1096
  }
1085
1097
  /**
1086
1098
  * Parses an HTTP `Range` request header against a known resource `size` —
1087
- * TOTAL, returning a {@link RangeSpec} or `undefined`.
1099
+ * total, returning a {@link RangeSpec} or `undefined`.
1088
1100
  *
1089
1101
  * @remarks
1090
1102
  * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1091
1103
  * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1092
- * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1104
+ * `[0, size - 1]` (the HTTP inclusive-end convention). Returns
1093
1105
  * `{ satisfiable: true, start, end }` for an overlapping range,
1094
1106
  * `{ satisfiable: false }` for a range wholly past the resource, and
1095
- * `undefined` for the "serve the whole resource" case: an ABSENT header, a
1096
- * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
1097
- * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1107
+ * `undefined` for the "serve the whole resource" case: an absent header, a
1108
+ * non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
1109
+ * supported), or any malformed/non-finite bound. Never throws on a hostile
1098
1110
  * header.
1099
1111
  *
1100
1112
  * @param header - The raw `Range` header value
@@ -1151,9 +1163,9 @@ function parseRange(header, size) {
1151
1163
  * @remarks
1152
1164
  * `'*'` and a single origin string pass straight through. An allow-list
1153
1165
  * echoes the request's `Origin` only when it is present in the list, else
1154
- * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1166
+ * `undefined` (no header set). Security: the literal `'null'` origin — sent
1155
1167
  * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1156
- * NEVER reflected even if `'null'` were listed, closing the hostile-context
1168
+ * never reflected even if `'null'` were listed, closing the hostile-context
1157
1169
  * cross-origin-access hole.
1158
1170
  *
1159
1171
  * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
@@ -1221,15 +1233,15 @@ function resolveSecurityHeader(value, fallback) {
1221
1233
  return value ?? fallback;
1222
1234
  }
1223
1235
  /**
1224
- * Checks whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1225
- * header + `context.state`.
1236
+ * Checks whether a client-supplied `X-Request-ID` is safe to echo into a response
1237
+ * header and `context.state`.
1226
1238
  *
1227
1239
  * @remarks
1228
- * A request id is echoed RAW into a response header and log lines, so an
1240
+ * A request id is echoed raw into a response header and log lines, so an
1229
1241
  * untrusted one is a header-injection + log-injection + DoS vector. This
1230
1242
  * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
1231
1243
  * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
1232
- * TOTAL — never throws.
1244
+ * Total — never throws.
1233
1245
  *
1234
1246
  * @param value - The candidate incoming request id
1235
1247
  * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
@@ -1251,7 +1263,7 @@ function isValidRequestId(value) {
1251
1263
  * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
1252
1264
  * is the identity) or any string that does not expand to exactly eight
1253
1265
  * hextets. Expands a single `::` into the missing zero hextets, takes the
1254
- * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
1266
+ * first four (the `/64` prefix), normalizes each (lower-case, no leading
1255
1267
  * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
1256
1268
  * first. Total — a malformed address returns `undefined`.
1257
1269
  *
@@ -1294,11 +1306,11 @@ function computeIPv6Network(address) {
1294
1306
  return `${prefix.join(":")}::/64`;
1295
1307
  }
1296
1308
  /**
1297
- * Collapses a client IP into its rate-limit BUCKET key — an IPv6 address to
1309
+ * Collapses a client IP into its rate-limit bucket key — an IPv6 address to
1298
1310
  * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1299
1311
  *
1300
1312
  * @remarks
1301
- * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1313
+ * A residential/mobile IPv6 user is routinely handed a whole `/64`, so a
1302
1314
  * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1303
1315
  * real identity is the `/64` network. Delegates the IPv6 collapse to
1304
1316
  * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
@@ -1320,7 +1332,7 @@ function computeClientKey(address) {
1320
1332
  * Serializes one {@link SSEMessage} to the SSE wire.
1321
1333
  *
1322
1334
  * @remarks
1323
- * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1335
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then one
1324
1336
  * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1325
1337
  * (so a consuming parser's multi-`data` concat reproduces the original
1326
1338
  * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
@@ -1344,9 +1356,9 @@ function serializeEvent(message) {
1344
1356
  return `${lines.join("\n")}\n\n`;
1345
1357
  }
1346
1358
  /**
1347
- * Checks whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1348
- * or `prototype` — the three keys that, assigned onto a normal object, can
1349
- * reach and mutate `Object.prototype`.
1359
+ * Checks whether a key is a prototype-pollution vector — `__proto__`,
1360
+ * `constructor`, or `prototype`, each of which can reach and mutate
1361
+ * `Object.prototype` when it is assigned onto a normal object.
1350
1362
  *
1351
1363
  * @param key - The candidate object key
1352
1364
  * @returns True if `key` is one of the three prototype-pollution keys; false otherwise
@@ -1361,12 +1373,11 @@ function isDangerousKey(key) {
1361
1373
  return key === "__proto__" || key === "constructor" || key === "prototype";
1362
1374
  }
1363
1375
  /**
1364
- * Strips the prototype-pollution keys from a parsed value IN PLACE,
1365
- * recursively.
1376
+ * Strips the prototype-pollution keys from a parsed value in place, recursively.
1366
1377
  *
1367
1378
  * @remarks
1368
- * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1369
- * enumerable `__proto__` DATA property — but that own key becomes a
1379
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
1380
+ * enumerable `__proto__` data property — but that own key becomes a
1370
1381
  * pollution gadget the moment a downstream deep-merge copies it onto a live
1371
1382
  * object. This walks the value and `delete`s any own {@link isDangerousKey}
1372
1383
  * key at every depth, recursing into nested objects + array elements.
@@ -1405,7 +1416,7 @@ function scrubPrototype(value) {
1405
1416
  * @remarks
1406
1417
  * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
1407
1418
  * throwing a {@link ContentTooLargeError} (413) the instant the running total
1408
- * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
1419
+ * exceeds `limit` — before the rest of the stream is buffered — rather than
1409
1420
  * collecting an unbounded body. A bodyless request (`request.body === null`)
1410
1421
  * resolves an empty array. A non-positive `limit` means unbounded.
1411
1422
  *
@@ -1448,11 +1459,11 @@ async function collectRequestBody(request, limit) {
1448
1459
  * whether a request body needs transparent decompression.
1449
1460
  *
1450
1461
  * @remarks
1451
- * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1462
+ * Lower-cases + trims and returns the matching {@link Encoding} only for
1452
1463
  * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
1453
1464
  * absent header, `identity`, an unknown value, or a
1454
1465
  * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1455
- * TOTAL — never asserts the loose `string | null` header.
1466
+ * Total — never asserts the loose `string | null` header.
1456
1467
  *
1457
1468
  * @param header - The raw `Content-Encoding` header value
1458
1469
  * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
@@ -1470,12 +1481,12 @@ function parseEncoding(header) {
1470
1481
  }
1471
1482
  /**
1472
1483
  * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
1473
- * transparently through `DecompressionStream`, capping the DECOMPRESSED output —
1484
+ * transparently through `DecompressionStream`, capping the decompressed output —
1474
1485
  * the zip-bomb defense.
1475
1486
  *
1476
1487
  * @remarks
1477
1488
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1478
- * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1489
+ * `TransformStream` that aborts the pipe the instant the running decompressed
1479
1490
  * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1480
1491
  * has no `maxOutputLength` knob. A cap breach surfaces
1481
1492
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
@@ -1525,9 +1536,10 @@ async function decompressRequestBody(bytes, encoding, cap) {
1525
1536
  return merged;
1526
1537
  }
1527
1538
  /**
1528
- * Collects + decodes a `Request` body — the shared body-collection pipeline
1539
+ * Collects and decodes a `Request` body — the shared body-collection pipeline
1529
1540
  * surfaced to middleware and handlers as the middleware context's cached
1530
- * `body()`.
1541
+ * `body()`. An empty body and a malformed `application/json` body each decode to
1542
+ * `undefined`.
1531
1543
  *
1532
1544
  * @remarks
1533
1545
  * Collects the wire body capped at `options.limit` bytes ({@link
@@ -1538,13 +1550,11 @@ async function decompressRequestBody(bytes, encoding, cap) {
1538
1550
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1539
1551
  * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1540
1552
  * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1541
- * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1542
- * decodes to `undefined`.
1553
+ * scrubPrototype}); any other type decodes as UTF-8 text.
1543
1554
  *
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.
1555
+ * A malformed JSON body is total: it decodes rather than throwing, so a handler
1556
+ * that must reject one checks for `undefined` itself, and nothing in the returned
1557
+ * value tells an empty body from a malformed one.
1548
1558
  *
1549
1559
  * @param request - The `Request` to read the body from
1550
1560
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
@@ -1603,18 +1613,19 @@ async function probePort(port) {
1603
1613
  return address.port;
1604
1614
  }
1605
1615
  /**
1606
- * Finds a FREE TCP port — binds a throwaway `node:net` server, reads the
1607
- * OS-assigned port, closes it, and resolves that port.
1616
+ * Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`
1617
+ * port where one is given and on an ephemeral port otherwise, reads the bound
1618
+ * port, closes the server, and resolves that port.
1608
1619
  *
1609
1620
  * @remarks
1610
1621
  * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
1611
- * and returns it. With a `preferred` port it tries THAT port first and
1612
- * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
1622
+ * and returns it. With a `preferred` port it tries that port first and
1623
+ * returns it when free; if already in use (`EADDRINUSE`) it falls back to an
1613
1624
  * ephemeral free port rather than rejecting — a caller always gets a usable
1614
1625
  * port. It binds then immediately closes a probe server, so the returned
1615
1626
  * port is free at the instant of the probe (an inherent TOCTOU race — bind it
1616
1627
  * promptly). Rejects only on an unexpected listen error other than a taken
1617
- * `preferred` port (e.g. a permission fault). A listener whose address is not
1628
+ * `preferred` port (for example, a permission fault). A listener whose address is not
1618
1629
  * an {@link import('node:net').AddressInfo} — a pipe listener, which this
1619
1630
  * package's options cannot request — rejects with a `TypeError` rather than
1620
1631
  * reporting `0`, because `0` is this package's own request for an ephemeral
@@ -1645,13 +1656,13 @@ async function discoverPort(preferred) {
1645
1656
  //#region src/server/Negotiator.ts
1646
1657
  /**
1647
1658
  * Represents the content-negotiation machine over the weighted `Accept` family — a
1648
- * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1659
+ * reusable, cross-middleware entity rather than a middleware. Implements exactly
1649
1660
  * {@link NegotiatorInterface}.
1650
1661
  *
1651
1662
  * @remarks
1652
1663
  * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1653
1664
  * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1654
- * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
1665
+ * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
1655
1666
  * rest of the substrate uses — one parser, never two. `format` reads the
1656
1667
  * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1657
1668
  * the winner — or answers `406 Not Acceptable`.
@@ -1707,7 +1718,7 @@ var Negotiator = class {
1707
1718
  * answering 406 when none matches.
1708
1719
  *
1709
1720
  * @remarks
1710
- * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1721
+ * Errors thrown by the negotiated handler propagate unmodified — the
1711
1722
  * server boundary classifies them, never this negotiator.
1712
1723
  */
1713
1724
  async format(request, context, handlers) {
@@ -1725,37 +1736,37 @@ var Negotiator = class {
1725
1736
  /**
1726
1737
  * Represents the HTTP server facade — an observable `node:http` lifecycle composing this
1727
1738
  * module's own middleware onion around a consumed `@orkestrel/router`
1728
- * dispatcher.
1739
+ * dispatcher. Implements exactly {@link ServerInterface}.
1729
1740
  *
1730
1741
  * @typeParam TState - The consumer's opaque per-request state type
1731
1742
  *
1732
1743
  * @remarks
1733
1744
  * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
1734
1745
  * server, binds the configured {@link ServerOptions.host} / {@link
1735
- * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1746
+ * ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the
1736
1747
  * bound address), exposes that {@link AddressInfo} through `address`, observes
1737
1748
  * caller cancellation plus the configured `timeouts.start` deadline while the
1738
1749
  * bind is pending, and transitions `idle → starting → listening`. A
1739
1750
  * cancelled or expired bind closes its partial server and resets to `idle` for
1740
1751
  * another start. `stop()` transitions
1741
1752
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1742
- * so in-flight handlers observe cancellation, drains in-flight requests AND
1753
+ * so in-flight handlers observe cancellation, drains in-flight requests and
1743
1754
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1744
1755
  * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1745
1756
  * still open. `destroy()` is the idempotent final teardown.
1746
1757
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1747
1758
  * `close`); a `Request` is built through the router's `buildRequest`, its
1748
- * `signal` LINKED to this run's stop signal through `@orkestrel/abort`'s
1759
+ * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
1749
1760
  * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1750
- * `buildRequest`'s own abort, armed by BOTH request-side and response-side
1761
+ * `buildRequest`'s own abort, armed by request-side and response-side
1751
1762
  * 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
1763
+ * so a handler awaiting `request.signal` observes either); `context.state` is built through
1753
1764
  * {@link ServerOptions.state} from the connection facts; the composed
1754
1765
  * middleware onion runs, terminating in `dispatcher.handle`; the result is
1755
1766
  * written back through `sendResponse`.
1756
- * - **The built-in boundary** wraps the WHOLE per-request chain, including
1767
+ * - **The built-in boundary** wraps the whole per-request chain, including
1757
1768
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1758
- * throw (e.g. a malformed `Host` header) to a silent `400` with no
1769
+ * throw (for example, a malformed `Host` header) to a silent `400` with no
1759
1770
  * `error` emit; everything after (`Request` reconstruction, connection
1760
1771
  * facts, `state`, the composed onion, and `dispatcher.handle`) runs
1761
1772
  * behind the outer boundary — a thrown `HTTPError` renders as its status +
@@ -1767,12 +1778,12 @@ var Negotiator = class {
1767
1778
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1768
1779
  * throwing handler is treated as declined and surfaced on `error`, an
1769
1780
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1770
- * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1781
+ * A claimed socket joins `#upgraded` until it closes: the claimant still
1771
1782
  * owns it, and the tracking exists because node detaches an upgraded socket
1772
1783
  * from the set its own close calls walk, so nothing else can end it.
1773
1784
  * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1774
1785
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1775
- * routes it to the `error` OPTION (not the domain `error` event).
1786
+ * routes it to the `error` option rather than to the domain `error` event.
1776
1787
  */
1777
1788
  var Server = class {
1778
1789
  #id;
@@ -2090,7 +2101,7 @@ var Server = class {
2090
2101
  * @remarks
2091
2102
  * Builds the `Response` at construction from
2092
2103
  * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
2093
- * merged OVER them, at `options.status` (default `200`). A caller repeating one
2104
+ * merged over them, at `options.status` (default `200`). A caller repeating one
2094
2105
  * of those keys therefore replaces the seam's value, in any casing. The
2095
2106
  * instance owns the stream's
2096
2107
  * controller, its text encoder, the closed flag, and the parked producer's
@@ -2102,7 +2113,7 @@ var Server = class {
2102
2113
  * receiving `false` awaits `drain()`; that promise resolves on the next
2103
2114
  * consumer pull restoring capacity, or on stream closure. `comment` writes a
2104
2115
  * `: 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
2116
+ * stream. Every method is a safe no-op once `closed` (ended by `end()`, or
2106
2117
  * the consumer cancelled the stream), so a late write never throws.
2107
2118
  *
2108
2119
  * The readiness signal reflects only the process-local `ReadableStream`
@@ -2203,11 +2214,18 @@ var Stream = class {
2203
2214
  *
2204
2215
  * @example
2205
2216
  * ```ts
2217
+ * import type { MiddlewareContext } from '@src/server'
2206
2218
  * import { createNegotiator } from '@src/server'
2207
2219
  *
2220
+ * declare const context: MiddlewareContext<Record<string, never>>
2221
+ *
2208
2222
  * const negotiator = createNegotiator()
2209
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
2210
- * // 'text/html'
2223
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'
2224
+ * negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
2225
+ * negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'
2226
+ * await negotiator.format(new Request('http://x'), context, {
2227
+ * 'application/json': (_request, _context) => Response.json({ ok: true }),
2228
+ * })
2211
2229
  * ```
2212
2230
  */
2213
2231
  function createNegotiator() {
@@ -2221,20 +2239,34 @@ function createNegotiator() {
2221
2239
  * @param options - {@link ServerOptions}
2222
2240
  * @returns A {@link ServerInterface}, not yet started
2223
2241
  *
2224
- * @example
2242
+ * @example Quickstart: dispatcher, middleware, lifecycle
2225
2243
  * ```ts
2226
- * import { createServer } from '@src/server'
2244
+ * import type { MiddlewareHandler } from '@orkestrel/server'
2245
+ * import { createServer } from '@orkestrel/server'
2227
2246
  * import { createDispatcher } from '@orkestrel/router'
2228
2247
  *
2229
- * const dispatcher = createDispatcher<{ readonly ip?: string }>()
2248
+ * interface State {
2249
+ * readonly requestId: string
2250
+ * readonly ip: string | undefined
2251
+ * }
2252
+ *
2253
+ * const dispatcher = createDispatcher<State>()
2230
2254
  * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
2231
2255
  *
2232
- * const server = createServer({
2256
+ * const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {
2257
+ * const response = await next()
2258
+ * response.headers.set('X-Request-ID', context.state.requestId)
2259
+ * return response
2260
+ * }
2261
+ *
2262
+ * const server = createServer<State>({
2233
2263
  * dispatcher,
2234
- * state: (connection) => ({ ip: connection.ip }),
2264
+ * state: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),
2235
2265
  * })
2266
+ * server.use(logRequestId)
2236
2267
  * const port = await server.start()
2237
2268
  * await server.stop()
2269
+ * await server.destroy()
2238
2270
  * ```
2239
2271
  */
2240
2272
  function createServer(options) {