@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,10 +1,10 @@
1
- import { AddressInfo } from 'node:net';
2
- import { DispatcherInterface } from '@orkestrel/router';
3
- import { Duplex } from 'node:stream';
4
- import { EmitterErrorHandler } from '@orkestrel/emitter';
5
- import { EmitterHooks } from '@orkestrel/emitter';
6
- import { EmitterInterface } from '@orkestrel/emitter';
7
- import { IncomingMessage } from 'node:http';
1
+ import type { AddressInfo } from 'node:net';
2
+ import type { DispatcherInterface } from '@orkestrel/router';
3
+ import type { Duplex } from 'node:stream';
4
+ import type { EmitterErrorHandler } from '@orkestrel/emitter';
5
+ import type { EmitterHooks } from '@orkestrel/emitter';
6
+ import type { EmitterInterface } from '@orkestrel/emitter';
7
+ import type { IncomingMessage } from 'node:http';
8
8
 
9
9
  /**
10
10
  * Represents one parsed entry of a weighted `Accept` / `Accept-Encoding` /
@@ -14,7 +14,7 @@ import { IncomingMessage } from 'node:http';
14
14
  * @remarks
15
15
  * `value` is the lower-cased token (`text/html`, `gzip`, `en-us`, or a
16
16
  * wildcard). `q` is the quality weight in `[0, 1]` (the `;q=` parameter,
17
- * default `1` when absent); a `;q=0` entry explicitly REJECTS that token — a
17
+ * default `1` when absent); a `;q=0` entry explicitly rejects that token — a
18
18
  * parser keeps it (so a caller can honor the rejection) rather than
19
19
  * dropping it.
20
20
  */
