@orkestrel/server 0.0.23 → 0.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { isError, isFiniteNumber, isFunction, isInstance, isInteger, isNumber, isObject, isRecord, isString, parseJSON } from "@orkestrel/contract";
1
+ import { INTRINSICS, attempt, holds, isError, isFiniteNumber, isFunction, isInstance, isInteger, isNumber, isObject, isRecord, isString, parseJSON } from "@orkestrel/contract";
2
2
  import { addAbortListener, once } from "node:events";
3
3
  import { createServer as createServer$1 } from "node:net";
4
4
  import { decodeBase64URL, encodeBase64URL, encodeHex } from "@orkestrel/codec";
@@ -8,7 +8,7 @@ import { createAbort, linkSignal } from "@orkestrel/abort";
8
8
  import { createTimeout, isTimeoutDuration } from "@orkestrel/timeout";
9
9
  import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
10
10
  import { Emitter } from "@orkestrel/emitter";
11
- //#region src/server/constants.ts
11
+ // src/server/constants.ts
12
12
  /**
13
13
  * Names the default graceful-stop deadline `stop()` gives in-flight requests and
14
14
  * claimed upgraded sockets, `10_000` ms.
@@ -120,8 +120,11 @@ var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
120
120
  * shared default.
121
121
  */
122
122
  var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
123
- //#endregion
124
- //#region src/server/errors.ts
123
+ /** Names the identity brand carried by lifecycle errors across package copies. */
124
+ var SERVER_ERROR_BRAND = Symbol.for("@orkestrel/server.ServerError");
125
+ /** Names the identity brand carried by body-limit errors across package copies. */
126
+ var CONTENT_TOO_LARGE_ERROR_BRAND = Symbol.for("@orkestrel/server.ContentTooLargeError");
127
+ // src/server/errors.ts
125
128
  /**
126
129
  * Represents an error a handler (or middleware) throws to produce an HTTP response of a
127
130
  * specific status.
@@ -151,9 +154,9 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
151
154
  var HTTPError = class extends Error {
152
155
  status;
153
156
  context;
154
- [HTTP_ERROR_BRAND] = true;
155
157
  constructor(status, message, context) {
156
158
  super(message);
159
+ Object.defineProperty(this, HTTP_ERROR_BRAND, { value: this });
157
160
  this.name = "HTTPError";
158
161
  this.status = status;
159
162
  if (context !== void 0) this.context = context;
@@ -183,26 +186,23 @@ var HTTPError = class extends Error {
183
186
  var ContentTooLargeError = class extends HTTPError {
184
187
  constructor(limit) {
185
188
  super(413, `request body exceeds the ${limit}-byte limit`, { limit });
189
+ Object.defineProperty(this, CONTENT_TOO_LARGE_ERROR_BRAND, { value: this });
186
190
  this.name = "ContentTooLargeError";
187
191
  }
188
192
  };
189
193
  /**
190
194
  * Narrows an unknown caught value to an {@link HTTPError}, including a subclass such
191
195
  * as {@link ContentTooLargeError}, and recognizes an instance from another copy of
192
- * this package through a structural brand fallback.
196
+ * this package through its own identity brand.
193
197
  *
194
198
  * @param value - The value to test (typically a `catch` binding)
195
199
  * @returns True if `value` is an {@link HTTPError}; false otherwise
196
200
  *
197
201
  * @remarks
198
- * Tries `instanceof` first, then falls back to a total structural check for
199
- * an instance built by a different copy of this package (the dual-package
200
- * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
201
- * constructor is a distinct object from this copy's: the value must carry
202
- * the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
203
- * same key) and expose the exact fields the server's error boundary reads off
204
- * a recognized `HTTPError` — a numeric `status` and a string `message`. A
205
- * plain object that merely carries a `status` without the brand is rejected.
202
+ * Requires a global Error instance with a derived prototype, its own identity brand,
203
+ * a numeric status, a string message, and an absent or object-valued context.
204
+ * Callable contexts are accepted. Subclass names are unrestricted.
205
+ * Transparent proxies and branded plain objects are rejected.
206
206
  *
207
207
  * @example
208
208
  * ```ts
@@ -216,11 +216,24 @@ var ContentTooLargeError = class extends HTTPError {
216
216
  * ```
217
217
  */
