@orkestrel/server 0.0.1 → 0.0.2

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,121 +1,12 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
3
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
- //#endregion
5
2
  let node_net = require("node:net");
3
+ let _orkestrel_contract = require("@orkestrel/contract");
6
4
  let node_http = require("node:http");
7
5
  let _src_core = require("../core/index.cjs");
8
- Object.freeze([
9
- "null",
10
- "boolean",
11
- "object",
12
- "array",
13
- "number",
14
- "integer",
15
- "string"
16
- ]);
17
- /**
18
- * Determine whether a value is a number.
19
- *
20
- * @remarks
21
- * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.
22
- */
23
- function isNumber(value) {
24
- return typeof value === "number";
25
- }
26
- /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). */
27
- function isFiniteNumber(value) {
28
- return typeof value === "number" && Number.isFinite(value);
29
- }
30
- /** Determine whether a value is callable. */
31
- function isFunction$1(value) {
32
- return typeof value === "function";
33
- }
34
- /**
35
- * Determine whether a value is a non-null object.
36
- *
37
- * @remarks
38
- * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use
39
- * {@link isRecord} when you need a plain-record check.
40
- */
41
- function isObject(value) {
42
- return typeof value === "object" && value !== null;
43
- }
44
- /**
45
- * Determine whether a value is a plain record (object literal or null-prototype),
46
- * not an array or class instance.
47
- *
48
- * @remarks
49
- * Use instead of {@link isObject} to distinguish a plain `{}` /
50
- * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
51
- * test is realm-agnostic: rather than comparing against the current realm's
52
- * `Object.prototype` (which a plain object from another `vm.Context`, iframe,
53
- * or worker would fail), it accepts any value whose prototype is `null`, OR
54
- * whose prototype's own prototype is `null` — the shape every plain object
55
- * has in every realm, since `Object.prototype` itself always sits one step
56
- * above `null`. Arrays and class instances are still rejected: an array's
57
- * prototype chain runs through `Array.prototype` before `null`, and a class
58
- * instance's runs through the class's own prototype. The whole body runs
59
- * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
60
- * `getPrototypeOf` trap cannot escape as a thrown error.
61
- */
62
- function isRecord(value) {
63
- const outcome = attempt(() => {
64
- if (!isObject(value) || isArray(value)) return false;
65
- const prototype = Object.getPrototypeOf(value);
66
- return prototype === null || Object.getPrototypeOf(prototype) === null;
67
- });
68
- return outcome.success && outcome.value;
69
- }
70
- /** Determine whether a value is an array. */
71
- function isArray(value) {
72
- return Array.isArray(value);
73
- }
74
- /**
75
- * Invoke a callback and capture its outcome as a {@link Result}, never letting
76
- * a throw escape.
77
- *
78
- * @remarks
79
- * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
80
- * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
81
- * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
82
- * `boolean`. This converts a throwing callback into a `Failure` so the
83
- * surrounding guard can treat it as a non-match instead of propagating the
84
- * exception, written once and shared rather than copy-pasted as ad-hoc
85
- * `try`/`catch`.
86
- *
87
- * @param callback - The callback to invoke with no arguments
88
- * @returns A `Success` carrying the return value, or a `Failure` carrying the
89
- * thrown reason normalised to an `Error`
90
- *
91
- * @example
92
- * ```ts
93
- * const outcome = attempt(() => predicate(value))
94
- * return outcome.success && outcome.value
95
- * ```
96
- */
97
- function attempt(callback) {
98
- try {
99
- return {
100
- success: true,
101
- value: callback()
102
- };
103
- } catch (reason) {
104
- if (reason instanceof Error) return {
105
- success: false,
106
- error: reason
107
- };
108
- let message = "Unknown thrown value";
109
- try {
110
- message = String(reason);
111
- } catch {}
112
- return {
113
- success: false,
114
- error: new Error(message)
115
- };
116
- }
117
- }
118
- //#endregion
6
+ let _orkestrel_abort = require("@orkestrel/abort");
7
+ let _orkestrel_timeout = require("@orkestrel/timeout");
8
+ let _orkestrel_router_server = require("@orkestrel/router/server");
9
+ let _orkestrel_emitter = require("@orkestrel/emitter");
119
10
  //#region src/server/helpers.ts
120
11
  /**
121
12
  * Whether a `node:net` `server.address()` return is the structured
@@ -135,7 +26,7 @@ function attempt(callback) {
135
26
  * ```
136
27
  */
137
28
  function isAddressInfo(value) {
138
- return isRecord(value) && isNumber(value.port);
29
+ return (0, _orkestrel_contract.isRecord)(value) && (0, _orkestrel_contract.isNumber)(value.port);
139
30
  }
