@orkestrel/server 0.0.18 → 0.0.19

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