218
218
  function isHTTPError(value) {
219
- if (isInstance(value, HTTPError)) return true;
220
- if (!isObject(value)) return false;
221
- if (!(HTTP_ERROR_BRAND in value) || value[HTTP_ERROR_BRAND] !== true) return false;
222
- if (!("status" in value) || !("message" in value)) return false;
223
- return isNumber(value.status) && isString(value.message);
219
+ return holds(() => {
220
+ if (!isInstance(value, Error) || INTRINSICS.prototype(value) === Error.prototype) return false;
221
+ if (!INTRINSICS.own(value, HTTP_ERROR_BRAND)) return false;
222
+ if (INTRINSICS.describe(value, HTTP_ERROR_BRAND)?.value !== value) return false;
223
+ const context = INTRINSICS.reflect.read(value, "context");
224
+ return isNumber(INTRINSICS.reflect.read(value, "status")) && isString(INTRINSICS.reflect.read(value, "message")) && (context === void 0 || isObject(context) || isFunction(context));
225
+ });
226
+ }
227
+ /**
228
+ * Recognizes a branded body-limit error, including subclasses and other package copies.
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * isContentTooLargeError(new ContentTooLargeError(1024)) // true
233
+ * ```
234
+ */
235
+ function isContentTooLargeError(value) {
236
+ return holds(() => isHTTPError(value) && INTRINSICS.own(value, CONTENT_TOO_LARGE_ERROR_BRAND) && INTRINSICS.describe(value, CONTENT_TOO_LARGE_ERROR_BRAND)?.value === value);
224
237
  }
225
238
  /**
226
239
  * Represents the error this package raises when a caller programmed a call the
@@ -251,6 +264,7 @@ var ServerError = class extends Error {
251
264
  context;
252
265
  constructor(code, message, context) {
253
266
  super(message);
267
+ Object.defineProperty(this, SERVER_ERROR_BRAND, { value: this });
254
268
  this.name = "ServerError";
255
269
  this.code = code;
256
270
  if (context !== void 0) this.context = context;
@@ -264,10 +278,9 @@ var ServerError = class extends Error {
264
278
  * @returns True if `value` is a {@link ServerError}; false otherwise
265
279
  *
266
280
  * @remarks
267
- * Recognizes an instance built by this copy of the package. A `ServerError`
268
- * is raised by a `Server` to the caller that invoked it directly, so both sides
269
- * hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
270
- * consumer here.
281
+ * Requires the own identity brand, a declared code, a string message, and an absent
282
+ * or object-valued context on a global Error with a derived prototype.
283
+ * Callable contexts and subclasses are accepted; transparent proxies are rejected.
271
284
  *
272
285
  * @example
273
286
  * ```ts
@@ -285,10 +298,16 @@ var ServerError = class extends Error {
285
298
  * ```
286
299
  */
287
300
  function isServerError(value) {
288
- return isInstance(value, ServerError);
301
+ return holds(() => {
302
+ if (!isInstance(value, Error) || INTRINSICS.prototype(value) === Error.prototype) return false;
303
+ if (!INTRINSICS.own(value, SERVER_ERROR_BRAND)) return false;
304
+ if (INTRINSICS.describe(value, SERVER_ERROR_BRAND)?.value !== value) return false;
305
+ const code = INTRINSICS.reflect.read(value, "code");
306
+ const context = INTRINSICS.reflect.read(value, "context");
307
+ return (code === "STATUS" || code === "NEXT") && isString(INTRINSICS.reflect.read(value, "message")) && (context === void 0 || isObject(context) || isFunction(context));
308
+ });
289
309
  }
