@orkestrel/server 0.0.18 → 0.0.20

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