@orkestrel/server 0.0.17 → 0.0.18

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