290
- //#endregion
291
- //#region src/server/validators.ts
310
+ // src/server/validators.ts
292
311
  /**
293
312
  * Checks whether a `node:net` `server.address()` return is the structured
294
313
  * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
@@ -313,8 +332,7 @@ function isServerError(value) {
313
332
  function isAddressInfo(value) {
314
333
  return isRecord(value) && isString(value.address) && isString(value.family) && isNumber(value.port);
315
334
  }
316
- //#endregion
317
- //#region src/server/helpers.ts
335
+ // src/server/helpers.ts
318
336
  /**
319
337
  * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
320
338
  * handler into one request handler — the frozen middleware seam.
@@ -373,11 +391,12 @@ function compose(middleware, terminal) {
373
391
  */
374
392
  function wrapMiddleware(layer, next) {
375
393
  return async (request, context) => {
376
- let called = false;
394
+ const calls = [next].values();
377
395
  return Promise.resolve(layer(request, context, (nextRequest) => {
378
- if (called) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
379
- called = true;
380
- return next(nextRequest ?? request, context);
396
+ const invocation = calls.next();
397
+ if (invocation.done) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
398
+ const downstream = invocation.value;
399
+ return downstream(nextRequest ?? request, context);
381
400
  }));
382
401
  };
383
402
  }