@@ -30,14 +30,14 @@ export declare interface AcceptEntry {
30
30
  * @param limit - The maximum request body size in bytes; a larger body
31
31
  * throws a {@link import('./errors.js').ContentTooLargeError} (413).
32
32
  * Defaults to {@link DEFAULT_BODY_LIMIT}.
33
- * @param decompression - The maximum DECOMPRESSED body size in bytes (the
33
+ * @param decompression - The maximum decompressed body size in bytes (the
34
34
  * zip-bomb cap) for a `Content-Encoding: gzip` / `deflate` request body. A
35
- * highly-compressible payload small ON THE WIRE (under `limit`) can inflate
35
+ * highly-compressible payload small on the wire (under `limit`) can inflate
36
36
  * enormously, so a byte-counting `TransformStream` aborts the pipe the
37
37
  * instant decompressed output would exceed this. Defaults to {@link
38
38
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT} (16 MiB) —
39
- * INDEPENDENT of `limit`, not aligned with it; a non-positive value means
40
- * UNCAPPED decompressed output — use only when `limit` already bounds the
39
+ * independent of `limit`, not aligned with it; a non-positive value means
40
+ * uncapped decompressed output — use only when `limit` already bounds the
41
41
  * compressed input.
42
42
  */
43
43
  export declare interface BodyOptions {
@@ -51,7 +51,7 @@ export declare interface BodyOptions {
51
51
  * @remarks
52
52
  * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
53
53
  * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
54
- * a cookie when those MATCH the one it set).
54
+ * a cookie when those match the one it set).
55
55
  *
56
56
  * @param headers - The response `Headers` to write into
57
57
  * @param name - The cookie name to clear
@@ -71,7 +71,7 @@ export declare function clearCookie(headers: Headers, name: string, options?: Co
71
71
  * @remarks
72
72
  * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
73
73
  * throwing a {@link ContentTooLargeError} (413) the instant the running total
74
- * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
74
+ * exceeds `limit` — before the rest of the stream is buffered — rather than
75
75
  * collecting an unbounded body. A bodyless request (`request.body === null`)
76
76
  * resolves an empty array. A non-positive `limit` means unbounded.
77
77
  *
@@ -88,18 +88,18 @@ export declare function clearCookie(headers: Headers, name: string, options?: Co
88
88
  export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
89
89
 
90
90
  /**
91
- * Composes an ordered chain of {@link MiddlewareHandler}s around a `terminal`
91
+ * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
92
92
  * handler into one request handler — the frozen middleware seam.
93
93
  *
94
94
  * @remarks
95
- * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
96
- * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
95
+ * `middleware[0]` runs outermost: it is invoked first, and its call to `next`
96
+ * runs `middleware[1]`, and so on until the last middleware's `next` invokes
97
97
  * `terminal`. Each middleware's `next` may be called with a substituted
98
98
  * `Request` (the downstream chain then sees that request instead of the
99
99
  * original), called with no argument (the original request continues
100
- * downstream), or NOT called at all (a short-circuit — the middleware's own
100
+ * downstream), or not called at all (a short-circuit — the middleware's own
101
101
  * returned `Response` is sent, and everything downstream never runs). A
102
- * SECOND call to the same `next` within one middleware invocation REJECTS —
102
+ * second call to the same `next` within one middleware invocation rejects —
103
103
  * each link runs the chain at most once, so a middleware cannot fork the
104
104
  * request into two divergent downstream runs.
105
105
  *
@@ -122,13 +122,13 @@ export declare function collectRequestBody(request: Request, limit: number): Pro
122
122
  export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
123
123
 
124
124
  /**
125
- * Holds the set of bare `Content-Type`s `isCompressibleType` treats as
126
- * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
127
- * `+xml`) rules that helper also applies.
125
+ * Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
126
+ * beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
127
+ * helper also applies.
128
128
  *
129
129
  * @remarks
130
130
  * The text-shaped application types worth compressing (JSON / JavaScript /
131
- * XML / SVG / WASM / a few document formats) — NOT already-compressed
131
+ * XML / SVG / WASM / a few document formats) — never already-compressed
132
132
  * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
133
133
  * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
134
134
  * withholds `add` / `delete` / `clear` from the shared default, so a consumer
@@ -137,13 +137,13 @@ export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHand
137
137
  export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
138
138
 
139
139
  /**
140
- * Computes a CONTENT `ETag` over a fully-buffered response body by using WebCrypto.
140
+ * Computes a content `ETag` over a fully-buffered response body by using WebCrypto.
141
141
  *
142
142
  * @remarks
143
143
  * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
144
- * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
145
- * default, encoding-AGNOSTIC, so the tag survives a downstream content
146
- * re-encoding (gzip) and still matches on revalidation — or a STRONG one
144
+ * digest as a weak validator (`W/"<hash>"`) when `weak` is `true` — the
145
+ * default, encoding-agnostic, so the tag survives a downstream content
146
+ * re-encoding (gzip) and still matches on revalidation — or a strong one
147
147
  * (`"<hash>"`, byte-identity) when `weak` is `false`.
148
148
  *
149
149
  * @param body - The full (uncompressed) response body to hash
@@ -159,11 +159,11 @@ export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
159
159
  export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: boolean): Promise<string>;
160
160
 
161
161
  /**
162
- * Collapses a client IP into its rate-limit BUCKET key — an IPv6 address to
162
+ * Collapses a client IP into its rate-limit bucket key — an IPv6 address to
163
163
  * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
164
164
  *
165
165
  * @remarks
166
- * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
166
+ * A residential/mobile IPv6 user is routinely handed a whole `/64`, so a
167
167
  * per-`/128` rate limit is trivially bypassed by rotating host bits — the
168
168
  * real identity is the `/64` network. Delegates the IPv6 collapse to
169
169
  * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
@@ -186,7 +186,7 @@ export declare function computeClientKey(address: string): string;
186
186
  * each offered coding.
187
187
  *
188
188
  * @remarks
189
- * Prefers an EXACT named match (including an explicit `;q=0` rejection);
189
+ * Prefers an exact named match (including an explicit `;q=0` rejection);
190
190
  * failing that, a bare `*` wildcard's q applies. A coding that is neither
191
191
  * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
192
192
  * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
@@ -211,7 +211,7 @@ export declare function computeCodingQuality(entries: readonly AcceptEntry[], co
211
211
  * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
212
212
  * is the identity) or any string that does not expand to exactly eight
213
213
  * hextets. Expands a single `::` into the missing zero hextets, takes the
214
- * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
214
+ * first four (the `/64` prefix), normalizes each (lower-case, no leading
215
215
  * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
216
216
  * first. Total — a malformed address returns `undefined`.
217
217
  *
@@ -237,7 +237,7 @@ export declare function computeIPv6Network(address: string): string | undefined;
237
237
  * is an explicit rejection).
238
238
  *
239
239
  * @param entries - The parsed {@link AcceptEntry} list
240
- * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
240
+ * @param candidate - The candidate language tag to score (for example `'en-US'`)
241
241
  * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
242
242
  *
243
243
  * @example
@@ -250,7 +250,7 @@ export declare function computeIPv6Network(address: string): string | undefined;
250
250
  export declare function computeLanguageQuality(entries: readonly AcceptEntry[], candidate: string): number;
251
251
 
252
252
  /**
253
- * Represents the per-request connection facts the server face injects — the ONLY data
253
+ * Represents the per-request connection facts the server face injects — the only data
254
254
  * that genuinely exists solely on the socket, surfaced so middleware and a
255
255
  * consumer's `state` factory stay core-pure.
256
256
  *
@@ -306,14 +306,14 @@ export declare class ContentTooLargeError extends HTTPError {
306
306
  *
307
307
  * @param path - The `Path` directive; defaults to `'/'`.
308
308
  * @param domain - The `Domain` directive; omitted ⇒ a host-only cookie.
309
- * @param maxAge - The `Max-Age` directive in SECONDS (the wire unit, not a
309
+ * @param maxAge - The `Max-Age` directive in seconds (the wire unit, not a
310
310
  * millisecond `ttl`); `0` expires the cookie immediately.
311
311
  * @param httpOnly - The `HttpOnly` directive; defaults to `true`.
312
312
  * @param secure - The `Secure` directive: `true` forces it, `false`
313
313
  * suppresses it, and omitted/`undefined` (the default) derives it from the
314
314
  * connection through {@link import('./helpers.js').resolveSecure} — `Secure` on
315
315
  * a TLS connection, off over plaintext HTTP ({@link
316
- * Connection.encrypted}). A `sameSite: 'None'` cookie is ALWAYS
316
+ * Connection.encrypted}). A `sameSite: 'None'` cookie is always
317
317
  * `Secure` regardless (the spec requires it).
318
318
  * @param sameSite - The `SameSite` directive; defaults to `'Lax'`.
319
319
  */
@@ -334,11 +334,18 @@ export declare interface CookieOptions {
334
334
  *
335
335
  * @example
336
336
  * ```ts
337
+ * import type { MiddlewareContext } from '@src/server'
337
338
  * import { createNegotiator } from '@src/server'
338
339
  *
340
+ * declare const context: MiddlewareContext<Record<string, never>>
341
+ *
339
342
  * const negotiator = createNegotiator()
340
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
341
- * // 'text/html'
343
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'
344
+ * negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
345
+ * negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'
346
+ * await negotiator.format(new Request('http://x'), context, {
347
+ * 'application/json': (_request, _context) => Response.json({ ok: true }),
348
+ * })
342
349
  * ```
343
350
  */
344
351
  export declare function createNegotiator(): NegotiatorInterface;
@@ -351,20 +358,34 @@ export declare function createNegotiator(): NegotiatorInterface;
351
358
  * @param options - {@link ServerOptions}
352
359
  * @returns A {@link ServerInterface}, not yet started
353
360
  *
354
- * @example
361
+ * @example Quickstart: dispatcher, middleware, lifecycle
355
362
  * ```ts
356
- * import { createServer } from '@src/server'
363
+ * import type { MiddlewareHandler } from '@orkestrel/server'
364
+ * import { createServer } from '@orkestrel/server'
357
365
  * import { createDispatcher } from '@orkestrel/router'
358
366
  *
359
- * const dispatcher = createDispatcher<{ readonly ip?: string }>()
367
+ * interface State {
368
+ * readonly requestId: string
369
+ * readonly ip: string | undefined
370
+ * }
371
+ *
372
+ * const dispatcher = createDispatcher<State>()
360
373
  * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
361
374
  *
362
- * const server = createServer({
375
+ * const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {
376
+ * const response = await next()
377
+ * response.headers.set('X-Request-ID', context.state.requestId)
378
+ * return response
379
+ * }
380
+ *
381
+ * const server = createServer<State>({
363
382
  * dispatcher,
364
- * state: (connection) => ({ ip: connection.ip }),
383
+ * state: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),
365
384
  * })
385
+ * server.use(logRequestId)
366
386
  * const port = await server.start()
367
387
  * await server.stop()
388
+ * await server.destroy()
368
389
  * ```
369
390
  */
370
391
  export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
@@ -407,7 +428,7 @@ export declare function createStream(options?: StreamOptions): StreamInterface;
407
428
  export declare function decodeCookieValue(raw: string): string;
408
429
 
409
430
  /**
410
- * Decodes + narrows a signed token's base64url JSON payload, honoring its
431
+ * Decodes and narrows a signed token's base64url JSON payload, honoring its
411
432
  * expiry — the shared decode step {@link verifyToken} applies after a
412
433
  * signature match.
413
434
  *
@@ -415,9 +436,8 @@ export declare function decodeCookieValue(raw: string): string;
415
436
  * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
416
437
  * non-canonical base64url segment answers `undefined` rather than throwing),
417
438
  * reads it as UTF-8 JSON, narrows it to a record with a string `value` without
418
- * `as`, and rejects an expired `exp`. TOTAL — any
419
- * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
420
- * throws, and its `catch` answers `undefined` too.
439
+ * `as`, and rejects an expired `exp`. Total — any decode/shape/expiry failure
440
+ * yields `undefined`, including invalid JSON (`parseJSON` answers `undefined`).
421
441
  *
422
442
  * @param encoded - The base64url-encoded payload segment (before the last `.`)
423
443
  * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
@@ -426,12 +446,12 @@ export declare function decodeTokenPayload(encoded: string): string | undefined;
426
446
 
427
447
  /**
428
448
  * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
429
- * transparently through `DecompressionStream`, capping the DECOMPRESSED output —
449
+ * transparently through `DecompressionStream`, capping the decompressed output —
430
450
  * the zip-bomb defense.
431
451
  *
432
452
  * @remarks
433
453
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
434
- * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
454
+ * `TransformStream` that aborts the pipe the instant the running decompressed
435
455
  * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
436
456
  * has no `maxOutputLength` knob. A cap breach surfaces
437
457
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
@@ -447,19 +467,22 @@ export declare function decodeTokenPayload(encoded: string): string | undefined;
447
467
  */
448
468
  export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
449
469
 
450
- /** Names the default maximum request body size (bytes) `readBody` accepts before a 413. */
470
+ /**
471
+ * Names the default maximum request body size `readBody` accepts before a 413,
472
+ * `1_048_576` bytes.
473
+ */
451
474
  export declare const DEFAULT_BODY_LIMIT = 1048576;
452
475
 
453
476
  /**
454
- * Names the default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
455
- * the body pipeline's byte-counting `TransformStream` enforces when
456
- * transparently decompressing a `Content-Encoding` request body.
477
+ * Names the default maximum decompressed request body size, `16_777_216` bytes — the
478
+ * zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when
479
+ * it transparently decompresses a `Content-Encoding` request body.
457
480
  *
458
481
  * @remarks
459
482
  * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
460
483
  * can inflate by many orders of magnitude — a classic decompression bomb.
461
- * Capping the decompressed byte count makes the pipe ABORT the moment the
462
- * output would exceed this, BEFORE the full bomb is materialized, so the
484
+ * Capping the decompressed byte count makes the pipe abort the moment the
485
+ * output would exceed this, before the full bomb is materialized, so the
463
486
  * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
464
487
  * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
465
488
  * consumer raises it through {@link import('./types.js').BodyOptions}
@@ -469,17 +492,17 @@ export declare const DEFAULT_BODY_LIMIT = 1048576;
469
492
  export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
470
493
 
471
494
  /**
472
- * Names the default graceful-stop deadline (ms) the server gives in-flight
473
- * requests on `stop()`.
495
+ * Names the default graceful-stop deadline `stop()` gives in-flight requests and
496
+ * claimed upgraded sockets, `10_000` ms.
474
497
  */
475
498
  export declare const DEFAULT_DRAIN_MS = 10000;
476
499
 
477
500
  /**
478
501
  * Lists the default {@link Encoding} content-codings the substrate offers, in
479
- * PREFERENCE order — `gzip` / `deflate`.
502
+ * preference order — `gzip` then `deflate`.
480
503
  *
481
504
  * @remarks
482
- * `identity` (no compression) is always implicitly acceptable and is NOT
505
+ * `identity` (no compression) is always implicitly acceptable and is not
483
506
  * listed here — it is the fall-through when a client accepts none of these.
484
507
  * Brotli is omitted per the core's `CompressionStream`-only decision (see
485
508
  * {@link Encoding}). Frozen so a consumer can read but never mutate the
@@ -488,18 +511,19 @@ export declare const DEFAULT_DRAIN_MS = 10000;
488
511
  export declare const DEFAULT_ENCODINGS: readonly Encoding[];
489
512
 
490
513
  /**
491
- * Finds a FREE TCP port — binds a throwaway `node:net` server, reads the
492
- * OS-assigned port, closes it, and resolves that port.
514
+ * Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`
515
+ * port where one is given and on an ephemeral port otherwise, reads the bound
516
+ * port, closes the server, and resolves that port.
493
517
  *
494
518
  * @remarks
495
519
  * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
496
- * and returns it. With a `preferred` port it tries THAT port first and
497
- * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
520
+ * and returns it. With a `preferred` port it tries that port first and
521
+ * returns it when free; if already in use (`EADDRINUSE`) it falls back to an
498
522
  * ephemeral free port rather than rejecting — a caller always gets a usable
499
523
  * port. It binds then immediately closes a probe server, so the returned
500
524
  * port is free at the instant of the probe (an inherent TOCTOU race — bind it
501
525
  * promptly). Rejects only on an unexpected listen error other than a taken
502
- * `preferred` port (e.g. a permission fault). A listener whose address is not
526
+ * `preferred` port (for example, a permission fault). A listener whose address is not
503
527
  * an {@link import('node:net').AddressInfo} — a pipe listener, which this
504
528
  * package's options cannot request — rejects with a `TypeError` rather than
505
529
  * reporting `0`, because `0` is this package's own request for an ephemeral
@@ -520,14 +544,15 @@ export declare const DEFAULT_ENCODINGS: readonly Encoding[];
520
544
  export declare function discoverPort(preferred?: number): Promise<number>;
521
545
 
522
546
  /**
523
- * Represents a content-coding the substrate compresses / decompresses with — the
524
- * `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
547
+ * Represents a content-coding the substrate compresses or decompresses with. Its
548
+ * members are the `Content-Encoding` and `Accept-Encoding` token vocabulary the
549
+ * substrate understands.
525
550
  *
526
551
  * @remarks
527
552
  * `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
528
553
  * (web-standard, no external codec); `identity` is the no-op "uncompressed"
529
554
  * coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
530
- * is deliberately OMITTED here — Brotli parity is the middleware package's
555
+ * is deliberately omitted here — Brotli parity is the middleware package's
531
556
  * node-entry decision, not this core's. A constrained set of external-spec
532
557
  * literals, so it stays a union, not a behavioral toggle.
533
558
  */
@@ -540,7 +565,7 @@ export declare type Encoding = 'gzip' | 'deflate' | 'identity';
540
565
  * @typeParam TState - The consumer's opaque per-request state type
541
566
  *
542
567
  * @remarks
543
- * Each key is a media type the route can PRODUCE (`application/json`,
568
+ * Each key is a media type the route can produce (`application/json`,
544
569
  * `text/html`, …) and each value the responder that returns that
545
570
  * representation as a `Response`. `format` negotiates the client's preferred
546
571
  * key from the request `Accept` header and invokes the matching handler, or
@@ -552,15 +577,16 @@ export declare type Encoding = 'gzip' | 'deflate' | 'identity';
552
577
  export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
553
578
 
554
579
  /**
555
- * Names the `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
556
- * an instance thrown by ANOTHER copy of this package (the dual-package
557
- * hazard — a version-skewed or workspace-linked duplicate install), where
558
- * `instanceof` alone fails because the two copies' `HTTPError` constructors
559
- * are distinct objects.
580
+ * Names the `Symbol.for`-interned brand `HTTPError` carries,
581
+ * `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
582
+ * package copies. A consumer never sets it by hand.
560
583
  *
561
584
  * @remarks
562
- * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every
563
- * copy of this package that evaluates this key resolves the SAME symbol
585
+ * The brand exists for the dual-package hazard — a version-skewed or
586
+ * workspace-linked duplicate install — where `instanceof` alone fails because
587
+ * each copy's `HTTPError` constructor is a distinct object.
588
+ * `Symbol.for` interns the symbol on the global symbol registry, so every
589
+ * copy of this package that evaluates this key resolves the same symbol
564
590
  * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
565
591
  * unequal symbol per copy and defeat the whole point of a cross-copy brand.
566
592
  */
@@ -574,7 +600,7 @@ export declare const HTTP_ERROR_BRAND: unique symbol;
574
600
  * Carries the HTTP `status` to send and an optional `context` record (the
575
601
  * offending field / value). The server's built-in error boundary catches it
576
602
  * and renders a response of `status` with the error's `message` as the body
577
- * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
603
+ * — so an `HTTPError`'s message is always client-facing (it is the handler's
578
604
  * deliberate signal), unlike a generic throw whose message is hidden unless
579
605
  * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
580
606
  * specific statuses, or throw it directly. Narrow a caught value with
@@ -629,8 +655,8 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
629
655
  * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
630
656
  * type, a `+json`/`+xml` structured suffix, or one of the explicit
631
657
  * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
632
- * binary (`image/png`, `application/zip`) is NOT compressible. An
633
- * absent/empty type is not compressible. TOTAL.
658
+ * binary (`image/png`, `application/zip`) is not compressible. An
659
+ * absent/empty type is not compressible. Total.
634
660
  *
635
661
  * @param type - The response `Content-Type` header value (with or without parameters)
636
662
  * @returns True if the type is text-shaped and worth compressing; false otherwise
@@ -644,9 +670,9 @@ export declare function isAddressInfo(value: unknown): value is AddressInfo;
644
670
  export declare function isCompressibleType(type: string): boolean;
645
671
 
646
672
  /**
647
- * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
648
- * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
649
- * attributes with before emitting them.
673
+ * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —
674
+ * the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it
675
+ * emits them.
650
676
  *
651
677
  * @remarks
652
678
  * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
@@ -666,8 +692,8 @@ export declare function isCompressibleType(type: string): boolean;
666
692
  export declare function isCookieAttribute(value: string): boolean;
667
693
 
668
694
  /**
669
- * Checks whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
670
- * cookie-token chars with NO surrounding (or interior) whitespace.
695
+ * Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
696
+ * cookie-token characters with no surrounding or interior whitespace.
671
697
  *
672
698
  * @remarks
673
699
  * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
@@ -687,9 +713,9 @@ export declare function isCookieAttribute(value: string): boolean;
687
713
  export declare function isCookieName(value: string): boolean;
688
714
 
689
715
  /**
690
- * Checks whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
691
- * or `prototype` — the three keys that, assigned onto a normal object, can
692
- * reach and mutate `Object.prototype`.
716
+ * Checks whether a key is a prototype-pollution vector — `__proto__`,
717
+ * `constructor`, or `prototype`, each of which can reach and mutate
718
+ * `Object.prototype` when it is assigned onto a normal object.
693
719
  *
694
720
  * @param key - The candidate object key
695
721
  * @returns True if `key` is one of the three prototype-pollution keys; false otherwise
@@ -703,21 +729,22 @@ export declare function isCookieName(value: string): boolean;
703
729
  export declare function isDangerousKey(key: string): boolean;
704
730
 
705
731
  /**
706
- * Narrows an unknown caught value to an {@link HTTPError} (including its
707
- * subclasses, e.g. {@link ContentTooLargeError}).
732
+ * Narrows an unknown caught value to an {@link HTTPError}, including a subclass such
733
+ * as {@link ContentTooLargeError}, and recognizes an instance from another copy of
734
+ * this package through a structural brand fallback.
708
735
  *
709
736
  * @param value - The value to test (typically a `catch` binding)
710
737
  * @returns True if `value` is an {@link HTTPError}; false otherwise
711
738
  *
712
739
  * @remarks
713
740
  * Tries `instanceof` first, then falls back to a total structural check for
714
- * an instance built by a DIFFERENT copy of this package (the dual-package
741
+ * an instance built by a different copy of this package (the dual-package
715
742
  * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
716
743
  * constructor is a distinct object from this copy's: the value must carry
717
744
  * the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
718
- * same key) AND expose the exact fields the server's error boundary reads off
745
+ * same key) and expose the exact fields the server's error boundary reads off
719
746
  * a recognized `HTTPError` — a numeric `status` and a string `message`. A
720
- * plain object that merely carries a `status` WITHOUT the brand is rejected.
747
+ * plain object that merely carries a `status` without the brand is rejected.
721
748
  *
722
749
  * @example
723
750
  * ```ts
@@ -733,14 +760,15 @@ export declare function isDangerousKey(key: string): boolean;
733
760
  export declare function isHTTPError(value: unknown): value is HTTPError;
734
761
 
735
762
  /**
736
- * Narrows an unknown caught value to a {@link ServerError}.
763
+ * Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal
764
+ * of a call the caller programmed.
737
765
  *
738
766
  * @param value - The value to test (typically a `catch` binding)
739
767
  * @returns True if `value` is a {@link ServerError}; false otherwise
740
768
  *
741
769
  * @remarks
742
- * Recognizes an instance built by THIS copy of the package. A `ServerError`
743
- * is raised by a `Server` to the caller that just invoked it, so both sides
770
+ * Recognizes an instance built by this copy of the package. A `ServerError`
771
+ * is raised by a `Server` to the caller that invoked it directly, so both sides
744
772
  * hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
745
773
  * consumer here.
746
774
  *
@@ -762,15 +790,15 @@ export declare function isHTTPError(value: unknown): value is HTTPError;
762
790
  export declare function isServerError(value: unknown): value is ServerError;
763
791
 
764
792
  /**
765
- * Checks whether a client-supplied `X-Request-ID` is SAFE to echo into a response
766
- * header + `context.state`.
793
+ * Checks whether a client-supplied `X-Request-ID` is safe to echo into a response
794
+ * header and `context.state`.
767
795
  *
768
796
  * @remarks
769
- * A request id is echoed RAW into a response header and log lines, so an
797
+ * A request id is echoed raw into a response header and log lines, so an
770
798
  * untrusted one is a header-injection + log-injection + DoS vector. This
771
799
  * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
772
800
  * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
773
- * TOTAL — never throws.
801
+ * Total — never throws.
774
802
  *
775
803
  * @param value - The candidate incoming request id
776
804
  * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
@@ -785,14 +813,14 @@ export declare function isValidRequestId(value: string): boolean;
785
813
 
786
814
  /**
787
815
  * Checks whether a request's `If-None-Match` header matches a resource's current
788
- * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
816
+ * `ETag` — the RFC 7232 §2.3.2 weak comparison.
789
817
  *
790
818
  * @remarks
791
- * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
792
- * listed tag matches), or the `*` wildcard (matches ANY current
819
+ * `If-None-Match` is a comma-separated list of entity-tags (matches if any
820
+ * listed tag matches), or the `*` wildcard (matches any current
793
821
  * representation — only a list of exactly `*` is the wildcard). Comparison is
794
- * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
795
- * through {@link unwrapETag} before comparing the opaque body). TOTAL — a
822
+ * weak: `W/"abc"` and `"abc"` are equal (each side's weak prefix is stripped
823
+ * through {@link unwrapETag} before comparing the opaque body). Total — a
796
824
  * malformed/empty header matches nothing, never throws.
797
825
  *
798
826
  * @param header - The raw `If-None-Match` header value
@@ -808,7 +836,7 @@ export declare function isValidRequestId(value: string): boolean;
808
836
  export declare function matchesETag(header: string, etag: string): boolean;
809
837
 
810
838
  /**
811
- * Reports the rank + quality of one `candidate` media type against the parsed `Accept`
839
+ * Reports the rank and quality of one `candidate` media type against the parsed `Accept`
812
840
  * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
813
841
  * uses to score each `available` candidate.
814
842
  *
@@ -822,7 +850,7 @@ export declare function matchesETag(header: string, etag: string): boolean;
822
850
  * rank tie the highest `q` wins.
823
851
  *
824
852
  * @param entries - The parsed {@link AcceptEntry} list
825
- * @param candidate - The candidate media type to score (e.g. `'text/html'`)
853
+ * @param candidate - The candidate media type to score (for example `'text/html'`)
826
854
  * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
827
855
  *
828
856
  * @example
@@ -875,7 +903,7 @@ export declare function mergeVary(existing: string | undefined, value: string):
875
903
 
876
904
  /**
877
905
  * Represents the composition context — plain data, one per request, shared by every
878
- * middleware AND (as `state`) by the route handlers behind the dispatcher.
906
+ * middleware and, as `state`, by the route handlers behind the dispatcher.
879
907
  *
880
908
  * @typeParam TState - The consumer's opaque per-request state type
881
909
  *
@@ -884,7 +912,7 @@ export declare function mergeVary(existing: string | undefined, value: string):
884
912
  * a middleware never re-parses it).
885
913
  * - `method` — the raw request verb; the dispatcher (not this seam) narrows it
886
914
  * to a known {@link import('@orkestrel/router').Method}.
887
- * - `state` — THE shared bag threaded from the adapter's `state` factory,
915
+ * - `state` — the shared bag threaded from the adapter's `state` factory,
888
916
  * through every middleware, into `dispatcher.handle`'s `state` — the same
889
917
  * object a route handler reads as `context.state`.
890
918
  * - `body()` — lazily collect the request body (byte-limited, transparently
@@ -937,7 +965,7 @@ export declare type MiddlewareHandler<TState> = (request: Request, context: Midd
937
965
  * Parses the header ({@link parseAcceptHeader}) and hands the entries to
938
966
  * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
939
967
  * the two doors onto this axis cannot drift. Returns `undefined` when the
940
- * client accepts none of `available` (identity — no compression). TOTAL on
968
+ * client accepts none of `available` (identity — no compression). Total on
941
969
  * hostile input.
942
970
  *
943
971
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
@@ -954,13 +982,13 @@ export declare function negotiateEncoding<T extends string>(header: string, avai
954
982
 
955
983
  /**
956
984
  * Represents the content-negotiation machine over the weighted `Accept` family — a
957
- * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
985
+ * reusable, cross-middleware entity rather than a middleware. Implements exactly
958
986
  * {@link NegotiatorInterface}.
959
987
  *
960
988
  * @remarks
961
989
  * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
962
990
  * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
963
- * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
991
+ * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
964
992
  * rest of the substrate uses — one parser, never two. `format` reads the
965
993
  * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
966
994
  * the winner — or answers `406 Not Acceptable`.
@@ -981,7 +1009,7 @@ export declare class Negotiator implements NegotiatorInterface {
981
1009
  * answering 406 when none matches.
982
1010
  *
983
1011
  * @remarks
984
- * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1012
+ * Errors thrown by the negotiated handler propagate unmodified — the
985
1013
  * server boundary classifies them, never this negotiator.
986
1014
  */
987
1015
  format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
@@ -1013,7 +1041,7 @@ export declare interface NegotiatorInterface {
1013
1041
  * Picks the best `available` value for a weighted `Accept`-style `header` —
1014
1042
  * the generic media-type primitive (`encoding` / `language` build on it).
1015
1043
  *
1016
- * @param header - The raw weighted header value (e.g. `text/html, application/json;q=0.9`)
1044
+ * @param header - The raw weighted header value (for example `text/html, application/json;q=0.9`)
1017
1045
  * @param available - The values the server can produce, in preference (tie-break) order
1018
1046
  * @returns The best acceptable value, or `undefined` when none is
1019
1047
  */
@@ -1023,7 +1051,7 @@ export declare interface NegotiatorInterface {
1023
1051
  * — the coding axis of the same q-value parser (a bare `*` wildcard ⇒ the
1024
1052
  * first `available`).
1025
1053
  *
1026
- * @param header - The raw `Accept-Encoding` header value (e.g. `gzip;q=1.0, deflate;q=0.8`)
1054
+ * @param header - The raw `Accept-Encoding` header value (for example `gzip;q=1.0, deflate;q=0.8`)
1027
1055
  * @param available - The codings the server offers, in preference order
1028
1056
  * @returns The best acceptable coding, or `undefined` when none is
1029
1057
  *
@@ -1041,7 +1069,7 @@ export declare interface NegotiatorInterface {
1041
1069
  * `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
1042
1070
  * bare `*` wildcard.
1043
1071
  *
1044
- * @param header - The raw `Accept-Language` header value (e.g. `en-US, en;q=0.8, fr;q=0.5`)
1072
+ * @param header - The raw `Accept-Language` header value (for example `en-US, en;q=0.8, fr;q=0.5`)
1045
1073
  * @param available - The languages the server offers, in preference order
1046
1074
  * @returns The best acceptable language, or `undefined` when none is
1047
1075
  */
@@ -1062,12 +1090,12 @@ export declare interface NegotiatorInterface {
1062
1090
 
1063
1091
  /**
1064
1092
  * Represents the downstream continuation a {@link MiddlewareHandler} invokes to run the
1065
- * rest of the onion.
1093
+ * rest of the onion — guarded so a second call within one invocation rejects.
1066
1094
  *
1067
1095
  * @remarks
1068
1096
  * Call it (optionally with a substituted `Request`) to run the downstream
1069
1097
  * chain and receive its `Response`; omit the call entirely to short-circuit
1070
- * with a `Response` built by this middleware instead. A SECOND call rejects
1098
+ * with a `Response` built by this middleware instead. A second call rejects
1071
1099
  * (the double-`next` guard) — each middleware runs the chain at most once.
1072
1100
  *
1073
1101
  * @param request - An optional replacement `Request` to hand downstream
@@ -1077,13 +1105,13 @@ export declare interface NegotiatorInterface {
1077
1105
  export declare type NextFunction = (request?: Request) => Promise<Response>;
1078
1106
 
1079
1107
  /**
1080
- * Normalizes a {@link TokenSecret} to a concrete list of USABLE secrets —
1081
- * backs both {@link signToken} and {@link verifyToken}.
1108
+ * Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
1109
+ * behind both {@link signToken} and {@link verifyToken}.
1082
1110
  *
1083
1111
  * @remarks
1084
1112
  * A single string becomes a one-element list; a rotation list is copied. Any
1085
- * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
1086
- * emptiness test; each kept secret is stored VERBATIM). The first kept
1113
+ * blank/whitespace-only entry is dropped (`.trim()` is used only for that
1114
+ * emptiness test; each kept secret is stored verbatim). The first kept
1087
1115
  * element is the signing secret; all kept are accepted on verify.
1088
1116
  *
1089
1117
  * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
@@ -1104,10 +1132,10 @@ export declare function normalizeSecret(secret: TokenSecret): readonly string[];
1104
1132
  * Splits on `,`; for each part takes the token before the first `;`
1105
1133
  * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
1106
1134
  * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
1107
- * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
1108
- * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
1135
+ * back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must
1136
+ * honor). The result is sorted by `q` descending, a stable sort preserving
1109
1137
  * the header's own order within a tie — a single pass with no backtracking,
1110
- * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
1138
+ * so parsing stays linear in the header length (ReDoS-safe). Total — an
1111
1139
  * empty/malformed header yields `[]`/best-effort entries, never throws.
1112
1140
  *
1113
1141
  * @param header - The raw weighted header value
@@ -1125,13 +1153,13 @@ export declare function parseAcceptHeader(header: string): readonly AcceptEntry[
1125
1153
  * Parses a raw `Cookie:` request header into a `name → value` lookup.
1126
1154
  *
1127
1155
  * @remarks
1128
- * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
1156
+ * Splits on `;`; the first segment keeps any leading whitespace (a genuine
1129
1157
  * cookie-pair separator never precedes it), while every later segment has its
1130
1158
  * inter-pair separator (ASCII space/tab) stripped before parsing — so a
1131
- * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
1159
+ * whitespace-padded name (`' __Host-x=evil'`) is rejected by
1132
1160
  * {@link isCookieName} rather than silently reconciling into a
1133
1161
  * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
1134
- * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
1162
+ * name, is skipped; a later duplicate name wins. Total — an absent/empty/
1135
1163
  * malformed header yields an empty record, never throws.
1136
1164
  *
1137
1165
  * @param header - The raw `Cookie` header value (possibly `undefined`)
@@ -1150,11 +1178,11 @@ export declare function parseCookies(header: string | undefined): Record<string,
1150
1178
  * whether a request body needs transparent decompression.
1151
1179
  *
1152
1180
  * @remarks
1153
- * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1181
+ * Lower-cases + trims and returns the matching {@link Encoding} only for
1154
1182
  * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
1155
1183
  * absent header, `identity`, an unknown value, or a
1156
1184
  * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1157
- * TOTAL — never asserts the loose `string | null` header.
1185
+ * Total — never asserts the loose `string | null` header.
1158
1186
  *
1159
1187
  * @param header - The raw `Content-Encoding` header value
1160
1188
  * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
@@ -1169,17 +1197,17 @@ export declare function parseEncoding(header: string | null): Exclude<Encoding,
1169
1197
 
1170
1198
  /**
1171
1199
  * Parses an HTTP `Range` request header against a known resource `size` —
1172
- * TOTAL, returning a {@link RangeSpec} or `undefined`.
1200
+ * total, returning a {@link RangeSpec} or `undefined`.
1173
1201
  *
1174
1202
  * @remarks
1175
1203
  * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1176
1204
  * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1177
- * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1205
+ * `[0, size - 1]` (the HTTP inclusive-end convention). Returns
1178
1206
  * `{ satisfiable: true, start, end }` for an overlapping range,
1179
1207
  * `{ satisfiable: false }` for a range wholly past the resource, and
1180
- * `undefined` for the "serve the whole resource" case: an ABSENT header, a
1181
- * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
1182
- * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1208
+ * `undefined` for the "serve the whole resource" case: an absent header, a
1209
+ * non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
1210
+ * supported), or any malformed/non-finite bound. Never throws on a hostile
1183
1211
  * header.
1184
1212
  *
1185
1213
  * @param header - The raw `Range` header value
@@ -1218,19 +1246,19 @@ export declare function probePort(port: number): Promise<number>;
1218
1246
  * Represents the parsed outcome of an HTTP `Range` request header.
1219
1247
  *
1220
1248
  * @remarks
1221
- * A `Range: bytes=start-end` against a known resource `size` resolves to ONE
1249
+ * A `Range: bytes=start-end` against a known resource `size` resolves to one
1222
1250
  * of two shapes, discriminated by `satisfiable` (the axis is whether the
1223
1251
  * requested span overlaps the resource):
1224
1252
  *
1225
1253
  * - **`satisfiable: true`** — a concrete, clamped byte window `[start, end]`
1226
- * (INCLUSIVE, the HTTP wire convention), normalized from the header's
1254
+ * (inclusive, the HTTP wire convention), normalized from the header's
1227
1255
  * open / suffix / closed forms against `size`.
1228
1256
  * - **`satisfiable: false`** — the range lies wholly outside the resource.
1229
1257
  *
1230
- * `parseRange` returns `undefined` for an ABSENT / unparseable / multi-range
1258
+ * `parseRange` returns `undefined` for an absent / unparseable / multi-range
1231
1259
  * / non-`bytes` header — the "no range, serve the whole resource" case — so
1232
1260
  * the three outcomes (full / partial / unsatisfiable) are distinguished
1233
- * without a separate flag. It is TOTAL — a hostile header never throws.
1261
+ * without a separate flag. It is total — a hostile header never throws.
1234
1262
  */
1235
1263
  export declare type RangeSpec = {
1236
1264
  readonly satisfiable: true;
@@ -1241,9 +1269,10 @@ export declare type RangeSpec = {
1241
1269
  };
1242
1270
 
1243
1271
  /**
1244
- * Collects + decodes a `Request` body — the shared body-collection pipeline
1272
+ * Collects and decodes a `Request` body — the shared body-collection pipeline
1245
1273
  * surfaced to middleware and handlers as the middleware context's cached
1246
- * `body()`.
1274
+ * `body()`. An empty body and a malformed `application/json` body each decode to
1275
+ * `undefined`.
1247
1276
  *
1248
1277
  * @remarks
1249
1278
  * Collects the wire body capped at `options.limit` bytes ({@link
@@ -1254,13 +1283,11 @@ export declare type RangeSpec = {
1254
1283
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1255
1284
  * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1256
1285
  * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1257
- * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1258
- * decodes to `undefined`.
1286
+ * scrubPrototype}); any other type decodes as UTF-8 text.
1259
1287
  *
1260
- * A malformed JSON body is total: it decodes to `undefined` rather than
1261
- * throwing, so a handler that must reject one checks for `undefined` itself.
1262
- * That makes `undefined` the answer for two distinct inputs, and nothing in the
1263
- * returned value tells them apart.
1288
+ * A malformed JSON body is total: it decodes rather than throwing, so a handler
1289
+ * that must reject one checks for `undefined` itself, and nothing in the returned
1290
+ * value tells an empty body from a malformed one.
1264
1291
  *
1265
1292
  * @param request - The `Request` to read the body from
1266
1293
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
@@ -1277,13 +1304,13 @@ export declare type RangeSpec = {
1277
1304
  export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
1278
1305
 
1279
1306
  /**
1280
- * Reads + verifies a SIGNED cookie off a request — TOTAL, returning the
1307
+ * Reads and verifies a signed cookie off a request — total, returning the
1281
1308
  * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
1282
1309
  *
1283
1310
  * @remarks
1284
1311
  * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
1285
1312
  * and verifies it with {@link verifyToken} against `secret` (a rotation list
1286
- * accepts a cookie signed by any of its secrets). ANY failure — an absent
1313
+ * accepts a cookie signed by any of its secrets). Any failure — an absent
1287
1314
  * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
1288
1315
  *
1289
1316
  * @param request - The `Request` to read the `Cookie` header from
@@ -1300,10 +1327,14 @@ export declare function readSignedCookie(request: Request, name: string, secret:
1300
1327
 
1301
1328
  /**
1302
1329
  * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
1303
- * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
1304
- * / control-char-bearing incoming id is REJECTED (a fresh id is minted
1305
- * instead) rather than ever riding into a response header or `context.state`.
1306
- * Frozen so a consumer can read but never mutate the shared default.
1330
+ * to match, `^[A-Za-z0-9_-]{1,200}$`.
1331
+ *
1332
+ * @remarks
1333
+ * An incoming id carrying CRLF, a log-injection payload, a control character,
1334
+ * or more characters than the pattern admits fails the match and is rejected —
1335
+ * a fresh id is minted instead — so it never rides into a response header or
1336
+ * `context.state`. Frozen so a consumer can read but never mutate the shared
1337
+ * default.
1307
1338
  */
1308
1339
  export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
1309
1340
 
@@ -1324,7 +1355,8 @@ export declare interface RequestLine {
1324
1355
 
1325
1356
  /**
1326
1357
  * Picks the highest-scoring content-coding the server offers against already
1327
- * parsed `Accept-Encoding` entries.
1358
+ * parsed `Accept-Encoding` entries — the shared selection leaf behind
1359
+ * {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.
1328
1360
  *
1329
1361
  * @remarks
1330
1362
  * The single selection leaf behind both doors onto this axis —
@@ -1332,9 +1364,9 @@ export declare interface RequestLine {
1332
1364
  * entity — so the scoring loop has one implementation. Scores each `available`
1333
1365
  * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
1334
1366
  * keeps the earlier-offered coding on a client-side tie, which is what makes
1335
- * `available` the SERVER's preference order. An empty `available` list, and a
1367
+ * `available` the server's preference order. An empty `available` list, and a
1336
1368
  * list the client rejects outright, both yield `undefined` (identity — no
1337
- * compression). TOTAL on hostile input.
1369
+ * compression). Total on hostile input.
1338
1370
  *
1339
1371
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
1340
1372
  * @param entries - The parsed {@link AcceptEntry} list
@@ -1355,9 +1387,9 @@ export declare function resolveCoding<T extends string>(entries: readonly Accept
1355
1387
  * @remarks
1356
1388
  * `'*'` and a single origin string pass straight through. An allow-list
1357
1389
  * echoes the request's `Origin` only when it is present in the list, else
1358
- * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1390
+ * `undefined` (no header set). Security: the literal `'null'` origin — sent
1359
1391
  * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1360
- * NEVER reflected even if `'null'` were listed, closing the hostile-context
1392
+ * never reflected even if `'null'` were listed, closing the hostile-context
1361
1393
  * cross-origin-access hole.
1362
1394
  *
1363
1395
  * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
@@ -1437,12 +1469,11 @@ export declare interface ResponseRecord {
1437
1469
  }
1438
1470
 
1439
1471
  /**
1440
- * Strips the prototype-pollution keys from a parsed value IN PLACE,
1441
- * recursively.
1472
+ * Strips the prototype-pollution keys from a parsed value in place, recursively.
1442
1473
  *
1443
1474
  * @remarks
1444
- * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1445
- * enumerable `__proto__` DATA property — but that own key becomes a
1475
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
1476
+ * enumerable `__proto__` data property — but that own key becomes a
1446
1477
  * pollution gadget the moment a downstream deep-merge copies it onto a live
1447
1478
  * object. This walks the value and `delete`s any own {@link isDangerousKey}
1448
1479
  * key at every depth, recursing into nested objects + array elements.
@@ -1467,11 +1498,11 @@ export declare function scrubPrototype(value: unknown): unknown;
1467
1498
  * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
1468
1499
  * appends the present {@link CookieOptions} attributes in canonical order:
1469
1500
  * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
1470
- * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
1471
- * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
1472
- * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
1501
+ * (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated
1502
+ * with {@link isCookieAttribute} and throw an {@link HTTPError} on an
1503
+ * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of
1473
1504
  * the `secure` option (the spec requires it); an un-resolved `undefined`
1474
- * `secure` here falls to OFF — request-aware callers resolve it first through
1505
+ * `secure` here falls to off — request-aware callers resolve it first through
1475
1506
  * {@link resolveSecure}.
1476
1507
  *
1477
1508
  * @param name - The cookie name
@@ -1491,7 +1522,7 @@ export declare function serializeCookie(name: string, value: string, options?: C
1491
1522
  * Serializes one {@link SSEMessage} to the SSE wire.
1492
1523
  *
1493
1524
  * @remarks
1494
- * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1525
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then one
1495
1526
  * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1496
1527
  * (so a consuming parser's multi-`data` concat reproduces the original
1497
1528
  * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
@@ -1511,37 +1542,37 @@ export declare function serializeEvent(message: SSEMessage): string;
1511
1542
  /**
1512
1543
  * Represents the HTTP server facade — an observable `node:http` lifecycle composing this
1513
1544
  * module's own middleware onion around a consumed `@orkestrel/router`
1514
- * dispatcher.
1545
+ * dispatcher. Implements exactly {@link ServerInterface}.
1515
1546
  *
1516
1547
  * @typeParam TState - The consumer's opaque per-request state type
1517
1548
  *
1518
1549
  * @remarks
1519
1550
  * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
1520
1551
  * server, binds the configured {@link ServerOptions.host} / {@link
1521
- * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1552
+ * ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the
1522
1553
  * bound address), exposes that {@link AddressInfo} through `address`, observes
1523
1554
  * caller cancellation plus the configured `timeouts.start` deadline while the
1524
1555
  * bind is pending, and transitions `idle → starting → listening`. A
1525
1556
  * cancelled or expired bind closes its partial server and resets to `idle` for
1526
1557
  * another start. `stop()` transitions
1527
1558
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1528
- * so in-flight handlers observe cancellation, drains in-flight requests AND
1559
+ * so in-flight handlers observe cancellation, drains in-flight requests and
1529
1560
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1530
1561
  * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1531
1562
  * still open. `destroy()` is the idempotent final teardown.
1532
1563
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1533
1564
  * `close`); a `Request` is built through the router's `buildRequest`, its
1534
- * `signal` LINKED to this run's stop signal through `@orkestrel/abort`'s
1565
+ * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
1535
1566
  * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1536
- * `buildRequest`'s own abort, armed by BOTH request-side and response-side
1567
+ * `buildRequest`'s own abort, armed by request-side and response-side
1537
1568
  * teardown, composes with the server's stop signal through `AbortSignal.any`,
1538
- * so a handler awaiting `request.signal` observes BOTH); `context.state` is built through
1569
+ * so a handler awaiting `request.signal` observes either); `context.state` is built through
1539
1570
  * {@link ServerOptions.state} from the connection facts; the composed
1540
1571
  * middleware onion runs, terminating in `dispatcher.handle`; the result is
1541
1572
  * written back through `sendResponse`.
1542
- * - **The built-in boundary** wraps the WHOLE per-request chain, including
1573
+ * - **The built-in boundary** wraps the whole per-request chain, including
1543
1574
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1544
- * throw (e.g. a malformed `Host` header) to a silent `400` with no
1575
+ * throw (for example, a malformed `Host` header) to a silent `400` with no
1545
1576
  * `error` emit; everything after (`Request` reconstruction, connection
1546
1577
  * facts, `state`, the composed onion, and `dispatcher.handle`) runs
1547
1578
  * behind the outer boundary — a thrown `HTTPError` renders as its status +
@@ -1553,12 +1584,12 @@ export declare function serializeEvent(message: SSEMessage): string;
1553
1584
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1554
1585
  * throwing handler is treated as declined and surfaced on `error`, an
1555
1586
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1556
- * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1587
+ * A claimed socket joins `#upgraded` until it closes: the claimant still
1557
1588
  * owns it, and the tracking exists because node detaches an upgraded socket
1558
1589
  * from the set its own close calls walk, so nothing else can end it.
1559
1590
  * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1560
1591
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1561
- * routes it to the `error` OPTION (not the domain `error` event).
1592
+ * routes it to the `error` option rather than to the domain `error` event.
1562
1593
  */
1563
1594
  export declare class Server<TState> implements ServerInterface<TState> {
1564
1595
  #private;
@@ -1579,11 +1610,11 @@ export declare class Server<TState> implements ServerInterface<TState> {
1579
1610
 
1580
1611
  /**
1581
1612
  * Represents the error this package raises when a caller programmed a call the
1582
- * entity refuses.
1613
+ * entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
1583
1614
  *
1584
1615
  * @remarks
1585
1616
  * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
1586
- * record naming the offending facts. This is a PROGRAMMER error, so it carries
1617
+ * record naming the offending facts. This is a programmer error, so it carries
1587
1618
  * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
1588
1619
  * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
1589
1620
  * middleware into the request boundary, which reaches it as a generic 500 with
@@ -1609,7 +1640,9 @@ export declare class ServerError extends Error {
1609
1640
 
1610
1641
  /**
1611
1642
  * Represents the machine-readable category a
1612
- * {@link import('./errors.js').ServerError} carries.
1643
+ * {@link import('./errors.js').ServerError} carries — `'STATUS'` for a lifecycle
1644
+ * call the current status forbids, `'NEXT'` for a middleware that called its `next`
1645
+ * a second time.
1613
1646
  *
1614
1647
  * @remarks
1615
1648
  * A `ServerError` reports a call the caller programmed and the substrate
@@ -1640,19 +1673,19 @@ export declare type ServerErrorCode =
1640
1673
  * the per-request path; `undefined` for an upgrade-handler throw (no fetch
1641
1674
  * `Request` exists on that path — only a raw `IncomingMessage`) or a listen
1642
1675
  * failure.
1643
- * - `stop` — `stop()` began (status just moved to `'stopping'`). An upgrade
1676
+ * - `stop` — `stop()` began (status moved to `'stopping'`). An upgrade
1644
1677
  * handler that owns a long-lived socket closes it from here, so the drain
1645
- * below settles instead of running out the deadline.
1678
+ * settles instead of running out the deadline.
1646
1679
  * - `drain` — the graceful drain settled (deadline hit or all finished);
1647
- * carries the still-pending request count AND the still-attached upgraded
1680
+ * carries the still-pending request count and the still-attached upgraded
1648
1681
  * socket count. Both `0` is a clean drain; either non-zero means the close
1649
- * that follows was FORCED and cut that work.
1682
+ * that follows was forced and cut that work.
1650
1683
  * - `response` — fired after the response has been sent, for every request
1651
1684
  * that reaches the middleware pipeline (the success path and the
1652
1685
  * outer-boundary error path); carries the method, parsed pathname, final
1653
1686
  * status, and elapsed time in milliseconds. A request rejected at the
1654
- * `buildRequest` INNER boundary (a plain `400`, e.g. a malformed `Host`
1655
- * header) emits no `response` — no parsed `Request` exists yet to derive
1687
+ * `buildRequest` inner boundary (a plain `400`, for example a malformed
1688
+ * `Host` header) emits no `response` — no parsed `Request` exists yet to derive
1656
1689
  * its facts from.
1657
1690
  */
1658
1691
  export declare type ServerEventMap = {
@@ -1675,7 +1708,7 @@ export declare type ServerEventMap = {
1675
1708
  * @remarks
1676
1709
  * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
1677
1710
  * both configurable before or after `start()`. `start(signal?)` binds the
1678
- * configured `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved
1711
+ * configured `host`/`port` (an omitted/`0` port ⇒ an ephemeral port, resolved
1679
1712
  * from the bound address), exposes that {@link AddressInfo} through `address`,
1680
1713
  * observes caller cancellation plus `timeouts.start` while binding, and resolves
1681
1714
  * the actually-bound port. A cancelled or expired bind closes its partial server
@@ -1707,7 +1740,8 @@ export declare interface ServerInterface<TState> {
1707
1740
  /** Holds the lifecycle emitter over {@link ServerEventMap}. */
1708
1741
  readonly emitter: EmitterInterface<ServerEventMap>;
1709
1742
  /**
1710
- * Appends one middleware, or an array of them in order, to the onion.
1743
+ * Appends one middleware, or an array of them in order, to the onion, outer-to-inner
1744
+ * in call order.
1711
1745
  *
1712
1746
  * @param middleware - One handler, or the ordered array of handlers to append
1713
1747
  *
@@ -1718,13 +1752,15 @@ export declare interface ServerInterface<TState> {
1718
1752
  use(middleware: MiddlewareHandler<TState>): void;
1719
1753
  use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
1720
1754
  /**
1721
- * Registers a protocol-upgrade claimant that runs in registration order.
1755
+ * Registers an {@link UpgradeHandler} claimant that runs in registration order; a
1756
+ * claimed socket is tracked until it closes.
1722
1757
  *
1723
1758
  * @param handler - The claimant; the first to return `true` claims the socket
1724
1759
  */
1725
1760
  upgrade(handler: UpgradeHandler): void;
1726
1761
  /**
1727
- * Binds the configured listener and resolves its actually-bound port.
1762
+ * Binds the configured `host` and `port`, or an ephemeral port, under an optional
1763
+ * caller `AbortSignal`, and resolves the actually-bound port.
1728
1764
  *
1729
1765
  * @param signal - Optional caller cancellation observed only while startup
1730
1766
  * is pending; aborting after this method resolves does not stop the server.
@@ -1741,10 +1777,11 @@ export declare interface ServerInterface<TState> {
1741
1777
  */
1742
1778
  start(signal?: AbortSignal): Promise<number>;
1743
1779
  /**
1744
- * Stops gracefully: refuses new connections, fires the stop signal, drains, closes.
1780
+ * Stops gracefully: refuses new connections, fires the stop signal, drains in-flight
1781
+ * requests and claimed upgraded sockets up to the `drain` deadline, then closes.
1745
1782
  *
1746
1783
  * @remarks
1747
- * Drainable work is every in-flight request PLUS every upgraded socket a
1784
+ * Drainable work is every in-flight request plus every upgraded socket a
1748
1785
  * handler claimed. The drain parks on that work reaching zero or the
1749
1786
  * `drain` deadline expiring, emits `drain` with both remaining counts, and
1750
1787
  * then closes — dropping idle keep-alive sockets on a clean drain, and
@@ -1756,7 +1793,8 @@ export declare interface ServerInterface<TState> {
1756
1793
  */
1757
1794
  stop(): Promise<void>;
1758
1795
  /**
1759
- * Tears down for good: force-closes the listener and every socket, then the emitter.
1796
+ * Tears down for good: force-closes the listener and every socket, then the emitter —
1797
+ * terminal and idempotent from any state.
1760
1798
  *
1761
1799
  * @returns Resolves once nothing is left open; idempotent from any state
1762
1800
  */
@@ -1764,7 +1802,9 @@ export declare interface ServerInterface<TState> {
1764
1802
  }
1765
1803
 
1766
1804
  /**
1767
- * Options for `createServer`.
1805
+ * Options for `createServer` — the dispatcher and per-request state factory the
1806
+ * server requires, plus its listener, drain, boundary, timeout, socket-cap, and
1807
+ * emitter knobs.
1768
1808
  *
1769
1809
  * @param dispatcher - The `@orkestrel/router` {@link DispatcherInterface} the
1770
1810
  * composed middleware onion terminates into — bring-your-own router (the
@@ -1778,12 +1818,12 @@ export declare interface ServerInterface<TState> {
1778
1818
  * @param host - The network interface `start()` binds to (`node:http`
1779
1819
  * `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
1780
1820
  * @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
1781
- * EPHEMERAL, OS-assigned free port (the default); `start()` always resolves
1821
+ * ephemeral, OS-assigned free port (the default); `start()` always resolves
1782
1822
  * the actually-bound port. A port already in use rejects `start()` with
1783
1823
  * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
1784
1824
  * guaranteed-free port up front).
1785
1825
  * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
1786
- * server stops accepting new connections and gives in-flight requests AND
1826
+ * server stops accepting new connections and gives in-flight requests and
1787
1827
  * claimed upgraded sockets this long to finish before forcing every
1788
1828
  * remaining socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be a
1789
1829
  * non-negative finite number. A long-lived upgraded socket that nothing
@@ -1863,10 +1903,10 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
1863
1903
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
1864
1904
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
1865
1905
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
1866
- * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the FIRST
1906
+ * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
1867
1907
  * {@link TokenSecret} (the current secret, or the head of a rotation list).
1868
- * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
1869
- * misconfigured secret with no usable entry THROWS an {@link HTTPError}
1908
+ * Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
1909
+ * misconfigured secret with no usable entry throws an {@link HTTPError}
1870
1910
  * (`500`) — fail-closed, a programmer error. Verify with
1871
1911
  * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
1872
1912
  *
@@ -1884,16 +1924,16 @@ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping
1884
1924
  export declare function signToken(value: string, options: TokenOptions): Promise<string>;
1885
1925
 
1886
1926
  /**
1887
- * Holds the SSE response headers a `Stream` always sets on its response.
1927
+ * Holds the SSE response headers a `Stream` sets on its response, merged under any
1928
+ * caller `headers` so a caller repeating one of these keys replaces its value.
1888
1929
  *
1889
1930
  * @remarks
1890
1931
  * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
1891
1932
  * keeps a proxy from caching the stream; `keep-alive` holds the connection
1892
1933
  * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
1893
1934
  * events flush promptly rather than batching. Frozen so a consumer can read
1894
- * but never mutate the shared default; a `Stream` merges any
1895
- * {@link import('./types.js').StreamOptions.headers} OVER these, so a caller
1896
- * repeating one of these keys replaces its value.
1935
+ * but never mutate the shared default; the merged keys are
1936
+ * {@link import('./types.js').StreamOptions.headers}.
1897
1937
  */
1898
1938
  export declare const SSE_HEADERS: Readonly<Record<string, string>>;
1899
1939
 
@@ -1902,9 +1942,9 @@ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
1902
1942
  *
1903
1943
  * @remarks
1904
1944
  * - `data` — the event payload (required). Serialized as one or more `data:`
1905
- * lines: the value is split on `\n` into a `data:` line PER segment, so it
1945
+ * lines: the value is split on `\n` into a `data:` line per segment, so it
1906
1946
  * round-trips through a consumer's multi-`data` concat.
1907
- * - `event` — the optional event TYPE, emitted as an `event:` line; omitted
1947
+ * - `event` — the optional event type, emitted as an `event:` line; omitted
1908
1948
  * ⇒ the consumer's default (`message`).
1909
1949
  * - `id` — the optional last-event-id, emitted as an `id:` line.
1910
1950
  * - `retry` — the optional reconnection time in milliseconds, emitted as a
@@ -1912,9 +1952,9 @@ export declare const SSE_HEADERS: Readonly<Record<string, string>>;
1912
1952
  */
1913
1953
  export declare interface SSEMessage {
1914
1954
  readonly data: string;
1915
- /** Requires a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
1955
+ /** Requires a single-line value — an embedded newline would corrupt the SSE wire format. */
1916
1956
  readonly event?: string;
1917
- /** Requires a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
1957
+ /** Requires a single-line value — an embedded newline would corrupt the SSE wire format. */
1918
1958
  readonly id?: string;
1919
1959
  readonly retry?: number;
1920
1960
  }
@@ -1926,7 +1966,7 @@ export declare interface SSEMessage {
1926
1966
  * @remarks
1927
1967
  * Builds the `Response` at construction from
1928
1968
  * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
1929
- * merged OVER them, at `options.status` (default `200`). A caller repeating one
1969
+ * merged over them, at `options.status` (default `200`). A caller repeating one
1930
1970
  * of those keys therefore replaces the seam's value, in any casing. The
1931
1971
  * instance owns the stream's
1932
1972
  * controller, its text encoder, the closed flag, and the parked producer's
@@ -1938,7 +1978,7 @@ export declare interface SSEMessage {
1938
1978
  * receiving `false` awaits `drain()`; that promise resolves on the next
1939
1979
  * consumer pull restoring capacity, or on stream closure. `comment` writes a
1940
1980
  * `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
1941
- * stream. Every method is a SAFE NO-OP once `closed` (ended by `end()`, or
1981
+ * stream. Every method is a safe no-op once `closed` (ended by `end()`, or
1942
1982
  * the consumer cancelled the stream), so a late write never throws.
1943
1983
  *
1944
1984
  * The readiness signal reflects only the process-local `ReadableStream`
@@ -1989,7 +2029,7 @@ export declare class Stream implements StreamInterface {
1989
2029
  * queue still has capacity; a producer that receives `false` parks on
1990
2030
  * `drain()` before writing again. `comment` writes a `: text` keep-alive line
1991
2031
  * (ignored by a conforming SSE parser — no spurious event); `end` closes the
1992
- * stream. Every method is a SAFE NO-OP once `closed` is `true`, so a late
2032
+ * stream. Every method is a safe no-op once `closed` is `true`, so a late
1993
2033
  * `write` never throws.
1994
2034
  *
1995
2035
  * The readiness signal is deliberately local: it reflects the
@@ -1998,7 +2038,7 @@ export declare class Stream implements StreamInterface {
1998
2038
  * the process-local socket sink is backpressured, so a cooperative producer
1999
2039
  * can bound its contribution to transport buffering without polling. A caller
2000
2040
  * that ignores the boolean keeps the prior unconditional-enqueue behavior.
2001
- * The stream's default strategy measures queued CHUNKS, not their byte length,
2041
+ * The stream's default strategy measures queued chunks, not their byte length,
2002
2042
  * so a producer seeking a byte bound must also bound each individual message.
2003
2043
  * Return `response` before awaiting a `false` write: the consumer cannot pull
2004
2044
  * until it receives the response.
@@ -2009,7 +2049,9 @@ export declare interface StreamInterface {
2009
2049
  /** Reports whether the underlying stream is done (ended, or the consumer disconnected). */
2010
2050
  readonly closed: boolean;
2011
2051
  /**
2012
- * Serializes + enqueues one {@link SSEMessage} to the wire.
2052
+ * Serializes and enqueues one {@link SSEMessage} to the wire, reporting whether the
2053
+ * process-local queue still has capacity afterward — `false` also once the stream
2054
+ * is closed.
2013
2055
  *
2014
2056
  * @param message - The event to send (its `data` split on `\n` into `data:` lines)
2015
2057
  * @returns True if the process-local stream queue has capacity after
@@ -2019,13 +2061,16 @@ export declare interface StreamInterface {
2019
2061
  */
2020
2062
  write(message: SSEMessage): boolean;
2021
2063
  /**
2022
- * Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores.
2064
+ * Writes a `: text` SSE comment line — a keep-alive a conforming parser ignores,
2065
+ * and a no-op once the stream is closed.
2023
2066
  *
2024
2067
  * @param text - The comment text (sent after the `: ` prefix)
2025
2068
  */
2026
2069
  comment(text: string): void;
2027
2070
  /**
2028
- * Parks until the process-local stream queue has capacity again.
2071
+ * Parks until the process-local stream queue has capacity again — resolving on the
2072
+ * consumer pull that restores it, or immediately when capacity is already available
2073
+ * or the stream is closed, and never polling.
2029
2074
  *
2030
2075
  * @returns A promise that resolves when a consumer pull restores positive
2031
2076
  * desired size, or immediately when capacity is already available or the
@@ -2033,7 +2078,10 @@ export declare interface StreamInterface {
2033
2078
  * not prove that a remote peer consumed the queued bytes.
2034
2079
  */
2035
2080
  drain(): Promise<void>;
2036
- /** Ends the stream, completing the response (a no-op once already `closed`). */
2081
+ /**
2082
+ * Ends the stream, completing the response — a no-op once already `closed`, and it
2083
+ * settles any parked producer.
2084
+ */
2037
2085
  end(): void;
2038
2086
  }
2039
2087
 
@@ -2043,7 +2091,7 @@ export declare interface StreamInterface {
2043
2091
  *
2044
2092
  * @param status - The HTTP status the streaming response is opened with;
2045
2093
  * defaults to `200`.
2046
- * @param headers - Extra response headers merged OVER the SSE headers the
2094
+ * @param headers - Extra response headers merged over the SSE headers the
2047
2095
  * seam always sets ({@link SSE_HEADERS}); a caller repeating one of those
2048
2096
  * keys replaces the seam's value, in any casing.
2049
2097
  */
@@ -2056,10 +2104,10 @@ export declare interface StreamOptions {
2056
2104
  * Options for `signToken` — how a stateless, HMAC-signed token is minted.
2057
2105
  *
2058
2106
  * @param secret - The {@link TokenSecret} to sign with; `signToken` always
2059
- * uses the FIRST secret (a single string, or the current head of a
2107
+ * uses the first secret (a single string, or the current head of a
2060
2108
  * rotation list). An empty rotation list is a misconfiguration and throws.
2061
2109
  * @param ttl - An optional lifetime in milliseconds. When set, the expiry
2062
- * timestamp is bound INTO the signed payload (HMAC-covered, tamper-proof);
2110
+ * timestamp is bound into the signed payload (HMAC-covered, tamper-proof);
2063
2111
  * `verifyToken` rejects the token once that instant has passed. Omitted ⇒
2064
2112
  * the token never expires.
2065
2113
  */
@@ -2069,21 +2117,21 @@ export declare interface TokenOptions {
2069
2117
  }
2070
2118
 
2071
2119
  /**
2072
- * Represents a secret (or rotation list) for signing + verifying a stateless, HMAC-signed
2073
- * token.
2120
+ * Represents a secret, or a `[current, ...older]` rotation list, for signing and
2121
+ * verifying a stateless, HMAC-signed token.
2074
2122
  *
2075
2123
  * @remarks
2076
2124
  * A single `string` is the lone secret. A `readonly string[]` is a rotation
2077
2125
  * list in `[current, ...older]` order: `signToken` always signs with the
2078
- * FIRST (current) secret, while `verifyToken` accepts a token signed by ANY
2079
- * secret in the list — so a key rotates by prepending the new one and keeping
2126
+ * first (current) secret, while `verifyToken` accepts a token signed by any
2127
+ * secret in the list — so a key rotates by prepending the fresh one and keeping
2080
2128
  * the old until every outstanding token has expired, with zero downtime.
2081
2129
  */
2082
2130
  export declare type TokenSecret = string | readonly string[];
2083
2131
 
2084
2132
  /**
2085
- * Strips the WEAK indicator (`W/`) from an entity-tag, returning its opaque
2086
- * comparison body — the reduction {@link matchesETag} applies to both sides
2133
+ * Strips the weak indicator (`W/`) from an entity-tag, returning its opaque
2134
+ * comparison body — the reduction {@link matchesETag} applies to each side
2087
2135
  * before the RFC 7232 §2.3.2 weak comparison.
2088
2136
  *
2089
2137
  * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
@@ -2102,14 +2150,14 @@ export declare function unwrapETag(tag: string): string;
2102
2150
  *
2103
2151
  * @remarks
2104
2152
  * Fan-out semantics: handlers run in registration
2105
- * order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
2106
- * fan-out; a handler that THROWS is treated as declined (the throw surfaces
2107
- * on the `error` event) and the fan-out continues; if NONE claim it, the
2153
+ * order, the first to return `true` claims (owns) the socket and stops the
2154
+ * fan-out; a handler that throws is treated as declined (the throw surfaces
2155
+ * on the `error` event) and the fan-out continues; if none claim it, the
2108
2156
  * socket is destroyed so an unhandled upgrade never leaks a dangling
2109
2157
  * connection. `request` / `socket` / `head` are node's own raw values, handed
2110
2158
  * over verbatim — no assertion at this boundary.
2111
2159
  *
2112
- * A CLAIMED socket is TRACKED until it closes. The handler still owns it —
2160
+ * A claimed socket is tracked until it closes. The handler still owns it —
2113
2161
  * the server only watches — but `stop()` now drains that socket like an
2114
2162
  * in-flight request and destroys it if the `drain` deadline expires first.
2115
2163
  * Node detaches an upgraded socket from its own connection set, so neither
@@ -2122,25 +2170,25 @@ export declare function unwrapETag(tag: string): string;
2122
2170
  * @param request - The raw `node:http` upgrade request
2123
2171
  * @param socket - The raw, now-detached `Duplex` connection
2124
2172
  * @param head - The first packet of the upgraded stream, if any
2125
- * @returns True if the handler CLAIMS the socket (this handler now owns
2173
+ * @returns True if the handler claims the socket (this handler now owns
2126
2174
  * it); false otherwise, declining so a later handler can try
2127
2175
  */
2128
2176
  export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
2129
2177
 
2130
2178
  /**
2131
- * Verifies a stateless token and returns its embedded value — TOTAL, never throws.
2179
+ * Verifies a stateless token and returns its embedded value — total, never throws.
2132
2180
  *
2133
2181
  * @remarks
2134
- * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
2182
+ * The inverse of {@link signToken}: splits the token on its last `.` (so a
2135
2183
  * value containing dots survives), decodes the signature with
2136
2184
  * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
2137
2185
  * base64url is refused there, before any key import — and checks the payload's
2138
- * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate through
2186
+ * HMAC-SHA256 signature against each {@link TokenSecret} candidate through
2139
2187
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
2140
2188
  * retired), accepting the token on the first match (the
2141
2189
  * rotation path). It then decodes + narrows the payload (`isRecord` +
2142
2190
  * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
2143
- * token. ANY failure — a malformed token, a bad signature,
2191
+ * token. Any failure — a malformed token, a bad signature,
2144
2192
  * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
2145
2193
  * yields `undefined` rather than throwing.
2146
2194
  *
@@ -2156,7 +2204,8 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
2156
2204
  export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
2157
2205
 
2158
2206
  /**
2159
- * Wraps one middleware layer around its downstream handler.
2207
+ * Wraps one middleware layer around its downstream handler, enforcing the one-call
2208
+ * `next` invariant.
2160
2209
  *
2161
2210
  * @remarks
2162
2211
  * The returned handler enforces the one-call `next` invariant while preserving
@@ -2178,7 +2227,7 @@ export declare function verifyToken(token: string, secret: TokenSecret): Promise
2178
2227
  export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
2179
2228
 
2180
2229
  /**
2181
- * Writes a SIGNED cookie — HMAC-signs `value` with {@link signToken} and
2230
+ * Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
2182
2231
  * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
2183
2232
  *
2184
2233
  * @remarks