140
31
  /**
141
32
  * Find a FREE TCP port — bind a throwaway `node:net` server, read the
@@ -183,837 +74,6 @@ function discoverPort(preferred) {
183
74
  });
184
75
  }
185
76
  //#endregion
186
- //#region node_modules/@orkestrel/abort/dist/src/core/index.js
187
- /**
188
- * Link an own `AbortSignal` to an optional parent signal.
189
- *
190
- * @remarks
191
- * When `parent` is `undefined`, the own signal is returned unchanged. When a
192
- * parent is given, the result is `AbortSignal.any([own, parent])`, which fires
193
- * on EITHER the own signal aborting or the parent aborting — without
194
- * re-implementing listener wiring. A parent that has ALREADY aborted makes the
195
- * combined signal born aborted (carrying the parent's reason).
196
- *
197
- * @param own - The instance's own signal.
198
- * @param parent - An optional parent signal to link against.
199
- * @returns `own` unchanged when `parent` is `undefined`, otherwise
200
- * `AbortSignal.any([own, parent])`.
201
- *
202
- * @example
203
- * ```ts
204
- * import { linkSignal } from '@src/core'
205
- *
206
- * const controller = new AbortController()
207
- * const linked = linkSignal(controller.signal, undefined) // controller.signal
208
- * ```
209
- */
210
- function linkSignal(own, parent) {
211
- return parent === void 0 ? own : AbortSignal.any([own, parent]);
212
- }
213
- Object.freeze([
214
- "null",
215
- "boolean",
216
- "object",
217
- "array",
218
- "number",
219
- "integer",
220
- "string"
221
- ]);
222
- /** Determine whether a value is a string. */
223
- function isString$1(value) {
224
- return typeof value === "string";
225
- }
226
- /**
227
- * A cancellation handle — a thin, traceable wrapper over a native
228
- * `AbortController` whose exposed `signal` can be linked to a parent signal.
229
- *
230
- * @remarks
231
- * - **Own controller.** The instance owns a private `AbortController`; `abort`
232
- * aborts it, and `aborted` reads the exposed signal. `abort(reason)` keeps any
233
- * DEFINED reason verbatim (including a falsy `null` / `0` / `''` / `false`);
234
- * `abort()` / `abort(undefined)` defaults `signal.reason` to an `AbortError`
235
- * `DOMException`. Aborting is idempotent — the first reason sticks.
236
- * - **Parent linking.** When `options.signal` is given, the exposed `signal` is
237
- * `AbortSignal.any([own, parent])`, so it fires on EITHER the own `abort()` or
238
- * the parent aborting — without re-implementing listener wiring. A parent that
239
- * has ALREADY aborted makes the handle born aborted (carrying the parent's reason).
240
- * - **Traceable.** Each handle carries an `id` (caller-supplied or a random UUID)
241
- * for correlating cancellations across the system.
242
- * - **Event-free.** A pure functional primitive — no Emitter, no events.
243
- *
244
- * @example
245
- * ```ts
246
- * const abort = new Abort()
247
- * abort.signal.addEventListener('abort', () => stop(), { once: true })
248
- * abort.abort('cancelled') // flips `aborted`, fires `signal` with the reason
249
- * ```
250
- */
251
- var Abort = class {
252
- #controller = new AbortController();
253
- id;
254
- signal;
255
- constructor(options) {
256
- this.id = isString$1(options?.id) ? options.id : crypto.randomUUID();
257
- this.signal = linkSignal(this.#controller.signal, options?.signal);
258
- }
259
- get aborted() {
260
- return this.signal.aborted;
261
- }
262
- abort(reason) {
263
- this.#controller.abort(reason);
264
- }
265
- };
266
- /**
267
- * Create a cancellation handle — a thin, traceable wrapper over a native
268
- * `AbortController` whose `signal` can be linked to a parent signal.
269
- *
270
- * @remarks
271
- * The created handle's `signal` fires when its own `abort()` is called; when
272
- * `options.signal` is given, it ALSO fires when that parent signal aborts (linked
273
- * via `AbortSignal.any`). Pass `options.id` to label the handle for tracing, or
274
- * let it default to a random UUID.
275
- *
276
- * @param options - Optional `id` (a trace label; defaults to a random UUID) and
277
- * `signal` (a parent signal whose abort also fires the created handle's signal)
278
- * @returns A working {@link AbortInterface}
279
- *
280
- * @example
281
- * ```ts
282
- * import { createAbort } from '@src/core'
283
- *
284
- * const abort = createAbort()
285
- * const work = fetch(url, { signal: abort.signal })
286
- * abort.abort() // cancels the fetch via the linked native signal
287
- * ```
288
- *
289
- * @example
290
- * ```ts
291
- * // Link to a parent so a parent cancellation also aborts the child.
292
- * const parent = createAbort()
293
- * const child = createAbort({ signal: parent.signal })
294
- * parent.abort() // child.aborted is now true
295
- * ```
296
- */
297
- function createAbort(options) {
298
- return new Abort(options);
299
- }
300
- //#endregion
301
- //#region node_modules/@orkestrel/timeout/dist/src/core/index.js
302
- Object.freeze([
303
- "null",
304
- "boolean",
305
- "object",
306
- "array",
307
- "number",
308
- "integer",
309
- "string"
310
- ]);
311
- /** Determine whether a value is a string. */
312
- function isString(value) {
313
- return typeof value === "string";
314
- }
315
- /**
316
- * A deadline handle — a controllable `setTimeout` wrapper that exposes an
317
- * `AbortSignal` which fires when the timeout expires, for racing against work.
318
- *
319
- * @remarks
320
- * - **Deadline signal.** `start()` arms a `setTimeout` for `ms`; on expiry it
321
- * flips `expired` and aborts the controller, firing `signal`. Race `signal`
322
- * against work to bound how long it may run.
323
- * - **Controllable.** `clear()` cancels a pending expiry WITHOUT firing `signal`,
324
- * and resets `expired` back to `false` (the §10 reset) — a cleared timeout
325
- * reports `expired === false` and a non-aborted `signal`.
326
- * - **Reusable.** Re-`start()` after an expiry swaps in a fresh controller and
327
- * resets `expired`, so `signal` / `expired` reflect the new run — the handle is
328
- * reusable across deadlines without re-construction.
329
- * - **Parent linking.** A parent `signal` does NOT expire this timeout — it
330
- * CLEARS it: the parent listener is attached only while a timer is armed (added
331
- * on `start()`, removed on expiry or `clear()`), so a parent abort during the
332
- * timing window cancels the pending expiry and a later `start()` is a no-op once
333
- * the parent has aborted. An idle handle holds no parent listener.
334
- * - **Event-free.** A pure functional primitive — no Emitter, no events.
335
- *
336
- * @example
337
- * ```ts
338
- * const timeout = new Timeout({ ms: 5_000 })
339
- * timeout.start()
340
- * timeout.signal.addEventListener('abort', () => giveUp(), { once: true })
341
- * timeout.clear() // cancels the deadline before it fires
342
- * ```
343
- */
344
- var Timeout = class {
345
- id;
346
- ms;
347
- #parent;
348
- #controller = new AbortController();
349
- #handle;
350
- #listener;
351
- #expired = false;
352
- constructor(options) {
353
- this.id = isString(options.id) ? options.id : crypto.randomUUID();
354
- this.ms = options.ms;
355
- this.#parent = options.signal;
356
- }
357
- get signal() {
358
- return this.#controller.signal;
359
- }
360
- get expired() {
361
- return this.#expired;
362
- }
363
- start() {
364
- if (this.#parent?.aborted === true) return;
365
- if (this.#handle !== void 0) {
366
- clearTimeout(this.#handle);
367
- this.#handle = void 0;
368
- }
369
- this.#detach();
370
- this.#expired = false;
371
- if (this.#controller.signal.aborted) this.#controller = new AbortController();
372
- const listener = () => this.clear();
373
- this.#listener = listener;
374
- this.#parent?.addEventListener("abort", listener, { once: true });
375
- this.#handle = setTimeout(() => {
376
- this.#handle = void 0;
377
- this.#expired = true;
378
- this.#controller.abort();
379
- this.#detach();
380
- }, this.ms);
381
- }
382
- clear() {
383
- if (this.#handle !== void 0) {
384
- clearTimeout(this.#handle);
385
- this.#handle = void 0;
386
- }
387
- this.#detach();
388
- this.#expired = false;
389
- if (this.#controller.signal.aborted) this.#controller = new AbortController();
390
- }
391
- #detach() {
392
- if (this.#listener !== void 0) {
393
- this.#parent?.removeEventListener("abort", this.#listener);
394
- this.#listener = void 0;
395
- }
396
- }
397
- };
398
- /**
399
- * Create a deadline handle — a controllable `setTimeout` wrapper that exposes an
400
- * `AbortSignal` which fires when the timeout expires, for racing against work.
401
- *
402
- * @remarks
403
- * Call `start()` to arm the deadline for `ms` milliseconds; on expiry the handle's
404
- * `signal` fires and `expired` flips `true`. Call `clear()` to cancel a pending
405
- * deadline without firing. When `options.signal` is given, a parent abort CLEARS
406
- * the timeout (it never expires) rather than firing it. Pass `options.id` to label
407
- * the handle for tracing, or let it default to a random UUID. `ms` must be a
408
- * non-negative finite number; the host `setTimeout` clamps a negative or `NaN`
409
- * value to roughly `0` (firing on the next macrotask) rather than throwing.
410
- *
411
- * @param options - `ms` (the deadline in milliseconds, a non-negative finite
412
- * number), an optional `id` (a trace label; defaults to a random UUID), and an
413
- * optional parent `signal` whose abort clears the timeout
414
- * @returns A working {@link TimeoutInterface}
415
- *
416
- * @example
417
- * ```ts
418
- * import { createTimeout } from '@src/core'
419
- *
420
- * const timeout = createTimeout({ ms: 5_000 })
421
- * timeout.start()
422
- * const result = await Promise.race([
423
- * work(),
424
- * new Promise((_, reject) =>
425
- * timeout.signal.addEventListener('abort', () => reject(new Error('timed out')), {
426
- * once: true,
427
- * }),
428
- * ),
429
- * ])
430
- * timeout.clear() // work finished first — cancel the deadline
431
- * ```
432
- */
433
- function createTimeout(options) {
434
- return new Timeout(options);
435
- }
436
- //#endregion
437
- //#region node_modules/@orkestrel/emitter/dist/src/core/index.js
438
- var import_server = (/* @__PURE__ */ __commonJSMin(((exports) => {
439
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
440
- /**
441
- * Link an own `AbortSignal` to an optional parent signal.
442
- *
443
- * @remarks
444
- * When `parent` is `undefined`, the own signal is returned unchanged. When a
445
- * parent is given, the result is `AbortSignal.any([own, parent])`, which fires
446
- * on EITHER the own signal aborting or the parent aborting — without
447
- * re-implementing listener wiring. A parent that has ALREADY aborted makes the
448
- * combined signal born aborted (carrying the parent's reason).
449
- *
450
- * @param own - The instance's own signal.
451
- * @param parent - An optional parent signal to link against.
452
- * @returns `own` unchanged when `parent` is `undefined`, otherwise
453
- * `AbortSignal.any([own, parent])`.
454
- *
455
- * @example
456
- * ```ts
457
- * import { linkSignal } from '@src/core'
458
- *
459
- * const controller = new AbortController()
460
- * const linked = linkSignal(controller.signal, undefined) // controller.signal
461
- * ```
462
- */
463
- function linkSignal(own, parent) {
464
- return parent === void 0 ? own : AbortSignal.any([own, parent]);
465
- }
466
- Object.freeze([
467
- "null",
468
- "boolean",
469
- "object",
470
- "array",
471
- "number",
472
- "integer",
473
- "string"
474
- ]);
475
- /** Determine whether a value is a string. */
476
- function isString(value) {
477
- return typeof value === "string";
478
- }
479
- /**
480
- * A cancellation handle — a thin, traceable wrapper over a native
481
- * `AbortController` whose exposed `signal` can be linked to a parent signal.
482
- *
483
- * @remarks
484
- * - **Own controller.** The instance owns a private `AbortController`; `abort`
485
- * aborts it, and `aborted` reads the exposed signal. `abort(reason)` keeps any
486
- * DEFINED reason verbatim (including a falsy `null` / `0` / `''` / `false`);
487
- * `abort()` / `abort(undefined)` defaults `signal.reason` to an `AbortError`
488
- * `DOMException`. Aborting is idempotent — the first reason sticks.
489
- * - **Parent linking.** When `options.signal` is given, the exposed `signal` is
490
- * `AbortSignal.any([own, parent])`, so it fires on EITHER the own `abort()` or
491
- * the parent aborting — without re-implementing listener wiring. A parent that
492
- * has ALREADY aborted makes the handle born aborted (carrying the parent's reason).
493
- * - **Traceable.** Each handle carries an `id` (caller-supplied or a random UUID)
494
- * for correlating cancellations across the system.
495
- * - **Event-free.** A pure functional primitive — no Emitter, no events.
496
- *
497
- * @example
498
- * ```ts
499
- * const abort = new Abort()
500
- * abort.signal.addEventListener('abort', () => stop(), { once: true })
501
- * abort.abort('cancelled') // flips `aborted`, fires `signal` with the reason
502
- * ```
503
- */
504
- var Abort = class {
505
- #controller = new AbortController();
506
- id;
507
- signal;
508
- constructor(options) {
509
- this.id = isString(options?.id) ? options.id : crypto.randomUUID();
510
- this.signal = linkSignal(this.#controller.signal, options?.signal);
511
- }
512
- get aborted() {
513
- return this.signal.aborted;
514
- }
515
- abort(reason) {
516
- this.#controller.abort(reason);
517
- }
518
- };
519
- /**
520
- * Create a cancellation handle — a thin, traceable wrapper over a native
521
- * `AbortController` whose `signal` can be linked to a parent signal.
522
- *
523
- * @remarks
524
- * The created handle's `signal` fires when its own `abort()` is called; when
525
- * `options.signal` is given, it ALSO fires when that parent signal aborts (linked
526
- * via `AbortSignal.any`). Pass `options.id` to label the handle for tracing, or
527
- * let it default to a random UUID.
528
- *
529
- * @param options - Optional `id` (a trace label; defaults to a random UUID) and
530
- * `signal` (a parent signal whose abort also fires the created handle's signal)
531
- * @returns A working {@link AbortInterface}
532
- *
533
- * @example
534
- * ```ts
535
- * import { createAbort } from '@src/core'
536
- *
537
- * const abort = createAbort()
538
- * const work = fetch(url, { signal: abort.signal })
539
- * abort.abort() // cancels the fetch via the linked native signal
540
- * ```
541
- *
542
- * @example
543
- * ```ts
544
- * // Link to a parent so a parent cancellation also aborts the child.
545
- * const parent = createAbort()
546
- * const child = createAbort({ signal: parent.signal })
547
- * parent.abort() // child.aborted is now true
548
- * ```
549
- */
550
- function createAbort(options) {
551
- return new Abort(options);
552
- }
553
- Object.freeze([
554
- "null",
555
- "boolean",
556
- "object",
557
- "array",
558
- "number",
559
- "integer",
560
- "string"
561
- ]);
562
- /**
563
- * Determine whether a value is a non-null object.
564
- *
565
- * @remarks
566
- * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use
567
- * {@link isRecord} when you need a plain-record check.
568
- */
569
- function isObject(value) {
570
- return typeof value === "object" && value !== null;
571
- }
572
- /**
573
- * Determine whether a value is a plain record (object literal or null-prototype),
574
- * not an array or class instance.
575
- *
576
- * @remarks
577
- * Use instead of {@link isObject} to distinguish a plain `{}` /
578
- * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
579
- * test is realm-agnostic: rather than comparing against the current realm's
580
- * `Object.prototype` (which a plain object from another `vm.Context`, iframe,
581
- * or worker would fail), it accepts any value whose prototype is `null`, OR
582
- * whose prototype's own prototype is `null` — the shape every plain object
583
- * has in every realm, since `Object.prototype` itself always sits one step
584
- * above `null`. Arrays and class instances are still rejected: an array's
585
- * prototype chain runs through `Array.prototype` before `null`, and a class
586
- * instance's runs through the class's own prototype. The whole body runs
587
- * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
588
- * `getPrototypeOf` trap cannot escape as a thrown error.
589
- */
590
- function isRecord(value) {
591
- const outcome = attempt(() => {
592
- if (!isObject(value) || isArray(value)) return false;
593
- const prototype = Object.getPrototypeOf(value);
594
- return prototype === null || Object.getPrototypeOf(prototype) === null;
595
- });
596
- return outcome.success && outcome.value;
597
- }
598
- /** Determine whether a value is an array. */
599
- function isArray(value) {
600
- return Array.isArray(value);
601
- }
602
- /**
603
- * Invoke a callback and capture its outcome as a {@link Result}, never letting
604
- * a throw escape.
605
- *
606
- * @remarks
607
- * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
608
- * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
609
- * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
610
- * `boolean`. This converts a throwing callback into a `Failure` so the
611
- * surrounding guard can treat it as a non-match instead of propagating the
612
- * exception, written once and shared rather than copy-pasted as ad-hoc
613
- * `try`/`catch`.
614
- *
615
- * @param callback - The callback to invoke with no arguments
616
- * @returns A `Success` carrying the return value, or a `Failure` carrying the
617
- * thrown reason normalised to an `Error`
618
- *
619
- * @example
620
- * ```ts
621
- * const outcome = attempt(() => predicate(value))
622
- * return outcome.success && outcome.value
623
- * ```
624
- */
625
- function attempt(callback) {
626
- try {
627
- return {
628
- success: true,
629
- value: callback()
630
- };
631
- } catch (reason) {
632
- if (reason instanceof Error) return {
633
- success: false,
634
- error: reason
635
- };
636
- let message = "Unknown thrown value";
637
- try {
638
- message = String(reason);
639
- } catch {}
640
- return {
641
- success: false,
642
- error: new Error(message)
643
- };
644
- }
645
- }
646
- /**
647
- * Determine whether a `node:http` connection socket is TLS-encrypted — the
648
- * total, never-throwing narrow (AGENTS §14) `buildRequest` uses to pick the
649
- * derived scheme (`https` vs `http`).
650
- *
651
- * @param socket - The connection value to test (typically `message.socket`)
652
- * @returns `true` when `socket` carries a truthy `encrypted` property (a
653
- * `tls.TLSSocket`), `false` for anything else (including `undefined`)
654
- *
655
- * @example
656
- * ```ts
657
- * import { isEncryptedSocket } from '@src/server'
658
- *
659
- * isEncryptedSocket({ encrypted: true }) // true
660
- * isEncryptedSocket({}) // false
661
- * ```
662
- */
663
- function isEncryptedSocket(socket) {
664
- return isRecord(socket) && socket.encrypted === true;
665
- }
666
- /**
667
- * Build a fetch-standard `Request` from a `node:http` `IncomingMessage` — the
668
- * server-adapter half of the §5.3 conversion seam.
669
- *
670
- * @remarks
671
- * - `method` is carried over verbatim (defaulting to `GET` when absent).
672
- * - The URL is built against `options.origin` when given, otherwise a scheme
673
- * derived from the connection (`https` when {@link isEncryptedSocket}, else
674
- * `http`) plus the `Host` header (absent `Host` ⇒ `localhost`).
675
- * - Every request header is copied; multi-value headers are joined per fetch
676
- * semantics (`', '`-joined), except `set-cookie`, whose values are each
677
- * appended individually (fetch `Headers` preserves multiple `set-cookie`
678
- * entries distinctly).
679
- * - For a method that carries a body (anything but `GET`/`HEAD`), the message
680
- * is pumped chunk by chunk into a DOM-compatible `ReadableStream<Uint8Array>`
681
- * (reconciling the DOM + node type worlds under the root config), with
682
- * `duplex: 'half'` set as Node's fetch implementation requires for a
683
- * streamed request body.
684
- * - A fresh `@orkestrel/abort` handle backs `request.signal`: if the
685
- * connection closes before the message finished (`!message.complete`), the
686
- * handle aborts — so a handler awaiting `request.signal` observes a client
687
- * disconnect the fetch-standard way, with zero router-specific API.
688
- *
689
- * @param message - The raw `node:http` request
690
- * @param options - Optional `origin` override (§5.3 {@link RequestOptions})
691
- * @returns A fetch `Request` whose `signal` fires on client disconnect
692
- *
693
- * @example
694
- * ```ts
695
- * import { buildRequest } from '@src/server'
696
- * import http from 'node:http'
697
- *
698
- * const server = http.createServer((incoming) => {
699
- * const request = buildRequest(incoming)
700
- * console.log(request.method, request.url)
701
- * })
702
- * ```
703
- */
704
- function buildRequest(message, options) {
705
- const method = message.method ?? "GET";
706
- const host = message.headers.host ?? "localhost";
707
- const scheme = isEncryptedSocket(message.socket) ? "https" : "http";
708
- const origin = options?.origin ?? `${scheme}://${host}`;
709
- const url = new URL(message.url ?? "/", origin);
710
- const headers = new Headers();
711
- for (const [name, value] of Object.entries(message.headers)) {
712
- if (value === void 0) continue;
713
- if (name === "set-cookie") {
714
- for (const cookie of Array.isArray(value) ? value : [value]) headers.append(name, cookie);
715
- continue;
716
- }
717
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
718
- }
719
- const abort = createAbort();
720
- message.once("close", () => {
721
- if (!message.complete) abort.abort(/* @__PURE__ */ new Error(`request to ${url.pathname} disconnected before completion`));
722
- });
723
- const carriesBody = method !== "GET" && method !== "HEAD";
724
- const init = {
725
- method,
726
- headers,
727
- signal: abort.signal
728
- };
729
- if (!carriesBody) return new Request(url, init);
730
- const body = new ReadableStream({ async start(controller) {
731
- try {
732
- for await (const chunk of message) controller.enqueue(chunk);
733
- controller.close();
734
- } catch (error) {
735
- controller.error(error);
736
- }
737
- } });
738
- const streamed = {
739
- ...init,
740
- body,
741
- duplex: "half"
742
- };
743
- return new Request(url, streamed);
744
- }
745
- /**
746
- * Write a fetch-standard `Response` back to a `node:http` `ServerResponse` —
747
- * the reverse half of the §5.3 conversion seam.
748
- *
749
- * @remarks
750
- * Writes `status`/`statusText`, then every response header (`set-cookie`
751
- * written via {@link Headers.getSetCookie} so multiple cookies stay distinct
752
- * instead of collapsing into one comma-joined header), then streams the web
753
- * body to `target` chunk by chunk (`for await` over `response.body`), ending
754
- * `target` when the stream completes. A `null` body ends `target` immediately
755
- * with no further writes. Total error posture: if `target` is destroyed
756
- * mid-stream (the client disconnected), the write loop stops and `target` is
757
- * left as-is rather than throwing an unhandled rejection — a destroyed
758
- * target is not this function's error to surface.
759
- *
760
- * @param response - The fetch `Response` to write
761
- * @param target - The `node:http` response to write it to
762
- * @returns A promise that resolves once `target` has been ended (or the
763
- * stream stopped because `target` was destroyed)
764
- *
765
- * @example
766
- * ```ts
767
- * import { sendResponse } from '@src/server'
768
- * import http from 'node:http'
769
- *
770
- * const server = http.createServer(async (_incoming, target) => {
771
- * await sendResponse(new Response('ok'), target)
772
- * })
773
- * ```
774
- */
775
- async function sendResponse(response, target) {
776
- target.statusCode = response.status;
777
- target.statusMessage = response.statusText;
778
- for (const [name, value] of response.headers) {
779
- if (name === "set-cookie") continue;
780
- target.setHeader(name, value);
781
- }
782
- const cookies = response.headers.getSetCookie();
783
- if (cookies.length > 0) target.setHeader("set-cookie", cookies);
784
- if (response.body === null) {
785
- if (!target.destroyed) target.end();
786
- return;
787
- }
788
- try {
789
- for await (const chunk of response.body) {
790
- if (target.destroyed) return;
791
- target.write(chunk);
792
- }
793
- if (!target.destroyed) target.end();
794
- } catch {
795
- if (!target.destroyed) target.end();
796
- }
797
- }
798
- /**
799
- * Create a `node:http` request listener over a core {@link DispatcherInterface} —
800
- * the whole server face's entry point (§5.3): convert the incoming message to
801
- * a fetch `Request`, hand it to the dispatcher with the consumer's per-request
802
- * `state`, and write the resulting `Response` back.
803
- *
804
- * @remarks
805
- * A rejected `dispatcher.handle` (a route handler throw — the dispatcher
806
- * never invents an error boundary, §5.1) is this listener's transport-level
807
- * LAST RESORT, distinct from an application error boundary: when nothing has
808
- * been sent yet, it destroys the connection with a bare `500` head (never
809
- * leaking a hanging socket); once headers are already sent, it destroys the
810
- * connection outright. The router still owns no error POLICY — a consumer
811
- * that wants mapped error responses installs its own boundary around
812
- * `dispatcher.handle` (the future `@orkestrel/server` seam, §7).
813
- *
814
- * @typeParam TState - The consumer's opaque per-request state type
815
- * @param dispatcher - The core dispatcher to run each converted request through
816
- * @param state - Derives the consumer's per-request `state` from the raw message
817
- * @returns A `(request, response) => void` listener, passable directly to
818
- * `http.createServer`
819
- *
820
- * @example
821
- * ```ts
822
- * import { createListener } from '@src/server'
823
- * import { createDispatcher } from '@src/core'
824
- * import http from 'node:http'
825
- *
826
- * const dispatcher = createDispatcher()
827
- * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
828
- * http.createServer(createListener(dispatcher, () => undefined)).listen(0)
829
- * ```
830
- */
831
- function createListener(dispatcher, state) {
832
- return (request, response) => {
833
- (async () => {
834
- try {
835
- const converted = buildRequest(request);
836
- await sendResponse(await dispatcher.handle(converted, state(request)), response);
837
- } catch (error) {
838
- if (!response.headersSent && !response.destroyed) {
839
- response.writeHead(500);
840
- response.end();
841
- } else if (!response.destroyed) response.destroy(error instanceof Error ? error : new Error(String(error)));
842
- }
843
- })();
844
- };
845
- }
846
- exports.buildRequest = buildRequest;
847
- exports.createListener = createListener;
848
- exports.isEncryptedSocket = isEncryptedSocket;
849
- exports.sendResponse = sendResponse;
850
- })))();
851
- /**
852
- * Extract the own enumerable keys of a mapped object, typed as its key union.
853
- *
854
- * @remarks
855
- * `Object.keys` widens its result to `string[]`, which breaks the key↔value
856
- * correlation a mapped type (like `EmitterHooks<TMap>`) otherwise guarantees.
857
- * A `for…in` push into a `keyof`-typed array narrows the result back,
858
- * type-safely and with no assertion.
859
- *
860
- * @typeParam T - The object shape whose keys are extracted.
861
- * @param object - The object to read keys from.
862
- * @returns The object's own enumerable keys, typed as `(keyof T)[]`.
863
- *
864
- * @example
865
- * ```ts
866
- * import { extractKeys } from '@src/core'
867
- *
868
- * const hooks = { tick: () => {}, done: () => {} }
869
- * extractKeys(hooks) // ['tick', 'done']
870
- * extractKeys({}) // []
871
- * ```
872
- */
873
- function extractKeys(object) {
874
- const collected = [];
875
- for (const key in object) collected.push(key);
876
- return collected;
877
- }
878
- Object.freeze([
879
- "null",
880
- "boolean",
881
- "object",
882
- "array",
883
- "number",
884
- "integer",
885
- "string"
886
- ]);
887
- /** Determine whether a value is callable. */
888
- function isFunction(value) {
889
- return typeof value === "function";
890
- }
891
- /**
892
- * A typed synchronous event emitter — the foundational observable primitive of
893
- * the codebase (AGENTS §13). Stateful entities OWN one as a `#emitter` field and
894
- * expose it through `readonly emitter`; they never inherit from it.
895
- *
896
- * @typeParam TMap - The event map: each event name to the argument tuple its
897
- * listeners receive.
898
- *
899
- * @remarks
900
- * - **Synchronous.** `emit` invokes listeners in registration order, in the
901
- * current tick.
902
- * - **Listener isolation.** A throwing listener never stops its siblings: every
903
- * listener runs, and a throw is routed to the `error` handler
904
- * ({@link EmitterOptions.error}) — never rethrown. Every throwing listener
905
- * surfaces (not just the first), and with no `error` handler a throw is swallowed
906
- * silently. The `error` handler runs inside its own try/catch, so a throwing
907
- * error-handler is swallowed too (anti-recursion — it cannot escape or re-enter).
908
- * - **Per-event storage.** Listeners live in a per-event `Set`, so every public
909
- * method is precisely typed with no assertions.
910
- * - **Destroyed → no-op.** After `destroy()`, `on` / `once` / `emit` do nothing
911
- * and `destroyed` is `true`.
912
- *
913
- * @example
914
- * ```ts
915
- * type CounterEventMap = {
916
- * tick: readonly [count: number]
917
- * done: readonly []
918
- * }
919
- *
920
- * const emitter = new Emitter<CounterEventMap>({
921
- * on: { done: () => stop() },
922
- * error: (error, event) => log(`listener for ${event} threw`, error),
923
- * })
924
- * emitter.on('tick', (count) => render(count))
925
- * emitter.emit('tick', 1)
926
- * ```
927
- */
928
- var Emitter = class {
929
- #destroyed = false;
930
- #listeners = {};
931
- #wrappers = {};
932
- #error;
933
- constructor(options) {
934
- const error = options?.error;
935
- this.#error = isFunction(error) ? error : void 0;
936
- const hooks = options?.on;
937
- if (hooks !== void 0) this.#wire(hooks);
938
- }
939
- get destroyed() {
940
- return this.#destroyed;
941
- }
942
- on(event, handler) {
943
- if (this.#destroyed) return;
944
- (this.#listeners[event] ??= /* @__PURE__ */ new Set()).add(handler);
945
- }
946
- once(event, handler) {
947
- if (this.#destroyed) return;
948
- const pending = this.#wrappers[event] ??= /* @__PURE__ */ new Map();
949
- const wrapper = (...args) => {
950
- this.#listeners[event]?.delete(wrapper);
951
- const wrappers = pending.get(handler);
952
- wrappers?.delete(wrapper);
953
- if (wrappers !== void 0 && wrappers.size === 0) pending.delete(handler);
954
- handler(...args);
955
- };
956
- const wrappers = pending.get(handler) ?? /* @__PURE__ */ new Set();
957
- wrappers.add(wrapper);
958
- pending.set(handler, wrappers);
959
- this.on(event, wrapper);
960
- }
961
- off(event, handler) {
962
- const listeners = this.#listeners[event];
963
- const wrappers = this.#wrappers[event];
964
- const pending = wrappers?.get(handler);
965
- if (pending !== void 0) {
966
- for (const wrapper of pending) listeners?.delete(wrapper);
967
- wrappers?.delete(handler);
968
- }
969
- listeners?.delete(handler);
970
- }
971
- emit(event, ...args) {
972
- if (this.#destroyed) return;
973
- const listeners = this.#listeners[event];
974
- if (listeners === void 0) return;
975
- for (const handler of [...listeners]) try {
976
- handler(...args);
977
- } catch (error) {
978
- this.#surface(error, event);
979
- }
980
- }
981
- count(event) {
982
- if (event !== void 0) return this.#listeners[event]?.size ?? 0;
983
- let total = 0;
984
- for (const set of Object.values(this.#listeners)) total += set?.size ?? 0;
985
- return total;
986
- }
987
- clear(event) {
988
- if (event !== void 0) {
989
- delete this.#listeners[event];
990
- delete this.#wrappers[event];
991
- return;
992
- }
993
- this.#listeners = {};
994
- this.#wrappers = {};
995
- }
996
- destroy() {
997
- this.#listeners = {};
998
- this.#wrappers = {};
999
- this.#error = void 0;
1000
- this.#destroyed = true;
1001
- }
1002
- #surface(error, event) {
1003
- const handler = this.#error;
1004
- if (handler === void 0) return;
1005
- try {
1006
- handler(error, String(event));
1007
- } catch {}
1008
- }
1009
- #wire(hooks) {
1010
- for (const event of extractKeys(hooks)) {
1011
- const handler = hooks[event];
1012
- if (isFunction(handler)) this.on(event, handler);
1013
- }
1014
- }
1015
- };
1016
- //#endregion
1017
77
  //#region src/server/Server.ts
1018
78
  /**
1019
79
  * The HTTP server facade — an observable `node:http` lifecycle composing the
@@ -1074,20 +134,20 @@ var Server = class {
1074
134
  #report;
1075
135
  #timeouts;
1076
136
  #http;
1077
- #abort = createAbort();
137
+ #abort = (0, _orkestrel_abort.createAbort)();
1078
138
  #status = "idle";
1079
139
  #port;
1080
140
  #pending = 0;
1081
141
  #waiters = [];
1082
142
  constructor(options) {
1083
- if (!isFunction$1(options.state)) throw new TypeError("ServerOptions.state must be a function");
1084
- if (options.report !== void 0 && !isFunction$1(options.report)) throw new TypeError("ServerOptions.report must be a function");
143
+ if (!(0, _orkestrel_contract.isFunction)(options.state)) throw new TypeError("ServerOptions.state must be a function");
144
+ if (options.report !== void 0 && !(0, _orkestrel_contract.isFunction)(options.report)) throw new TypeError("ServerOptions.report must be a function");
1085
145
  const drain = options.drain ?? _src_core.DEFAULT_DRAIN_MS;
1086
- if (!isFiniteNumber(drain) || drain < 0) throw new TypeError("ServerOptions.drain must be a non-negative finite number");
146
+ if (!(0, _orkestrel_contract.isFiniteNumber)(drain) || drain < 0) throw new TypeError("ServerOptions.drain must be a non-negative finite number");
1087
147
  const limit = options.limit ?? _src_core.DEFAULT_BODY_LIMIT;
1088
- if (!isFiniteNumber(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
148
+ if (!(0, _orkestrel_contract.isFiniteNumber)(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
1089
149
  const timeouts = options.timeouts ?? {};
1090
- 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
+ for (const [name, value] of Object.entries(timeouts)) if (value !== void 0 && (!(0, _orkestrel_contract.isFiniteNumber)(value) || value < 0)) throw new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`);
1091
151
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1092
152
  this.#dispatcher = options.dispatcher;
1093
153
  this.#state = options.state;
@@ -1099,7 +159,7 @@ var Server = class {
1099
159
  this.#expose = options.expose ?? false;
1100
160
  this.#report = options.report;
1101
161
  this.#timeouts = timeouts;
1102
- this.#emitter = new Emitter({
162
+ this.#emitter = new _orkestrel_emitter.Emitter({
1103
163
  on: options.on,
1104
164
  error: options.error
1105
165
  });
@@ -1126,7 +186,7 @@ var Server = class {
1126
186
  start() {
1127
187
  if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1128
188
  this.#status = "starting";
1129
- this.#abort = createAbort();
189
+ this.#abort = (0, _orkestrel_abort.createAbort)();
1130
190
  const server = (0, node_http.createServer)((request, response) => this.#handle(request, response));
1131
191
  if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
1132
192
  if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
@@ -1159,7 +219,7 @@ var Server = class {
1159
219
  this.#emitter.emit("stop");
1160
220
  const server = this.#http;
1161
221
  this.#abort.abort();
1162
- const deadline = createTimeout({ ms: this.#drain });
222
+ const deadline = (0, _orkestrel_timeout.createTimeout)({ ms: this.#drain });
1163
223
  deadline.start();
1164
224
  await this.#drainPending(deadline.signal);
1165
225
  deadline.clear();
@@ -1192,19 +252,19 @@ var Server = class {
1192
252
  async #accept(message, response) {
1193
253
  let raw;
1194
254
  try {
1195
- raw = (0, import_server.buildRequest)(message);
255
+ raw = (0, _orkestrel_router_server.buildRequest)(message);
1196
256
  } catch {
1197
257
  await this.#respond(this.#boundary(new _src_core.HTTPError(400, "invalid request")), response);
1198
258
  return;
1199
259
  }
1200
260
  try {
1201
- const linked = linkSignal(raw.signal, this.#abort.signal);
261
+ const linked = (0, _orkestrel_abort.linkSignal)(raw.signal, this.#abort.signal);
1202
262
  const request = new Request(raw, { signal: linked });
1203
263
  const url = new URL(request.url);
1204
264
  this.#emitter.emit("request", request.method, url.pathname);
1205
265
  const connection = {
1206
266
  ip: message.socket.remoteAddress,
1207
- encrypted: (0, import_server.isEncryptedSocket)(message.socket)
267
+ encrypted: (0, _orkestrel_router_server.isEncryptedSocket)(message.socket)
1208
268
  };
1209
269
  let cached;
1210
270
  const context = {
@@ -1231,7 +291,7 @@ var Server = class {
1231
291
  }
1232
292
  async #respond(result, response) {
1233
293
  try {
1234
- await (0, import_server.sendResponse)(result, response);
294
+ await (0, _orkestrel_router_server.sendResponse)(result, response);
1235
295
  } catch {
1236
296
  response.destroy();
1237
297
  }