@@ -406,8 +425,7 @@ function parseCookies(header) {
406
425
  const out = {};
407
426
  if (header === void 0) return out;
408
427
  const segments = header.split(";");
409
- for (let index = 0; index < segments.length; index += 1) {
410
- const raw = segments[index] ?? "";
428
+ for (const [index, raw] of segments.entries()) {
411
429
  const segment = index === 0 ? raw : raw.replace(/^[ \t]+/, "");
412
430
  const eq = segment.indexOf("=");
413
431
  if (eq < 0) continue;
@@ -795,14 +813,9 @@ function parseAcceptHeader(header) {
795
813
  const semicolon = trimmed.indexOf(";");
796
814
  const value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase();
797
815
  if (value.length === 0) continue;
798
- let q = 1;
799
- if (semicolon !== -1) {
800
- const match = /;\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon));
801
- if (match !== null) {
802
- const parsed = Number(match[1]);
803
- if (isFiniteNumber(parsed)) q = Math.min(1, Math.max(0, parsed));
804
- }
805
- }
816
+ const match = semicolon === -1 ? null : /;\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon));
817
+ const parsed = match === null ? void 0 : Number(match[1]);
818
+ const q = isFiniteNumber(parsed) ? Math.min(1, Math.max(0, parsed)) : 1;
806
819
  entries.push({
807
820
  value,
808
821
  q
@@ -866,16 +879,13 @@ function computeCodingQuality(entries, coding) {
866
879
  * ```
867
880
  */
868
881
  function resolveCoding(entries, available) {
869
- let best;
870
- let bestQuality = 0;
871
- for (const coding of available) {
882
+ return Iterator.from(available).reduce((previous, coding) => {
872
883
  const quality = computeCodingQuality(entries, coding);
873
- if (quality > bestQuality) {
874
- best = coding;
875
- bestQuality = quality;
876
- }
877
- }
878
- return best;
884
+ return quality > (previous?.quality ?? 0) ? {
885
+ value: coding,
886
+ quality
887
+ } : previous;
888
+ }, void 0)?.value;
879
889
  }
880
890
  /**
881
891
  * Selects the best content-coding for a raw `Accept-Encoding` header from the
@@ -929,25 +939,54 @@ function negotiateEncoding(header, available) {
929
939
  * ```
930
940
  */
931
941
  function matchMediaType(entries, candidate) {
942
+ return iterateMediaMatches(entries, candidate).reduce((best, match) => {
943
+ if (match.q === 0) return void 0;
944
+ return best === void 0 || match.rank < best.rank || match.rank === best.rank && match.q > best.q ? match : best;
945
+ }, void 0);
946
+ }
947
+ /**
948
+ * Yields matching media ranges through the first exact rejection.
949
+ *
950
+ * @example
951
+ * ```ts
952
+ * Array.from(iterateMediaMatches([{ value: 'text/plain', q: 1 }], 'text/plain'))
953
+ * // [{ q: 1, rank: 0 }]
954
+ * ```
955
+ */
956
+ function* iterateMediaMatches(entries, candidate) {
932
957
  const slash = candidate.indexOf("/");
933
958
  const type = slash === -1 ? candidate : candidate.slice(0, slash);
934
- let best;
935
959
  for (const entry of entries) {
936
- let rank;
937
- if (entry.value === candidate) rank = 0;
938
- else if (entry.value === `${type}/*`) rank = 1;
939
- else if (entry.value === "*/*") rank = 2;
960
+ const rank = entry.value === candidate ? 0 : entry.value === `${type}/*` ? 1 : entry.value === "*/*" ? 2 : void 0;
940
961
  if (rank === void 0) continue;
941
962
  if (entry.q === 0) {
942
- if (rank === 0) return void 0;
963
+ if (rank === 0) {
964
+ yield {
965
+ q: 0,
966
+ rank
967
+ };
968
+ return;
969
+ }
943
970
  continue;
944
971
  }
945
- if (best === void 0 || rank < best.rank || rank === best.rank && entry.q > best.q) best = {
972
+ yield {
946
973
  q: entry.q,
947
974
  rank
948
975
  };
949
976
  }
950
- return best;
977
+ }
978
+ /**
979
+ * Yields the same lazily collected request-body promise on every read.
980
+ *
981
+ * @example
982
+ * ```ts
983
+ * const bodies = iterateRequestBody(new Request('http://localhost/'), 1024)
984
+ * bodies.next().value === bodies.next().value // true
985
+ * ```
986
+ */
987
+ function* iterateRequestBody(request, limit) {
988
+ const body = readBody(request, { limit });
989
+ for (;;) yield body;
951
990
  }
952
991
  /**
953
992
  * Computes the client's quality for one `candidate` language from the parsed
@@ -973,19 +1012,22 @@ function matchMediaType(entries, candidate) {
973
1012
  function computeLanguageQuality(entries, candidate) {
974
1013
  const lower = candidate.toLowerCase();
975
1014
  const primary = lower.split("-")[0];
976
- let named;
977
- let prefixed;
978
- let wildcard;
979
- for (const entry of entries) {
1015
+ const qualities = Iterator.from(entries).reduce((previous, entry) => {
980
1016
  const entryPrimary = entry.value.split("-")[0];
981
- if (entry.value === lower) named = entry.q;
982
- else if (entryPrimary === primary) {
983
- if (prefixed === void 0) prefixed = entry.q;
984
- } else if (entry.value === "*") wildcard = entry.q;
985
- }
986
- if (named !== void 0) return named;
987
- if (prefixed !== void 0) return prefixed;
988
- return wildcard ?? 0;
1017
+ if (entry.value === lower) return {
1018
+ ...previous,
1019
+ named: entry.q
1020
+ };
1021
+ if (entryPrimary === primary) return previous.prefixed === void 0 ? {
1022
+ ...previous,
1023
+ prefixed: entry.q
1024
+ } : previous;
1025
+ return entry.value === "*" ? {
1026
+ ...previous,
1027
+ wildcard: entry.q
1028
+ } : previous;
1029
+ }, {});
1030
+ return qualities.named ?? qualities.prefixed ?? qualities.wildcard ?? 0;
989
1031
  }
990
1032
  /**
991
1033
  * Checks whether a `Content-Type` is worth compressing.
@@ -1282,16 +1324,13 @@ function computeIPv6Network(address) {
1282
1324
  if (halves.length === 2 && second === void 0) return void 0;
1283
1325
  const head = first === "" ? [] : first.split(":");
1284
1326
  const tail = second === void 0 || second === "" ? [] : second.split(":");
1285
- let groups;
1286
- if (halves.length === 2) {
1287
- const missing = 8 - head.length - tail.length;
1288
- if (missing < 0) return void 0;
1289
- groups = [
1290
- ...head,
1291
- ...Array.from({ length: missing }, () => "0"),
1292
- ...tail
1293
- ];
1294
- } else groups = head;
1327
+ const missing = 8 - head.length - tail.length;
1328
+ if (halves.length === 2 && missing < 0) return void 0;
1329
+ const groups = halves.length === 2 ? [
1330
+ ...head,
1331
+ ...Array.from({ length: missing }, () => "0"),
1332
+ ...tail
1333
+ ] : head;
1295
1334
  if (groups.length !== 8) return void 0;
1296
1335
  const prefix = [];
1297
1336
  for (const group of groups.slice(0, 4)) {
@@ -1429,23 +1468,24 @@ async function collectRequestBody(request, limit) {
1429
1468
  if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
1430
1469
  const reader = request.body.getReader();
1431
1470
  const chunks = [];
1432
- let total = 0;
1433
1471
  for (;;) {
1434
1472
  const { done, value } = await reader.read();
1435
1473
  if (done) break;
1436
- total += value.byteLength;
1474
+ const total = (chunks.at(-1)?.total ?? 0) + value.byteLength;
1437
1475
  if (limit > 0 && total > limit) {
1438
1476
  await reader.cancel();
1439
1477
  throw new ContentTooLargeError(limit);
1440
1478
  }
1441
- chunks.push(value);
1442
- }
1443
- const merged = new Uint8Array(total);
1444
- let offset = 0;
1445
- for (const chunk of chunks) {
1446
- merged.set(chunk, offset);
1447
- offset += chunk.byteLength;
1479
+ chunks.push({
1480
+ bytes: value,
1481
+ total
1482
+ });
1448
1483
  }
1484
+ const merged = new Uint8Array(chunks.at(-1)?.total ?? 0);
1485
+ chunks.reduce((offset, chunk) => {
1486
+ merged.set(chunk.bytes, offset);
1487
+ return offset + chunk.bytes.byteLength;
1488
+ }, 0);
1449
1489
  return merged;
1450
1490
  }
1451
1491
  /**
@@ -1496,38 +1536,37 @@ function parseEncoding(header) {
1496
1536
  * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
1497
1537
  */
1498
1538
  async function decompressRequestBody(bytes, encoding, cap) {
1499
- let total = 0;
1539
+ const chunks = [];
1500
1540
  const capStream = new TransformStream({ transform(chunk, controller) {
1501
- total += chunk.byteLength;
1541
+ const total = (chunks.at(-1)?.total ?? 0) + chunk.byteLength;
1502
1542
  if (cap > 0 && total > cap) {
1503
1543
  controller.error(new ContentTooLargeError(cap));
1504
1544
  return;
1505
1545
  }
1546
+ chunks.push({
1547
+ bytes: chunk,
1548
+ total
1549
+ });
1506
1550
  controller.enqueue(chunk);
1507
1551
  } });
1508
1552
  const reader = new ReadableStream({ start(controller) {
1509
1553
  controller.enqueue(bytes);
1510
1554
  controller.close();
1511
1555
  } }).pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream).getReader();
1512
- const chunks = [];
1513
- let size = 0;
1514
1556
  try {
1515
1557
  for (;;) {
1516
- const { done, value } = await reader.read();
1558
+ const { done } = await reader.read();
1517
1559
  if (done) break;
1518
- chunks.push(value);
1519
- size += value.byteLength;
1520
1560
  }
1521
1561
  } catch (error) {
1522
1562
  if (isInstance(error, ContentTooLargeError)) throw error;
1523
1563
  throw new HTTPError(400, "malformed compressed request body");
1524
1564
  }
1525
- const merged = new Uint8Array(size);
1526
- let offset = 0;
1527
- for (const chunk of chunks) {
1528
- merged.set(chunk, offset);
1529
- offset += chunk.byteLength;
1530
- }
1565
+ const merged = new Uint8Array(chunks.at(-1)?.total ?? 0);
1566
+ chunks.reduce((offset, chunk) => {
1567
+ merged.set(chunk.bytes, offset);
1568
+ return offset + chunk.bytes.byteLength;
1569
+ }, 0);
1531
1570
  return merged;
1532
1571
  }
1533
1572
  /**
@@ -1647,8 +1686,7 @@ async function discoverPort(preferred) {
1647
1686
  throw error;
1648
1687
  }
1649
1688
  }
1650
- //#endregion
1651
- //#region src/server/Negotiator.ts
1689
+ // src/server/Negotiator.ts
1652
1690
  /**
1653
1691
  * Represents the content-negotiation machine over the weighted `Accept` family — a
1654
1692
  * reusable, cross-middleware entity rather than a middleware. Implements exactly
@@ -1674,20 +1712,16 @@ var Negotiator = class {
1674
1712
  if (available.length === 0) return void 0;
1675
1713
  const entries = parseAcceptHeader(header);
1676
1714
  if (entries.length === 0) return available[0];
1677
- let best;
1678
- let bestQuality = 0;
1679
- let bestRank = Number.POSITIVE_INFINITY;
1680
- for (const candidate of available) {
1715
+ return Iterator.from(available).reduce((previous, candidate) => {
1681
1716
  const match = matchMediaType(entries, candidate);
1682
- if (match === void 0) continue;
1717
+ if (match === void 0) return previous;
1683
1718
  const { q, rank } = match;
1684
- if (q > bestQuality || q === bestQuality && rank < bestRank) {
1685
- best = candidate;
1686
- bestQuality = q;
1687
- bestRank = rank;
1688
- }
1689
- }
1690
- return best;
1719
+ return q > (previous?.q ?? 0) || q === (previous?.q ?? 0) && rank < (previous?.rank ?? Number.POSITIVE_INFINITY) ? {
1720
+ value: candidate,
1721
+ q,
1722
+ rank
1723
+ } : previous;
1724
+ }, void 0)?.value;
1691
1725
  }
1692
1726
  encoding(header, available) {
1693
1727
  if (available.length === 0) return void 0;
@@ -1697,16 +1731,13 @@ var Negotiator = class {
1697
1731
  if (available.length === 0) return void 0;
1698
1732
  const entries = parseAcceptHeader(header);
1699
1733
  if (entries.length === 0) return available[0];
1700
- let best;
1701
- let bestQuality = 0;
1702
- for (const candidate of available) {
1734
+ return Iterator.from(available).reduce((previous, candidate) => {
1703
1735
  const quality = computeLanguageQuality(entries, candidate);
1704
- if (quality > bestQuality) {
1705
- best = candidate;
1706
- bestQuality = quality;
1707
- }
1708
- }
1709
- return best;
1736
+ return quality > (previous?.quality ?? 0) ? {
1737
+ value: candidate,
1738
+ quality
1739
+ } : previous;
1740
+ }, void 0)?.value;
1710
1741
  }
1711
1742
  /**
1712
1743
  * Dispatches the request to the handler its `Accept` header negotiates,
@@ -1726,8 +1757,36 @@ var Negotiator = class {
1726
1757
  return handler(request, context);
1727
1758
  }
1728
1759
  };
1729
- //#endregion
1730
- //#region src/server/Server.ts
1760
+ // src/server/ServerBinding.ts
1761
+ /**
1762
+ * Owns one startup attempt's listening subscription and validated bound port.
1763
+ *
1764
+ * @remarks
1765
+ * Create an instance per bind attempt. Subscribe before calling the native server's
1766
+ * `listen`, retain `pending` for failure cleanup, and record the native address after
1767
+ * listening settles. Reading `port` before a valid address was recorded throws.
1768
+ */
1769
+ var ServerBinding = class {
1770
+ #pending;
1771
+ #port;
1772
+ get pending() {
1773
+ return this.#pending;
1774
+ }
1775
+ get port() {
1776
+ if (this.#port === void 0) throw new TypeError("server bound a listener with no resolvable AddressInfo");
1777
+ return this.#port;
1778
+ }
1779
+ subscribe(server, signal) {
1780
+ const pending = once(server, "listening", { signal });
1781
+ this.#pending = pending;
1782
+ return pending;
1783
+ }
1784
+ record(address) {
1785
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
1786
+ this.#port = address.port;
1787
+ }
1788
+ };
1789
+ // src/server/Server.ts
1731
1790
  /**
1732
1791
  * Represents the HTTP server facade — an observable `node:http` lifecycle composing this
1733
1792
  * module's own middleware onion around a consumed `@orkestrel/router`
@@ -1946,13 +2005,12 @@ var Server = class {
1946
2005
  this.#accept(message, response);
1947
2006
  }
1948
2007
  async #accept(message, response) {
1949
- let raw;
1950
- try {
1951
- raw = buildRequest(message, { response });
1952
- } catch {
2008
+ const created = attempt(() => buildRequest(message, { response }));
2009
+ if (!created.success) {
1953
2010
  await this.#respond(this.#boundary(new HTTPError(400, "invalid request")), response);
1954
2011
  return;
1955
2012
  }
2013
+ const raw = created.value;
1956
2014
  const method = raw.method;
1957
2015
  const url = new URL(raw.url);
1958
2016
  const start = performance.now();
@@ -2019,15 +2077,14 @@ var Server = class {
2019
2077
  socket.destroy();
2020
2078
  return;
2021
2079
  }
2022
- let handled = false;
2023
- for (const handler of this.#upgradeHandlers) try {
2024
- if (handler(request, socket, head)) {
2025
- handled = true;
2026
- break;
2080
+ const handled = Iterator.from(this.#upgradeHandlers).some((handler) => {
2081
+ try {
2082
+ return handler(request, socket, head);
2083
+ } catch (error) {
2084
+ this.#emitter.emit("error", error);
2085
+ return false;
2027
2086
  }
2028
- } catch (error) {
2029
- this.#emitter.emit("error", error);
2030
- }
2087
+ });
2031
2088
  if (handled) this.#trackSocket(socket);
2032
2089
  else socket.destroy();
2033
2090
  this.#emitter.emit("upgrade", request, handled);
@@ -2037,14 +2094,13 @@ var Server = class {
2037
2094
  const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
2038
2095
  const binding = createAbort();
2039
2096
  const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
2040
- let listening;
2041
- let port;
2097
+ const operation = new ServerBinding();
2042
2098
  try {
2043
2099
  signal?.throwIfAborted();
2044
2100
  deadline?.start();
2045
2101
  if (deadline?.ms === 0 && startup !== void 0) await once(startup, "abort");
2046
2102
  startup?.throwIfAborted();
2047
- listening = once(server, "listening", { signal: binding.signal });
2103
+ const listening = operation.subscribe(server, binding.signal);
2048
2104
  if (startup === void 0) server.listen(this.#configuredPort ?? 0, this.#host);
2049
2105
  else server.listen({
2050
2106
  port: this.#configuredPort ?? 0,
@@ -2052,14 +2108,13 @@ var Server = class {
2052
2108
  signal: binding.signal
2053
2109
  });
2054
2110
  await listening;
2055
- const address = server.address();
2056
- if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
2057
- port = address.port;
2111
+ operation.record(server.address());
2058
2112
  } catch (error) {
2059
2113
  const expired = deadline?.expired === true;
2060
2114
  const cancelled = startup?.aborted === true;
2061
2115
  server.on("error", () => void 0);
2062
2116
  binding.abort(error);
2117
+ const listening = operation.pending;
2063
2118
  if (listening !== void 0) await listening.catch(() => void 0);
2064
2119
  await this.#close(server, true);
2065
2120
  this.#http = void 0;
@@ -2072,17 +2127,15 @@ var Server = class {
2072
2127
  relay?.[Symbol.dispose]();
2073
2128
  deadline?.clear();
2074
2129
  }
2130
+ const port = operation.port;
2075
2131
  this.#port = port;
2076
2132
  this.#status = "listening";
2077
2133
  this.#emitter.emit("start", port);
2078
2134
  return port;
2079
2135
  }
2080
2136
  #createBody(request) {
2081
- let cached;
2082
- return () => {
2083
- cached ??= readBody(request, { limit: this.#limit });
2084
- return cached;
2085
- };
2137
+ const bodies = iterateRequestBody(request, this.#limit);
2138
+ return () => bodies.next().value;
2086
2139
  }
2087
2140
  #close(server, force) {
2088
2141
  return new Promise((resolve) => {
@@ -2125,10 +2178,9 @@ var Server = class {
2125
2178
  #trackStart() {
2126
2179
  this.#enter();
2127
2180
  this.#pending += 1;
2128
- let done = false;
2181
+ const completions = [void 0].values();
2129
2182
  return () => {
2130
- if (done) return;
2131
- done = true;
2183
+ if (completions.next().done) return;
2132
2184
  this.#pending -= 1;
2133
2185
  this.#settle();
2134
2186
  };
@@ -2147,8 +2199,7 @@ var Server = class {
2147
2199
  await once(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
2148
2200
  }
2149
2201
  };
2150
- //#endregion
2151
- //#region src/server/Stream.ts
2202
+ // src/server/Stream.ts
2152
2203
  /**
2153
2204
  * Represents the Server-Sent-Events handle over an open, fetch-standard streaming
2154
2205
  * `Response`. Implements exactly {@link StreamInterface}.
@@ -2259,8 +2310,7 @@ var Stream = class {
2259
2310
  this.#wakeup = void 0;
2260
2311
  }
2261
2312
  };
2262
- //#endregion
2263
- //#region src/server/factories.ts
2313
+ // src/server/factories.ts
2264
2314
  /**
2265
2315
  * Creates a {@link NegotiatorInterface} — the reusable content-negotiation
2266
2316
  * machine over the weighted `Accept` family.
@@ -2350,7 +2400,6 @@ function createServer(options) {
2350
2400
  function createStream(options) {
2351
2401
  return new Stream(options);
2352
2402
  }
2353
- //#endregion
2354
- export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server, ServerError, Stream, clearCookie, collectRequestBody, compose, computeBodyETag, computeClientKey, computeCodingQuality, computeIPv6Network, computeLanguageQuality, createNegotiator, createServer, createStream, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isServerError, isValidRequestId, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, parseAcceptHeader, parseCookies, parseEncoding, parseRange, probePort, readBody, readSignedCookie, resolveCoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2403
+ export { COMPRESSIBLE_TYPES, CONTENT_TOO_LARGE_ERROR_BRAND, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SERVER_ERROR_BRAND, SSE_HEADERS, Server, ServerBinding, ServerError, Stream, clearCookie, collectRequestBody, compose, computeBodyETag, computeClientKey, computeCodingQuality, computeIPv6Network, computeLanguageQuality, createNegotiator, createServer, createStream, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, isAddressInfo, isCompressibleType, isContentTooLargeError, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isServerError, isValidRequestId, iterateMediaMatches, iterateRequestBody, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, parseAcceptHeader, parseCookies, parseEncoding, parseRange, probePort, readBody, readSignedCookie, resolveCoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2355
2404
 
2356
2405
  //# sourceMappingURL=index.js.map