@orkestrel/server 0.0.6 → 0.0.8

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,5 @@
1
- import { isFiniteNumber, isFunction, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
1
+ import { isFiniteNumber, isFunction, isInteger, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
2
+ import { addAbortListener, once } from "node:events";
2
3
  import { createServer as createServer$1 } from "node:net";
3
4
  import { createServer as createServer$2 } from "node:http";
4
5
  import { createAbort, linkSignal } from "@orkestrel/abort";
@@ -140,7 +141,7 @@ var HTTPError = class extends Error {
140
141
  super(message);
141
142
  this.name = "HTTPError";
142
143
  this.status = status;
143
- this.context = context;
144
+ if (context !== void 0) this.context = context;
144
145
  }
145
146
  };
146
147
  /**
@@ -240,19 +241,36 @@ function isHTTPError(value) {
240
241
  * ```
241
242
  */
242
243
  function compose(middleware, terminal) {
244
+ return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
245
+ }
246
+ /**
247
+ * Wrap one middleware layer around its downstream handler.
248
+ *
249
+ * @remarks
250
+ * The returned handler enforces the one-call `next` invariant while preserving
251
+ * request substitution and the middleware's synchronous or asynchronous result.
252
+ *
253
+ * @typeParam TState - The consumer's opaque per-request state type
254
+ * @param layer - The middleware layer to invoke
255
+ * @param next - The downstream handler wrapped by `layer`
256
+ * @returns A handler with `layer` composed around `next`
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * const handle = wrapMiddleware(
261
+ * async (_request, _context, next) => next(),
262
+ * async () => new Response('ok'),
263
+ * )
264
+ * ```
265
+ */
266
+ function wrapMiddleware(layer, next) {
243
267
  return async (request, context) => {
244
- const dispatch = (index, currentRequest) => {
245
- const layer = middleware[index];
246
- if (layer === void 0) return terminal(currentRequest, context);
247
- let called = false;
248
- const next = (nextRequest) => {
249
- if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
250
- called = true;
251
- return dispatch(index + 1, nextRequest ?? currentRequest);
252
- };
253
- return Promise.resolve(layer(currentRequest, context, next));
254
- };
255
- return dispatch(0, request);
268
+ let called = false;
269
+ return Promise.resolve(layer(request, context, (nextRequest) => {
270
+ if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
271
+ called = true;
272
+ return next(nextRequest ?? request, context);
273
+ }));
256
274
  };
257
275
  }
258
276
  /**
@@ -1026,7 +1044,9 @@ function parseRange(header, size) {
1026
1044
  if (header === void 0) return void 0;
1027
1045
  const match = /^bytes=(.*)$/.exec(header.trim());
1028
1046
  if (match === null) return void 0;
1029
- const spec = match[1].trim();
1047
+ const capture = match[1];
1048
+ if (capture === void 0) return void 0;
1049
+ const spec = capture.trim();
1030
1050
  if (spec.includes(",")) return void 0;
1031
1051
  const dash = spec.indexOf("-");
1032
1052
  if (dash < 0) return void 0;
@@ -1182,8 +1202,12 @@ function ipv6Network(address) {
1182
1202
  const percent = address.indexOf("%");
1183
1203
  const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
1184
1204
  if (halves.length > 2) return void 0;
1185
- const head = halves[0] === "" ? [] : halves[0].split(":");
1186
- const tail = halves.length === 2 ? halves[1] === "" ? [] : halves[1].split(":") : [];
1205
+ const first = halves[0];
1206
+ if (first === void 0) return void 0;
1207
+ const second = halves[1];
1208
+ if (halves.length === 2 && second === void 0) return void 0;
1209
+ const head = first === "" ? [] : first.split(":");
1210
+ const tail = second === void 0 || second === "" ? [] : second.split(":");
1187
1211
  let groups;
1188
1212
  if (halves.length === 2) {
1189
1213
  const missing = 8 - head.length - tail.length;
@@ -1253,6 +1277,28 @@ function serializeEvent(message) {
1253
1277
  return `${lines.join("\n")}\n\n`;
1254
1278
  }
1255
1279
  /**
1280
+ * Enqueue encoded text into an open byte stream.
1281
+ *
1282
+ * @param controller - The stream controller, when the stream has started
1283
+ * @param encoder - The encoder used for the stream's byte representation
1284
+ * @param closed - Whether the stream has already ended or been cancelled
1285
+ * @param text - The text to encode and enqueue
1286
+ * @returns Nothing
1287
+ *
1288
+ * @example
1289
+ * ```ts
1290
+ * const body = new ReadableStream<Uint8Array>({
1291
+ * start(controller) {
1292
+ * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
1293
+ * },
1294
+ * })
1295
+ * ```
1296
+ */
1297
+ function enqueueStreamText(controller, encoder, closed, text) {
1298
+ if (closed || controller === void 0) return;
1299
+ controller.enqueue(encoder.encode(text));
1300
+ }
1301
+ /**
1256
1302
  * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1257
1303
  * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1258
1304
  *
@@ -1293,24 +1339,19 @@ function openStream(options) {
1293
1339
  ...SSE_HEADERS,
1294
1340
  ...options?.headers
1295
1341
  });
1296
- const response = new Response(body, {
1297
- status: options?.status ?? 200,
1298
- headers
1299
- });
1300
- const enqueue = (text) => {
1301
- if (closed || controller === void 0) return;
1302
- controller.enqueue(encoder.encode(text));
1303
- };
1304
1342
  return {
1305
- response,
1343
+ response: new Response(body, {
1344
+ status: options?.status ?? 200,
1345
+ headers
1346
+ }),
1306
1347
  get closed() {
1307
1348
  return closed;
1308
1349
  },
1309
1350
  write(message) {
1310
- enqueue(serializeEvent(message));
1351
+ enqueueStreamText(controller, encoder, closed, serializeEvent(message));
1311
1352
  },
1312
1353
  comment(text) {
1313
- enqueue(`: ${text}\n\n`);
1354
+ enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
1314
1355
  },
1315
1356
  end() {
1316
1357
  if (closed) return;
@@ -1563,6 +1604,29 @@ function isAddressInfo(value) {
1563
1604
  return isRecord(value) && isNumber(value.port);
1564
1605
  }
1565
1606
  /**
1607
+ * Bind and close a throwaway TCP server to resolve one available port.
1608
+ *
1609
+ * @param port - The requested port, with `0` selecting an ephemeral port
1610
+ * @returns The bound port after the probe server has closed
1611
+ *
1612
+ * @example
1613
+ * ```ts
1614
+ * const port = await probePort(0)
1615
+ * ```
1616
+ */
1617
+ async function probePort(port) {
1618
+ const probe = createServer$1();
1619
+ const listening = once(probe, "listening");
1620
+ probe.listen(port);
1621
+ await listening;
1622
+ const address = probe.address();
1623
+ const resolved = isAddressInfo(address) ? address.port : 0;
1624
+ const closed = once(probe, "close");
1625
+ probe.close();
1626
+ await closed;
1627
+ return resolved;
1628
+ }
1629
+ /**
1566
1630
  * Find a FREE TCP port — bind a throwaway `node:net` server, read the
1567
1631
  * OS-assigned port, close it, and resolve that port.
1568
1632
  *
@@ -1587,25 +1651,14 @@ function isAddressInfo(value) {
1587
1651
  * const port = await discoverPort() // a guaranteed-free ephemeral port
1588
1652
  * ```
1589
1653
  */
1590
- function discoverPort(preferred) {
1591
- return new Promise((resolve, reject) => {
1592
- const bind = (port, fallback) => {
1593
- const probe = createServer$1();
1594
- const onError = (error) => {
1595
- probe.close();
1596
- const taken = "code" in error && error.code === "EADDRINUSE";
1597
- if (fallback && taken) bind(0, false);
1598
- else reject(error);
1599
- };
1600
- probe.once("error", onError);
1601
- probe.listen(port, () => {
1602
- const address = probe.address();
1603
- const resolved = isAddressInfo(address) ? address.port : 0;
1604
- probe.close(() => resolve(resolved));
1605
- });
1606
- };
1607
- bind(preferred ?? 0, preferred !== void 0);
1608
- });
1654
+ async function discoverPort(preferred) {
1655
+ if (preferred === void 0) return probePort(0);
1656
+ try {
1657
+ return await probePort(preferred);
1658
+ } catch (error) {
1659
+ if (error instanceof Error && "code" in error && error.code === "EADDRINUSE") return probePort(0);
1660
+ throw error;
1661
+ }
1609
1662
  }
1610
1663
  //#endregion
1611
1664
  //#region src/server/Negotiator.ts
@@ -1692,14 +1745,17 @@ var Negotiator = class {
1692
1745
  * @typeParam TState - The consumer's opaque per-request state type
1693
1746
  *
1694
1747
  * @remarks
1695
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1748
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1696
1749
  * server, binds the configured {@link ServerOptions.host} / {@link
1697
1750
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1698
- * bound address), and transitions `idle → starting → listening`. `stop()`
1699
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1700
- * stop signal so in-flight handlers observe cancellation, drains up to the
1701
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1702
- * `destroy()` is the idempotent final teardown.
1751
+ * bound address), observes caller cancellation plus the configured
1752
+ * `timeouts.start` deadline while the bind is pending, and transitions
1753
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1754
+ * partial server and resets to `idle` for another start. `stop()` transitions
1755
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1756
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1757
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1758
+ * is the idempotent final teardown.
1703
1759
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1704
1760
  * `close`); a `Request` is built via the router's `buildRequest`, its
1705
1761
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1742,12 +1798,13 @@ var Server = class {
1742
1798
  #expose;
1743
1799
  #report;
1744
1800
  #timeouts;
1801
+ #sockets;
1745
1802
  #http;
1746
1803
  #abort = createAbort();
1804
+ #wakeup = createAbort();
1747
1805
  #status = "idle";
1748
1806
  #port;
1749
1807
  #pending = 0;
1750
- #waiters = [];
1751
1808
  constructor(options) {
1752
1809
  if (!isFunction(options.state)) throw new TypeError("ServerOptions.state must be a function");
1753
1810
  if (options.report !== void 0 && !isFunction(options.report)) throw new TypeError("ServerOptions.report must be a function");
@@ -1758,6 +1815,8 @@ var Server = class {
1758
1815
  const timeouts = options.timeouts ?? {};
1759
1816
  for (const [name, value] of Object.entries(timeouts)) if (value !== void 0 && (!isFiniteNumber(value) || value < 0)) throw new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`);
1760
1817
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1818
+ const sockets = options.sockets ?? {};
1819
+ for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!isInteger(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1761
1820
  this.#dispatcher = options.dispatcher;
1762
1821
  this.#state = options.state;
1763
1822
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1768,9 +1827,10 @@ var Server = class {
1768
1827
  this.#expose = options.expose ?? false;
1769
1828
  this.#report = options.report;
1770
1829
  this.#timeouts = timeouts;
1830
+ this.#sockets = sockets;
1771
1831
  this.#emitter = new Emitter({
1772
- on: options.on,
1773
- error: options.error
1832
+ ...options.on === void 0 ? {} : { on: options.on },
1833
+ ...options.error === void 0 ? {} : { error: options.error }
1774
1834
  });
1775
1835
  }
1776
1836
  get status() {
@@ -1792,7 +1852,7 @@ var Server = class {
1792
1852
  upgrade(handler) {
1793
1853
  this.#upgradeHandlers.push(handler);
1794
1854
  }
1795
- start() {
1855
+ start(signal) {
1796
1856
  if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1797
1857
  this.#status = "starting";
1798
1858
  this.#abort = createAbort();
@@ -1800,27 +1860,12 @@ var Server = class {
1800
1860
  if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
1801
1861
  if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
1802
1862
  if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
1863
+ if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
1864
+ if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
1865
+ if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
1803
1866
  server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
1804
1867
  this.#http = server;
1805
- return new Promise((resolve, reject) => {
1806
- const onError = (error) => {
1807
- server.off("listening", onListening);
1808
- this.#http = void 0;
1809
- this.#status = "idle";
1810
- reject(error);
1811
- };
1812
- const onListening = () => {
1813
- server.off("error", onError);
1814
- const port = this.#resolvePort(server);
1815
- this.#port = port;
1816
- this.#status = "listening";
1817
- this.#emitter.emit("start", port);
1818
- resolve(port);
1819
- };
1820
- server.once("error", onError);
1821
- server.once("listening", onListening);
1822
- server.listen(this.#configuredPort ?? 0, this.#host);
1823
- });
1868
+ return this.#listen(server, signal);
1824
1869
  }
1825
1870
  async stop() {
1826
1871
  if (this.#status !== "listening") return;
@@ -1873,19 +1918,16 @@ var Server = class {
1873
1918
  const linked = linkSignal(raw.signal, this.#abort.signal);
1874
1919
  const request = new Request(raw, { signal: linked });
1875
1920
  this.#emitter.emit("request", method, url.pathname);
1921
+ const ip = message.socket.remoteAddress;
1876
1922
  const connection = {
1877
- ip: message.socket.remoteAddress,
1923
+ ...ip === void 0 ? {} : { ip },
1878
1924
  encrypted: isEncryptedSocket(message.socket)
1879
1925
  };
1880
- let cached;
1881
1926
  const context = {
1882
1927
  url,
1883
1928
  method,
1884
1929
  state: this.#state(connection),
1885
- body: () => {
1886
- cached ??= readBody(request, { limit: this.#limit });
1887
- return cached;
1888
- }
1930
+ body: this.#createBody(request)
1889
1931
  };
1890
1932
  const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
1891
1933
  await this.#respond(result, response);
@@ -1948,6 +1990,55 @@ var Server = class {
1948
1990
  if (isAddressInfo(address)) return address.port;
1949
1991
  return 0;
1950
1992
  }
1993
+ async #listen(server, signal) {
1994
+ const deadline = this.#timeouts.start === void 0 ? void 0 : createTimeout({ ms: this.#timeouts.start });
1995
+ const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
1996
+ const binding = createAbort();
1997
+ const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
1998
+ let listening;
1999
+ try {
2000
+ signal?.throwIfAborted();
2001
+ deadline?.start();
2002
+ if (deadline?.ms === 0 && startup !== void 0) await once(startup, "abort");
2003
+ startup?.throwIfAborted();
2004
+ listening = once(server, "listening", { signal: binding.signal });
2005
+ if (startup === void 0) server.listen(this.#configuredPort ?? 0, this.#host);
2006
+ else server.listen({
2007
+ port: this.#configuredPort ?? 0,
2008
+ ...this.#host === void 0 ? {} : { host: this.#host },
2009
+ signal: binding.signal
2010
+ });
2011
+ await listening;
2012
+ } catch (error) {
2013
+ const expired = deadline?.expired === true;
2014
+ const cancelled = startup?.aborted === true;
2015
+ server.on("error", () => void 0);
2016
+ binding.abort(error);
2017
+ if (listening !== void 0) await listening.catch(() => void 0);
2018
+ await this.#close(server, true);
2019
+ this.#http = void 0;
2020
+ this.#port = void 0;
2021
+ this.#status = "idle";
2022
+ if (expired && deadline !== void 0) throw new DOMException(`Server startup exceeded ${deadline.ms} milliseconds`, "TimeoutError");
2023
+ if (cancelled && startup !== void 0) throw startup.reason;
2024
+ throw error;
2025
+ } finally {
2026
+ relay?.[Symbol.dispose]();
2027
+ deadline?.clear();
2028
+ }
2029
+ const port = this.#resolvePort(server);
2030
+ this.#port = port;
2031
+ this.#status = "listening";
2032
+ this.#emitter.emit("start", port);
2033
+ return port;
2034
+ }
2035
+ #createBody(request) {
2036
+ let cached;
2037
+ return () => {
2038
+ cached ??= readBody(request, { limit: this.#limit });
2039
+ return cached;
2040
+ };
2041
+ }
1951
2042
  #close(server, force) {
1952
2043
  return new Promise((resolve) => {
1953
2044
  server.close(() => resolve());
@@ -1956,29 +2047,19 @@ var Server = class {
1956
2047
  });
1957
2048
  }
1958
2049
  #trackStart() {
2050
+ if (this.#pending === 0) this.#wakeup = createAbort();
1959
2051
  this.#pending += 1;
1960
2052
  let finished = false;
1961
2053
  return () => {
1962
2054
  if (finished) return;
1963
2055
  finished = true;
1964
2056
  this.#pending -= 1;
1965
- if (this.#pending === 0) {
1966
- const waiters = this.#waiters;
1967
- this.#waiters = [];
1968
- for (const wake of waiters) wake();
1969
- }
2057
+ if (this.#pending === 0) this.#wakeup.abort();
1970
2058
  };
1971
2059
  }
1972
- #drainPending(signal) {
1973
- if (this.#pending === 0 || signal.aborted) return Promise.resolve();
1974
- return new Promise((resolve) => {
1975
- const onDone = () => {
1976
- signal.removeEventListener("abort", onDone);
1977
- resolve();
1978
- };
1979
- this.#waiters.push(onDone);
1980
- signal.addEventListener("abort", onDone, { once: true });
1981
- });
2060
+ async #drainPending(signal) {
2061
+ if (this.#pending === 0 || signal.aborted) return;
2062
+ await once(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
1982
2063
  }
1983
2064
  };
1984
2065
  //#endregion
@@ -2033,6 +2114,6 @@ function createServer(options) {
2033
2114
  return new Server(options);
2034
2115
  }
2035
2116
  //#endregion
2036
- 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, appendCookie, clearCookie, clientRateKey, codingQuality, collectRequestBody, compose, computeBodyETag, createNegotiator, createServer, decodeBase64Url, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, encodeBase64Url, ipv6Network, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isValidRequestId, languageQuality, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, openStream, parseAcceptHeader, parseCookies, parseRange, readBody, readSignedCookie, requestEncoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, writeSignedCookie };
2117
+ 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, appendCookie, clearCookie, clientRateKey, codingQuality, collectRequestBody, compose, computeBodyETag, createNegotiator, createServer, decodeBase64Url, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, encodeBase64Url, enqueueStreamText, ipv6Network, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isValidRequestId, languageQuality, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, openStream, parseAcceptHeader, parseCookies, parseRange, probePort, readBody, readSignedCookie, requestEncoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2037
2118
 
2038
2119
  //# sourceMappingURL=index.js.map