@orkestrel/server 0.0.1 → 0.0.3

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.
@@ -0,0 +1,406 @@
1
+ import { createServer as createServer$1 } from "node:net";
2
+ import { isFiniteNumber, isFunction, isNumber, isRecord } from "@orkestrel/contract";
3
+ import { createServer as createServer$2 } from "node:http";
4
+ import { DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_MS, HTTPError, compose, isHTTPError, readBody } from "../core/index.js";
5
+ import { createAbort, linkSignal } from "@orkestrel/abort";
6
+ import { createTimeout } from "@orkestrel/timeout";
7
+ import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
8
+ import { Emitter } from "@orkestrel/emitter";
9
+ //#region src/server/helpers.ts
10
+ /**
11
+ * Whether a `node:net` `server.address()` return is the structured
12
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
13
+ * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
14
+ * and the `Server`'s own port resolution read the bound port through.
15
+ *
16
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
17
+ * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { isAddressInfo } from '@src/server'
22
+ *
23
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
24
+ * isAddressInfo(null) // false
25
+ * ```
26
+ */
27
+ function isAddressInfo(value) {
28
+ return isRecord(value) && isNumber(value.port);
29
+ }
30
+ /**
31
+ * Find a FREE TCP port — bind a throwaway `node:net` server, read the
32
+ * OS-assigned port, close it, and resolve that port.
33
+ *
34
+ * @remarks
35
+ * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
36
+ * and returns it. With a `preferred` port it tries THAT port first and
37
+ * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
38
+ * ephemeral free port rather than rejecting — a caller always gets a usable
39
+ * port. It binds then immediately closes a probe server, so the returned
40
+ * port is free at the instant of the probe (an inherent TOCTOU race — bind it
41
+ * promptly). Rejects only on an unexpected listen error other than a taken
42
+ * `preferred` port (e.g. a permission fault).
43
+ *
44
+ * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
45
+ * fall back to an ephemeral port
46
+ * @returns A free TCP port number
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * import { createServer, discoverPort } from '@src/server'
51
+ *
52
+ * const port = await discoverPort() // a guaranteed-free ephemeral port
53
+ * ```
54
+ */
55
+ function discoverPort(preferred) {
56
+ return new Promise((resolve, reject) => {
57
+ const bind = (port, fallback) => {
58
+ const probe = createServer$1();
59
+ const onError = (error) => {
60
+ probe.close();
61
+ const taken = "code" in error && error.code === "EADDRINUSE";
62
+ if (fallback && taken) bind(0, false);
63
+ else reject(error);
64
+ };
65
+ probe.once("error", onError);
66
+ probe.listen(port, () => {
67
+ const address = probe.address();
68
+ const resolved = isAddressInfo(address) ? address.port : 0;
69
+ probe.close(() => resolve(resolved));
70
+ });
71
+ };
72
+ bind(preferred ?? 0, preferred !== void 0);
73
+ });
74
+ }
75
+ //#endregion
76
+ //#region src/server/Server.ts
77
+ /**
78
+ * The HTTP server facade — an observable `node:http` lifecycle composing the
79
+ * `@src/core` middleware onion around a consumed `@orkestrel/router`
80
+ * dispatcher.
81
+ *
82
+ * @typeParam TState - The consumer's opaque per-request state type
83
+ *
84
+ * @remarks
85
+ * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
86
+ * server, binds the configured {@link ServerOptions.host} / {@link
87
+ * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
88
+ * bound address), and transitions `idle → starting → listening`. `stop()`
89
+ * transitions to `stopping`: refuses new connections, fires a fresh-per-run
90
+ * stop signal so in-flight handlers observe cancellation, drains up to the
91
+ * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
92
+ * `destroy()` is the idempotent final teardown.
93
+ * - **Per request.** In-flight is tracked (finished on response `finish` or
94
+ * `close`); a `Request` is built via the router's `buildRequest`, its
95
+ * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
96
+ * `linkSignal` (a fresh `Request` is constructed with the linked signal —
97
+ * `buildRequest`'s own abort, tied to client disconnect, composes with the
98
+ * server's stop signal via `AbortSignal.any`, so a handler awaiting
99
+ * `request.signal` observes BOTH); `context.state` is built via
100
+ * {@link ServerOptions.state} from the connection facts; the composed
101
+ * middleware onion runs, terminating in `dispatcher.handle`; the result is
102
+ * written back via `sendResponse`.
103
+ * - **The built-in boundary** wraps the WHOLE per-request chain, including
104
+ * setup: `buildRequest` runs behind its own inner boundary that maps a
105
+ * throw (e.g. a malformed `Host` header) to a silent `400` with no
106
+ * `error` emit; everything after (`Request` reconstruction, connection
107
+ * facts, `state`, the composed onion, and `dispatcher.handle`) runs
108
+ * behind the outer boundary — a thrown `HTTPError` renders as its status +
109
+ * message; any other throw renders `500` (message hidden unless
110
+ * `expose`), `report` is invoked (its own throw swallowed), and `error` is
111
+ * emitted. A server-owned last resort wraps the final `sendResponse`
112
+ * write itself: if even that fails, the connection is destroyed rather
113
+ * than left to escape as an unhandled error.
114
+ * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
115
+ * throwing handler is treated as declined and surfaced on `error`, an
116
+ * unclaimed upgrade destroys the socket), bound per-run to this instance.
117
+ * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
118
+ * exposed as `readonly emitter`; the emitter isolates a listener throw and
119
+ * routes it to the `error` OPTION (not the domain `error` event).
120
+ */
121
+ var Server = class {
122
+ id = crypto.randomUUID();
123
+ #dispatcher;
124
+ #state;
125
+ #middleware;
126
+ #upgradeHandlers = [];
127
+ #emitter;
128
+ #host;
129
+ #configuredPort;
130
+ #drain;
131
+ #limit;
132
+ #expose;
133
+ #report;
134
+ #timeouts;
135
+ #http;
136
+ #abort = createAbort();
137
+ #status = "idle";
138
+ #port;
139
+ #pending = 0;
140
+ #waiters = [];
141
+ constructor(options) {
142
+ if (!isFunction(options.state)) throw new TypeError("ServerOptions.state must be a function");
143
+ if (options.report !== void 0 && !isFunction(options.report)) throw new TypeError("ServerOptions.report must be a function");
144
+ const drain = options.drain ?? DEFAULT_DRAIN_MS;
145
+ if (!isFiniteNumber(drain) || drain < 0) throw new TypeError("ServerOptions.drain must be a non-negative finite number");
146
+ const limit = options.limit ?? DEFAULT_BODY_LIMIT;
147
+ if (!isFiniteNumber(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
148
+ const timeouts = options.timeouts ?? {};
149
+ 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`);
150
+ if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
151
+ this.#dispatcher = options.dispatcher;
152
+ this.#state = options.state;
153
+ this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
154
+ this.#host = options.host;
155
+ this.#configuredPort = options.port;
156
+ this.#drain = drain;
157
+ this.#limit = limit;
158
+ this.#expose = options.expose ?? false;
159
+ this.#report = options.report;
160
+ this.#timeouts = timeouts;
161
+ this.#emitter = new Emitter({
162
+ on: options.on,
163
+ error: options.error
164
+ });
165
+ }
166
+ get status() {
167
+ return this.#status;
168
+ }
169
+ get port() {
170
+ return this.#port;
171
+ }
172
+ get dispatcher() {
173
+ return this.#dispatcher;
174
+ }
175
+ get emitter() {
176
+ return this.#emitter;
177
+ }
178
+ use(middleware) {
179
+ if (typeof middleware === "function") this.#middleware.push(middleware);
180
+ else this.#middleware.push(...middleware);
181
+ }
182
+ upgrade(handler) {
183
+ this.#upgradeHandlers.push(handler);
184
+ }
185
+ start() {
186
+ if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
187
+ this.#status = "starting";
188
+ this.#abort = createAbort();
189
+ const server = createServer$2((request, response) => this.#handle(request, response));
190
+ if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
191
+ if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
192
+ if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
193
+ server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
194
+ this.#http = server;
195
+ return new Promise((resolve, reject) => {
196
+ const onError = (error) => {
197
+ server.off("listening", onListening);
198
+ this.#http = void 0;
199
+ this.#status = "idle";
200
+ reject(error);
201
+ };
202
+ const onListening = () => {
203
+ server.off("error", onError);
204
+ const port = this.#resolvePort(server);
205
+ this.#port = port;
206
+ this.#status = "listening";
207
+ this.#emitter.emit("start", port);
208
+ resolve(port);
209
+ };
210
+ server.once("error", onError);
211
+ server.once("listening", onListening);
212
+ server.listen(this.#configuredPort ?? 0, this.#host);
213
+ });
214
+ }
215
+ async stop() {
216
+ if (this.#status !== "listening") return;
217
+ this.#status = "stopping";
218
+ this.#emitter.emit("stop");
219
+ const server = this.#http;
220
+ this.#abort.abort();
221
+ const deadline = createTimeout({ ms: this.#drain });
222
+ deadline.start();
223
+ await this.#drainPending(deadline.signal);
224
+ deadline.clear();
225
+ const pending = this.#pending;
226
+ this.#emitter.emit("drain", pending);
227
+ if (server !== void 0) await this.#close(server, pending > 0);
228
+ this.#http = void 0;
229
+ this.#port = void 0;
230
+ this.#status = "stopped";
231
+ }
232
+ async destroy() {
233
+ if (this.#status === "stopped" && this.#http === void 0) {
234
+ this.#emitter.destroy();
235
+ return;
236
+ }
237
+ if (!this.#abort.aborted) this.#abort.abort();
238
+ const server = this.#http;
239
+ if (server !== void 0) await this.#close(server, true);
240
+ this.#http = void 0;
241
+ this.#port = void 0;
242
+ this.#status = "stopped";
243
+ this.#emitter.destroy();
244
+ }
245
+ #handle(message, response) {
246
+ const finish = this.#trackStart();
247
+ response.once("finish", finish);
248
+ response.once("close", finish);
249
+ this.#accept(message, response);
250
+ }
251
+ async #accept(message, response) {
252
+ let raw;
253
+ try {
254
+ raw = buildRequest(message);
255
+ } catch {
256
+ await this.#respond(this.#boundary(new HTTPError(400, "invalid request")), response);
257
+ return;
258
+ }
259
+ const method = raw.method;
260
+ const url = new URL(raw.url);
261
+ const start = performance.now();
262
+ try {
263
+ const linked = linkSignal(raw.signal, this.#abort.signal);
264
+ const request = new Request(raw, { signal: linked });
265
+ this.#emitter.emit("request", method, url.pathname);
266
+ const connection = {
267
+ ip: message.socket.remoteAddress,
268
+ encrypted: isEncryptedSocket(message.socket)
269
+ };
270
+ let cached;
271
+ const context = {
272
+ url,
273
+ method,
274
+ state: this.#state(connection),
275
+ body: () => {
276
+ cached ??= readBody(request, { limit: this.#limit });
277
+ return cached;
278
+ }
279
+ };
280
+ const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
281
+ await this.#respond(result, response);
282
+ this.#emitter.emit("response", {
283
+ method,
284
+ pathname: url.pathname,
285
+ status: result.status,
286
+ ms: Math.round(performance.now() - start)
287
+ });
288
+ } catch (error) {
289
+ const mapped = this.#boundary(error);
290
+ if (!isHTTPError(error)) {
291
+ this.#emitter.emit("error", error, {
292
+ method,
293
+ url
294
+ });
295
+ if (this.#report !== void 0) try {
296
+ this.#report(error, {
297
+ method,
298
+ url
299
+ });
300
+ } catch {}
301
+ }
302
+ await this.#respond(mapped, response);
303
+ this.#emitter.emit("response", {
304
+ method,
305
+ pathname: url.pathname,
306
+ status: mapped.status,
307
+ ms: Math.round(performance.now() - start)
308
+ });
309
+ }
310
+ }
311
+ async #respond(result, response) {
312
+ try {
313
+ await sendResponse(result, response);
314
+ } catch {
315
+ response.destroy();
316
+ }
317
+ }
318
+ #boundary(error) {
319
+ if (isHTTPError(error)) return new Response(error.message, { status: error.status });
320
+ const message = this.#expose && error instanceof Error ? error.message : "Internal Server Error";
321
+ return new Response(message, { status: 500 });
322
+ }
323
+ #onUpgrade(request, socket, head) {
324
+ let handled = false;
325
+ for (const handler of this.#upgradeHandlers) try {
326
+ if (handler(request, socket, head)) {
327
+ handled = true;
328
+ break;
329
+ }
330
+ } catch (error) {
331
+ this.#emitter.emit("error", error);
332
+ }
333
+ if (!handled) socket.destroy();
334
+ this.#emitter.emit("upgrade", request, handled);
335
+ }
336
+ #resolvePort(server) {
337
+ const address = server.address();
338
+ if (isAddressInfo(address)) return address.port;
339
+ return 0;
340
+ }
341
+ #close(server, force) {
342
+ return new Promise((resolve) => {
343
+ server.close(() => resolve());
344
+ if (force) server.closeAllConnections();
345
+ else server.closeIdleConnections();
346
+ });
347
+ }
348
+ #trackStart() {
349
+ this.#pending += 1;
350
+ let finished = false;
351
+ return () => {
352
+ if (finished) return;
353
+ finished = true;
354
+ this.#pending -= 1;
355
+ if (this.#pending === 0) {
356
+ const waiters = this.#waiters;
357
+ this.#waiters = [];
358
+ for (const wake of waiters) wake();
359
+ }
360
+ };
361
+ }
362
+ #drainPending(signal) {
363
+ if (this.#pending === 0 || signal.aborted) return Promise.resolve();
364
+ return new Promise((resolve) => {
365
+ const onDone = () => {
366
+ signal.removeEventListener("abort", onDone);
367
+ resolve();
368
+ };
369
+ this.#waiters.push(onDone);
370
+ signal.addEventListener("abort", onDone, { once: true });
371
+ });
372
+ }
373
+ };
374
+ //#endregion
375
+ //#region src/server/factories.ts
376
+ /**
377
+ * Create a {@link ServerInterface} — the node face's HTTP server facade over
378
+ * a consumed `@orkestrel/router` dispatcher.
379
+ *
380
+ * @typeParam TState - The consumer's opaque per-request state type
381
+ * @param options - {@link ServerOptions}
382
+ * @returns A {@link ServerInterface}, not yet started
383
+ *
384
+ * @example
385
+ * ```ts
386
+ * import { createServer } from '@src/server'
387
+ * import { createDispatcher } from '@orkestrel/router'
388
+ *
389
+ * const dispatcher = createDispatcher<{ readonly ip?: string }>()
390
+ * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
391
+ *
392
+ * const server = createServer({
393
+ * dispatcher,
394
+ * state: (connection) => ({ ip: connection.ip }),
395
+ * })
396
+ * const port = await server.start()
397
+ * await server.stop()
398
+ * ```
399
+ */
400
+ function createServer(options) {
401
+ return new Server(options);
402
+ }
403
+ //#endregion
404
+ export { Server, createServer, discoverPort, isAddressInfo };
405
+
406
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#status","#port","#abort","#handle","#onUpgrade","#http","#resolvePort","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#waiters"],"sources":["../../../src/server/helpers.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["// ============================================================================\n// The node face — pure helpers (AGENTS §5). Every function here is genuinely\n// node-bound (a `node:net` probe, an `AddressInfo` narrow) — everything\n// fetch/string-pure lives in `@src/core` and is consumed, never duplicated\n// (the socket-encrypted narrow and the `Request`/`Response` conversion are\n// `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` / `sendResponse`).\n// ============================================================================\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord } from '@orkestrel/contract'\n\n/**\n * Whether a `node:net` `server.address()` return is the structured\n * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`\n * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`\n * and the `Server`'s own port resolution read the bound port through.\n *\n * @param value - The `server.address()` return (`AddressInfo | string | null`)\n * @returns `true` when `value` is an `AddressInfo` with a numeric `port`\n *\n * @example\n * ```ts\n * import { isAddressInfo } from '@src/server'\n *\n * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true\n * isAddressInfo(null) // false\n * ```\n */\nexport function isAddressInfo(value: unknown): value is AddressInfo {\n\treturn isRecord(value) && isNumber(value.port)\n}\n\n/**\n * Find a FREE TCP port — bind a throwaway `node:net` server, read the\n * OS-assigned port, close it, and resolve that port.\n *\n * @remarks\n * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)\n * and returns it. With a `preferred` port it tries THAT port first and\n * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an\n * ephemeral free port rather than rejecting — a caller always gets a usable\n * port. It binds then immediately closes a probe server, so the returned\n * port is free at the instant of the probe (an inherent TOCTOU race — bind it\n * promptly). Rejects only on an unexpected listen error other than a taken\n * `preferred` port (e.g. a permission fault).\n *\n * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒\n * fall back to an ephemeral port\n * @returns A free TCP port number\n *\n * @example\n * ```ts\n * import { createServer, discoverPort } from '@src/server'\n *\n * const port = await discoverPort() // a guaranteed-free ephemeral port\n * ```\n */\nexport function discoverPort(preferred?: number): Promise<number> {\n\treturn new Promise<number>((resolve, reject) => {\n\t\tconst bind = (port: number, fallback: boolean): void => {\n\t\t\tconst probe = createNetServer()\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tprobe.close()\n\t\t\t\tconst taken = 'code' in error && error.code === 'EADDRINUSE'\n\t\t\t\tif (fallback && taken) bind(0, false)\n\t\t\t\telse reject(error)\n\t\t\t}\n\t\t\tprobe.once('error', onError)\n\t\t\tprobe.listen(port, () => {\n\t\t\t\tconst address = probe.address()\n\t\t\t\tconst resolved = isAddressInfo(address) ? address.port : 0\n\t\t\t\tprobe.close(() => resolve(resolved))\n\t\t\t})\n\t\t}\n\t\tbind(preferred ?? 0, preferred !== undefined)\n\t})\n}\n","import type { IncomingMessage, Server as NodeHTTPServer, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { AbortInterface } from '@orkestrel/abort'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { MiddlewareContext, MiddlewareHandler } from '@src/core'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { createServer as createHTTPServer } from 'node:http'\nimport {\n\tcompose,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tHTTPError,\n\tisHTTPError,\n\treadBody,\n} from '@src/core'\nimport { createAbort, linkSignal } from '@orkestrel/abort'\nimport { createTimeout } from '@orkestrel/timeout'\nimport { buildRequest, isEncryptedSocket, sendResponse } from '@orkestrel/router/server'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isFiniteNumber, isFunction } from '@orkestrel/contract'\nimport { isAddressInfo } from './helpers.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing the\n * `@src/core` middleware onion around a consumed `@orkestrel/router`\n * dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n *\n * @remarks\n * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`\n * server, binds the configured {@link ServerOptions.host} / {@link\n * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the\n * bound address), and transitions `idle → starting → listening`. `stop()`\n * transitions to `stopping`: refuses new connections, fires a fresh-per-run\n * stop signal so in-flight handlers observe cancellation, drains up to the\n * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.\n * `destroy()` is the idempotent final teardown.\n * - **Per request.** In-flight is tracked (finished on response `finish` or\n * `close`); a `Request` is built via the router's `buildRequest`, its\n * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s\n * `linkSignal` (a fresh `Request` is constructed with the linked signal —\n * `buildRequest`'s own abort, tied to client disconnect, composes with the\n * server's stop signal via `AbortSignal.any`, so a handler awaiting\n * `request.signal` observes BOTH); `context.state` is built via\n * {@link ServerOptions.state} from the connection facts; the composed\n * middleware onion runs, terminating in `dispatcher.handle`; the result is\n * written back via `sendResponse`.\n * - **The built-in boundary** wraps the WHOLE per-request chain, including\n * setup: `buildRequest` runs behind its own inner boundary that maps a\n * throw (e.g. a malformed `Host` header) to a silent `400` with no\n * `error` emit; everything after (`Request` reconstruction, connection\n * facts, `state`, the composed onion, and `dispatcher.handle`) runs\n * behind the outer boundary — a thrown `HTTPError` renders as its status +\n * message; any other throw renders `500` (message hidden unless\n * `expose`), `report` is invoked (its own throw swallowed), and `error` is\n * emitted. A server-owned last resort wraps the final `sendResponse`\n * write itself: if even that fails, the connection is destroyed rather\n * than left to escape as an unhandled error.\n * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a\n * throwing handler is treated as declined and surfaced on `error`, an\n * unclaimed upgrade destroys the socket), bound per-run to this instance.\n * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}\n * exposed as `readonly emitter`; the emitter isolates a listener throw and\n * routes it to the `error` OPTION (not the domain `error` event).\n */\nexport class Server<TState> implements ServerInterface<TState> {\n\treadonly id = crypto.randomUUID()\n\treadonly #dispatcher: DispatcherInterface<TState>\n\treadonly #state: ConnectionStateFunction<TState>\n\treadonly #middleware: MiddlewareHandler<TState>[]\n\treadonly #upgradeHandlers: UpgradeHandler[] = []\n\treadonly #emitter: Emitter<ServerEventMap>\n\treadonly #host: string | undefined\n\treadonly #configuredPort: number | undefined\n\treadonly #drain: number\n\treadonly #limit: number\n\treadonly #expose: boolean\n\treadonly #report: ((error: unknown, request?: { method: string; url: URL }) => void) | undefined\n\treadonly #timeouts: {\n\t\treadonly request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\t#waiters: (() => void)[] = []\n\n\tconstructor(options: ServerOptions<TState>) {\n\t\tif (!isFunction(options.state)) throw new TypeError('ServerOptions.state must be a function')\n\t\tif (options.report !== undefined && !isFunction(options.report))\n\t\t\tthrow new TypeError('ServerOptions.report must be a function')\n\t\tconst drain = options.drain ?? DEFAULT_DRAIN_MS\n\t\tif (!isFiniteNumber(drain) || drain < 0)\n\t\t\tthrow new TypeError('ServerOptions.drain must be a non-negative finite number')\n\t\tconst limit = options.limit ?? DEFAULT_BODY_LIMIT\n\t\tif (!isFiniteNumber(limit) || limit < 0)\n\t\t\tthrow new TypeError('ServerOptions.limit must be a non-negative finite number')\n\t\tconst timeouts = options.timeouts ?? {}\n\t\tfor (const [name, value] of Object.entries(timeouts)) {\n\t\t\tif (value !== undefined && (!isFiniteNumber(value) || value < 0))\n\t\t\t\tthrow new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`)\n\t\t}\n\t\tif (\n\t\t\ttimeouts.headers !== undefined &&\n\t\t\ttimeouts.keepalive !== undefined &&\n\t\t\ttimeouts.headers > timeouts.keepalive\n\t\t) {\n\t\t\tthrow new TypeError('ServerOptions.timeouts.headers must not exceed timeouts.keepalive')\n\t\t}\n\t\tthis.#dispatcher = options.dispatcher\n\t\tthis.#state = options.state\n\t\tthis.#middleware = options.middleware === undefined ? [] : [...options.middleware]\n\t\tthis.#host = options.host\n\t\tthis.#configuredPort = options.port\n\t\tthis.#drain = drain\n\t\tthis.#limit = limit\n\t\tthis.#expose = options.expose ?? false\n\t\tthis.#report = options.report\n\t\tthis.#timeouts = timeouts\n\t\tthis.#emitter = new Emitter<ServerEventMap>({ on: options.on, error: options.error })\n\t}\n\n\tget status(): ServerStatus {\n\t\treturn this.#status\n\t}\n\n\tget port(): number | undefined {\n\t\treturn this.#port\n\t}\n\n\tget dispatcher(): DispatcherInterface<TState> {\n\t\treturn this.#dispatcher\n\t}\n\n\tget emitter(): EmitterInterface<ServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tuse(middleware: MiddlewareHandler<TState>): void\n\tuse(middleware: readonly MiddlewareHandler<TState>[]): void\n\tuse(middleware: MiddlewareHandler<TState> | readonly MiddlewareHandler<TState>[]): void {\n\t\tif (typeof middleware === 'function') this.#middleware.push(middleware)\n\t\telse this.#middleware.push(...middleware)\n\t}\n\n\tupgrade(handler: UpgradeHandler): void {\n\t\tthis.#upgradeHandlers.push(handler)\n\t}\n\n\tstart(): Promise<number> {\n\t\tif (this.#status !== 'idle' && this.#status !== 'stopped') {\n\t\t\treturn Promise.reject(new Error(`server cannot start from '${this.#status}'`))\n\t\t}\n\t\tthis.#status = 'starting'\n\t\t// A fresh stop signal per run, so a restarted server is not born aborted.\n\t\tthis.#abort = createAbort()\n\t\tconst server = createHTTPServer((request, response) => this.#handle(request, response))\n\t\tif (this.#timeouts.request !== undefined) server.requestTimeout = this.#timeouts.request\n\t\tif (this.#timeouts.headers !== undefined) server.headersTimeout = this.#timeouts.headers\n\t\tif (this.#timeouts.keepalive !== undefined) server.keepAliveTimeout = this.#timeouts.keepalive\n\t\t// Bound to THIS run's server instance, discarded with it on stop/restart —\n\t\t// no manual removal needed (the same per-run lifecycle as the handler above).\n\t\tserver.on('upgrade', (request, socket, head) => this.#onUpgrade(request, socket, head))\n\t\tthis.#http = server\n\t\treturn new Promise<number>((resolve, reject) => {\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tserver.off('listening', onListening)\n\t\t\t\tthis.#http = undefined\n\t\t\t\tthis.#status = 'idle'\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst onListening = (): void => {\n\t\t\t\tserver.off('error', onError)\n\t\t\t\tconst port = this.#resolvePort(server)\n\t\t\t\tthis.#port = port\n\t\t\t\tthis.#status = 'listening'\n\t\t\t\tthis.#emitter.emit('start', port)\n\t\t\t\tresolve(port)\n\t\t\t}\n\t\t\tserver.once('error', onError)\n\t\t\tserver.once('listening', onListening)\n\t\t\tserver.listen(this.#configuredPort ?? 0, this.#host)\n\t\t})\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (this.#status !== 'listening') return\n\t\tthis.#status = 'stopping'\n\t\tthis.#emitter.emit('stop')\n\t\tconst server = this.#http\n\t\t// A pure signal — NOT the drain deadline's parent (a parent abort would\n\t\t// clear the Timeout so it never fires). The drain deadline is an\n\t\t// independent clock; the wake-park below resolves on the last finish OR\n\t\t// the deadline, event-driven, never a busy-loop.\n\t\tthis.#abort.abort()\n\t\tconst deadline: TimeoutInterface = createTimeout({ ms: this.#drain })\n\t\tdeadline.start()\n\t\tawait this.#drainPending(deadline.signal)\n\t\tdeadline.clear()\n\t\tconst pending = this.#pending\n\t\tthis.#emitter.emit('drain', pending)\n\t\tif (server !== undefined) await this.#close(server, pending > 0)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#status === 'stopped' && this.#http === undefined) {\n\t\t\tthis.#emitter.destroy()\n\t\t\treturn\n\t\t}\n\t\tif (!this.#abort.aborted) this.#abort.abort()\n\t\tconst server = this.#http\n\t\tif (server !== undefined) await this.#close(server, true)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Track the request for draining FIRST — before anything that can throw —\n\t// so the sync listener itself never throws; the rest of setup (which CAN\n\t// throw on a malformed request) is deferred into the async `#accept`\n\t// entry, kept behind the built-in boundary.\n\t#handle(message: IncomingMessage, response: ServerResponse): void {\n\t\tconst finish = this.#trackStart()\n\t\tresponse.once('finish', finish)\n\t\tresponse.once('close', finish)\n\t\tvoid this.#accept(message, response)\n\t}\n\n\t// Build the fetch `Request` + `MiddlewareContext`, run the composed onion,\n\t// and write the result back — every escaping throw is caught so the\n\t// process can never crash on an unhandled handler (or malformed request)\n\t// error. `buildRequest` runs behind its OWN inner boundary: a throw there\n\t// (e.g. a malformed `Host` header) maps to a silent `400`, never `error`.\n\tasync #accept(message: IncomingMessage, response: ServerResponse): Promise<void> {\n\t\tlet raw: Request\n\t\ttry {\n\t\t\traw = buildRequest(message)\n\t\t} catch {\n\t\t\tawait this.#respond(this.#boundary(new HTTPError(400, 'invalid request')), response)\n\t\t\treturn\n\t\t}\n\t\t// Hoisted above the inner try (not block-scoped inside it) so the catch\n\t\t// below can attach real request context to the `error` emit / `report`\n\t\t// sink — and so `response` can be emitted with the same facts on either\n\t\t// the success or the error path.\n\t\tconst method = raw.method\n\t\tconst url = new URL(raw.url)\n\t\tconst start = performance.now()\n\t\ttry {\n\t\t\tconst linked = linkSignal(raw.signal, this.#abort.signal)\n\t\t\tconst request = new Request(raw, { signal: linked })\n\t\t\tthis.#emitter.emit('request', method, url.pathname)\n\t\t\tconst connection = {\n\t\t\t\tip: message.socket.remoteAddress,\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tlet cached: Promise<unknown> | undefined\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl,\n\t\t\t\tmethod,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tbody: () => {\n\t\t\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\t\t\treturn cached\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst runner = compose(this.#middleware, (currentRequest, currentContext) =>\n\t\t\t\tthis.#dispatcher.handle(currentRequest, currentContext.state),\n\t\t\t)\n\t\t\tconst result = await runner(request, context)\n\t\t\tawait this.#respond(result, response)\n\t\t\tthis.#emitter.emit('response', {\n\t\t\t\tmethod,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tstatus: result.status,\n\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tconst mapped = this.#boundary(error)\n\t\t\tif (!isHTTPError(error)) {\n\t\t\t\tthis.#emitter.emit('error', error, { method, url })\n\t\t\t\tif (this.#report !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#report(error, { method, url })\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Swallowed — reporting can never crash the response.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait this.#respond(mapped, response)\n\t\t\tthis.#emitter.emit('response', {\n\t\t\t\tmethod,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tstatus: mapped.status,\n\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t})\n\t\t}\n\t}\n\n\t// The server-owned last resort: even a write failure inside\n\t// `sendResponse` cannot escape and crash the process — the underlying\n\t// response (and its socket) is destroyed instead.\n\tasync #respond(result: Response, response: ServerResponse): Promise<void> {\n\t\ttry {\n\t\t\tawait sendResponse(result, response)\n\t\t} catch {\n\t\t\tresponse.destroy()\n\t\t}\n\t}\n\n\t// The built-in boundary — an `HTTPError` renders as its status + message;\n\t// any other throw renders `500` with its message hidden unless `expose`.\n\t#boundary(error: unknown): Response {\n\t\tif (isHTTPError(error)) return new Response(error.message, { status: error.status })\n\t\tconst message = this.#expose && error instanceof Error ? error.message : 'Internal Server Error'\n\t\treturn new Response(message, { status: 500 })\n\t}\n\n\t// Fan a raw protocol-upgrade out to the registered handlers in\n\t// registration order: the FIRST to return `true` CLAIMS the socket. A\n\t// throwing handler is treated as DECLINED — surfaced on `error` — and the\n\t// fan-out continues so a later handler can still claim. Unclaimed ⇒ the\n\t// socket is destroyed so an unhandled upgrade never leaks a connection.\n\t#onUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {\n\t\tlet handled = false\n\t\tfor (const handler of this.#upgradeHandlers) {\n\t\t\ttry {\n\t\t\t\tif (handler(request, socket, head)) {\n\t\t\t\t\thandled = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.#emitter.emit('error', error)\n\t\t\t}\n\t\t}\n\t\tif (!handled) socket.destroy()\n\t\tthis.#emitter.emit('upgrade', request, handled)\n\t}\n\n\t// Resolve the bound port from the server's address, narrowed via a guard\n\t// (an `AddressInfo` carries a numeric `port`; a string / null address has\n\t// none). No assertion — an unresolvable address yields `0`.\n\t#resolvePort(server: NodeHTTPServer): number {\n\t\tconst address = server.address()\n\t\tif (isAddressInfo(address)) return address.port\n\t\treturn 0\n\t}\n\n\t// Close the underlying server, resolving once it stops accepting\n\t// connections. A keep-alive client leaves its socket IDLE after a\n\t// response, which would hang a plain `close()` — so idle sockets are\n\t// always dropped (an in-flight request is untouched); when `force` is set\n\t// (the drain deadline fired with work still in flight, or `destroy`)\n\t// every open socket is destroyed so the callback fires promptly.\n\t#close(server: NodeHTTPServer, force: boolean): Promise<void> {\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tserver.close(() => resolve())\n\t\t\tif (force) server.closeAllConnections()\n\t\t\telse server.closeIdleConnections()\n\t\t})\n\t}\n\n\t// Track one in-flight request; returns an idempotent finish thunk. When\n\t// the last in-flight request finishes, every parked drain waiter is woken\n\t// — event-driven, never a busy-loop.\n\t#trackStart(): () => void {\n\t\tthis.#pending += 1\n\t\tlet finished = false\n\t\treturn () => {\n\t\t\tif (finished) return\n\t\t\tfinished = true\n\t\t\tthis.#pending -= 1\n\t\t\tif (this.#pending === 0) {\n\t\t\t\tconst waiters = this.#waiters\n\t\t\t\tthis.#waiters = []\n\t\t\t\tfor (const wake of waiters) wake()\n\t\t\t}\n\t\t}\n\t}\n\n\t// Park until the in-flight count reaches zero OR `signal` fires —\n\t// event-driven (wake-park), no polling.\n\t#drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return Promise.resolve()\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tconst onDone = (): void => {\n\t\t\t\tsignal.removeEventListener('abort', onDone)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.#waiters.push(onDone)\n\t\t\tsignal.addEventListener('abort', onDone, { once: true })\n\t\t})\n\t}\n}\n","import type { ServerInterface, ServerOptions } from './types.js'\nimport { Server } from './Server.js'\n\n/**\n * Create a {@link ServerInterface} — the node face's HTTP server facade over\n * a consumed `@orkestrel/router` dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param options - {@link ServerOptions}\n * @returns A {@link ServerInterface}, not yet started\n *\n * @example\n * ```ts\n * import { createServer } from '@src/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * const dispatcher = createDispatcher<{ readonly ip?: string }>()\n * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })\n *\n * const server = createServer({\n * \tdispatcher,\n * \tstate: (connection) => ({ ip: connection.ip }),\n * })\n * const port = await server.start()\n * await server.stop()\n * ```\n */\nexport function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState> {\n\treturn new Server(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,cAAc,OAAsC;CACnE,OAAO,SAAS,KAAK,KAAK,SAAS,MAAM,IAAI;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,aAAa,WAAqC;CACjE,OAAO,IAAI,SAAiB,SAAS,WAAW;EAC/C,MAAM,QAAQ,MAAc,aAA4B;GACvD,MAAM,QAAQ,eAAgB;GAC9B,MAAM,WAAW,UAAuB;IACvC,MAAM,MAAM;IACZ,MAAM,QAAQ,UAAU,SAAS,MAAM,SAAS;IAChD,IAAI,YAAY,OAAO,KAAK,GAAG,KAAK;SAC/B,OAAO,KAAK;GAClB;GACA,MAAM,KAAK,SAAS,OAAO;GAC3B,MAAM,OAAO,YAAY;IACxB,MAAM,UAAU,MAAM,QAAQ;IAC9B,MAAM,WAAW,cAAc,OAAO,IAAI,QAAQ,OAAO;IACzD,MAAM,YAAY,QAAQ,QAAQ,CAAC;GACpC,CAAC;EACF;EACA,KAAK,aAAa,GAAG,cAAc,KAAA,CAAS;CAC7C,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACFA,IAAa,SAAb,MAA+D;CAC9D,KAAc,OAAO,WAAW;CAChC;CACA;CACA;CACA,mBAA8C,CAAC;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAKA;CACA,SAAyB,YAAY;CACrC,UAAwB;CACxB;CACA,WAAW;CACX,WAA2B,CAAC;CAE5B,YAAY,SAAgC;EAC3C,IAAI,CAAC,WAAW,QAAQ,KAAK,GAAG,MAAM,IAAI,UAAU,wCAAwC;EAC5F,IAAI,QAAQ,WAA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,QAAQ;EAClE,OAAO,IAAI,SAAe,YAAY;GACrC,MAAM,eAAqB;IAC1B,OAAO,oBAAoB,SAAS,MAAM;IAC1C,QAAQ;GACT;GACA,KAAKM,SAAS,KAAK,MAAM;GACzB,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;EACxD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/XA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orkestrel/server",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "A typed HTTP server for the @orkestrel line — composes the @orkestrel/router dispatcher behind a managed lifecycle. Part of the @orkestrel line.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -23,18 +23,28 @@
23
23
  ],
24
24
  "type": "module",
25
25
  "sideEffects": false,
26
- "main": "./dist/src/core/index.js",
27
- "types": "./dist/src/core/index.d.ts",
26
+ "main": "./dist/src/core/index.cjs",
27
+ "module": "./dist/src/core/index.js",
28
28
  "exports": {
29
29
  ".": {
30
- "types": "./dist/src/core/index.d.ts",
31
- "import": "./dist/src/core/index.js",
32
- "default": "./dist/src/core/index.js"
30
+ "import": {
31
+ "types": "./dist/src/core/index.d.ts",
32
+ "default": "./dist/src/core/index.js"
33
+ },
34
+ "require": {
35
+ "types": "./dist/src/core/index.d.cts",
36
+ "default": "./dist/src/core/index.cjs"
37
+ }
33
38
  },
34
39
  "./server": {
35
- "types": "./dist/src/server/index.d.ts",
36
- "require": "./dist/src/server/index.cjs",
37
- "default": "./dist/src/server/index.cjs"
40
+ "import": {
41
+ "types": "./dist/src/server/index.d.ts",
42
+ "default": "./dist/src/server/index.js"
43
+ },
44
+ "require": {
45
+ "types": "./dist/src/server/index.d.cts",
46
+ "default": "./dist/src/server/index.cjs"
47
+ }
38
48
  },
39
49
  "./package.json": "./package.json"
40
50
  },
@@ -60,25 +70,27 @@
60
70
  "test:guides": "vitest run --config vite.config.ts --reporter=dot --project guides",
61
71
  "build": "npm run clean && npm run build:src",
62
72
  "build:src": "npm run build:src:core && npm run build:src:server",
63
- "build:src:core": "vite build --config configs/src/vite.core.config.ts && tsc -p configs/src/tsconfig.core.json",
64
- "build:src:server": "vite build --config configs/src/vite.server.config.ts && tsc -p configs/src/tsconfig.server.json",
65
- "prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run check && npm run build && npm test"
73
+ "build:src:core": "vite build --config configs/src/vite.core.config.ts && npm run copy dist/src/core/index.d.ts dist/src/core/index.d.cts",
74
+ "build:src:server": "vite build --config configs/src/vite.server.config.ts && npm run copy dist/src/server/index.d.ts dist/src/server/index.d.cts",
75
+ "prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run check:src && npm run build && npm test"
66
76
  },
67
77
  "dependencies": {
68
78
  "@orkestrel/abort": "^0.0.1",
69
79
  "@orkestrel/contract": "^0.0.1",
70
80
  "@orkestrel/emitter": "^0.0.1",
71
- "@orkestrel/router": "^0.0.1",
81
+ "@orkestrel/router": "^0.0.2",
72
82
  "@orkestrel/timeout": "^0.0.1"
73
83
  },
74
84
  "devDependencies": {
85
+ "@microsoft/api-extractor": "^7.58.10",
75
86
  "@orkestrel/guide": "^0.0.1",
76
87
  "@types/node": "^26.1.1",
77
88
  "@vitest/browser-playwright": "^4.1.10",
78
- "oxfmt": "^0.58.0",
79
- "oxlint": "^1.73.0",
89
+ "oxfmt": "^0.59.0",
90
+ "oxlint": "^1.74.0",
80
91
  "typescript": "^6.0.3",
81
- "vite": "^8.1.4",
92
+ "vite": "^8.1.5",
93
+ "vite-plugin-dts": "^5.0.3",
82
94
  "vitest": "^4.1.10"
83
95
  },
84
96
  "engines": {
@@ -1,32 +0,0 @@
1
- import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js';
2
- /**
3
- * The content-negotiation machine over the weighted `Accept` family — a
4
- * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
5
- * {@link NegotiatorInterface}.
6
- *
7
- * @remarks
8
- * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
9
- * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
10
- * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
11
- * rest of the substrate uses — one parser, never two. `format` reads the
12
- * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
13
- * the winner — or answers `406 Not Acceptable`.
14
- *
15
- * @example
16
- * ```ts
17
- * const negotiator = new Negotiator()
18
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
19
- * // 'text/html'
20
- * ```
21
- */
22
- export declare class Negotiator implements NegotiatorInterface {
23
- negotiate(header: string, available: readonly string[]): string | undefined;
24
- encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
25
- language(header: string, available: readonly string[]): string | undefined;
26
- /**
27
- * @remarks
28
- * Errors thrown by the negotiated handler propagate UNMODIFIED — the
29
- * server boundary classifies them, never this negotiator.
30
- */
31
- format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
32
- }
@@ -1,68 +0,0 @@
1
- import type { Encoding } from './types.js';
2
- /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
3
- export declare const DEFAULT_DRAIN_MS = 10000;
4
- /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
5
- export declare const DEFAULT_BODY_LIMIT = 1048576;
6
- /**
7
- * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
8
- * the body pipeline's byte-counting `TransformStream` enforces when
9
- * transparently decompressing a `Content-Encoding` request body.
10
- *
11
- * @remarks
12
- * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
13
- * can inflate by many orders of magnitude — a classic decompression bomb.
14
- * Capping the decompressed byte count makes the pipe ABORT the moment the
15
- * output would exceed this, BEFORE the full bomb is materialized, so the
16
- * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
17
- * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
18
- * consumer raises it via {@link import('./types.js').BodyOptions}
19
- * `decompression` for a workload that genuinely ships larger decompressed
20
- * bodies.
21
- */
22
- export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
23
- /**
24
- * The SSE response headers the `openStream` seam always sets.
25
- *
26
- * @remarks
27
- * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
28
- * keeps a proxy from caching the stream; `keep-alive` holds the connection
29
- * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
30
- * events flush promptly rather than batching. Frozen so a consumer can read
31
- * but never mutate the shared default; `openStream` merges any
32
- * {@link import('./types.js').StreamOptions.headers} UNDER these.
33
- */
34
- export declare const SSE_HEADERS: Readonly<Record<string, string>>;
35
- /**
36
- * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
37
- * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
38
- * / control-char-bearing incoming id is REJECTED (a fresh id is minted
39
- * instead) rather than ever riding into a response header or `context.state`
40
- * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
41
- * shared default.
42
- */
43
- export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
44
- /**
45
- * The set of bare `Content-Type`s `isCompressibleType` treats as
46
- * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
47
- * `+xml`) rules that helper also applies.
48
- *
49
- * @remarks
50
- * The text-shaped application types worth compressing (JSON / JavaScript /
51
- * XML / SVG / WASM / a few document formats) — NOT already-compressed
52
- * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
53
- * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
54
- * but never mutates the shared default.
55
- */
56
- export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
57
- /**
58
- * The default {@link Encoding} content-codings the substrate offers, in
59
- * PREFERENCE order — `gzip` / `deflate`.
60
- *
61
- * @remarks
62
- * `identity` (no compression) is always implicitly acceptable and is NOT
63
- * listed here — it is the fall-through when a client accepts none of these.
64
- * Brotli is omitted per the core's `CompressionStream`-only decision (see
65
- * {@link Encoding}). Frozen so a consumer can read but never mutate the
66
- * shared default.
67
- */
68
- export declare const DEFAULT_ENCODINGS: readonly Encoding[];