@orkestrel/server 0.0.1
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.
- package/LICENSE +21 -0
- package/README.md +34 -0
- package/dist/src/core/Negotiator.d.ts +32 -0
- package/dist/src/core/constants.d.ts +68 -0
- package/dist/src/core/errors.d.ts +73 -0
- package/dist/src/core/factories.d.ts +21 -0
- package/dist/src/core/helpers.d.ts +890 -0
- package/dist/src/core/index.d.ts +6 -0
- package/dist/src/core/index.js +1728 -0
- package/dist/src/core/index.js.map +1 -0
- package/dist/src/core/types.d.ts +362 -0
- package/dist/src/server/Server.d.ts +63 -0
- package/dist/src/server/factories.d.ts +26 -0
- package/dist/src/server/helpers.d.ts +45 -0
- package/dist/src/server/index.cjs +1330 -0
- package/dist/src/server/index.cjs.map +1 -0
- package/dist/src/server/index.d.ts +4 -0
- package/dist/src/server/types.d.ts +163 -0
- package/package.json +87 -0
|
@@ -0,0 +1,1330 @@
|
|
|
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
|
+
let node_net = require("node:net");
|
|
6
|
+
let node_http = require("node:http");
|
|
7
|
+
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
|
|
119
|
+
//#region src/server/helpers.ts
|
|
120
|
+
/**
|
|
121
|
+
* Whether a `node:net` `server.address()` return is the structured
|
|
122
|
+
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
123
|
+
* or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
|
|
124
|
+
* and the `Server`'s own port resolution read the bound port through.
|
|
125
|
+
*
|
|
126
|
+
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
127
|
+
* @returns `true` when `value` is an `AddressInfo` with a numeric `port`
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* import { isAddressInfo } from '@src/server'
|
|
132
|
+
*
|
|
133
|
+
* isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
|
|
134
|
+
* isAddressInfo(null) // false
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
function isAddressInfo(value) {
|
|
138
|
+
return isRecord(value) && isNumber(value.port);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Find a FREE TCP port — bind a throwaway `node:net` server, read the
|
|
142
|
+
* OS-assigned port, close it, and resolve that port.
|
|
143
|
+
*
|
|
144
|
+
* @remarks
|
|
145
|
+
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
146
|
+
* and returns it. With a `preferred` port it tries THAT port first and
|
|
147
|
+
* returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
|
|
148
|
+
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
149
|
+
* port. It binds then immediately closes a probe server, so the returned
|
|
150
|
+
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
151
|
+
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
152
|
+
* `preferred` port (e.g. a permission fault).
|
|
153
|
+
*
|
|
154
|
+
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
155
|
+
* fall back to an ephemeral port
|
|
156
|
+
* @returns A free TCP port number
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```ts
|
|
160
|
+
* import { createServer, discoverPort } from '@src/server'
|
|
161
|
+
*
|
|
162
|
+
* const port = await discoverPort() // a guaranteed-free ephemeral port
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
function discoverPort(preferred) {
|
|
166
|
+
return new Promise((resolve, reject) => {
|
|
167
|
+
const bind = (port, fallback) => {
|
|
168
|
+
const probe = (0, node_net.createServer)();
|
|
169
|
+
const onError = (error) => {
|
|
170
|
+
probe.close();
|
|
171
|
+
const taken = "code" in error && error.code === "EADDRINUSE";
|
|
172
|
+
if (fallback && taken) bind(0, false);
|
|
173
|
+
else reject(error);
|
|
174
|
+
};
|
|
175
|
+
probe.once("error", onError);
|
|
176
|
+
probe.listen(port, () => {
|
|
177
|
+
const address = probe.address();
|
|
178
|
+
const resolved = isAddressInfo(address) ? address.port : 0;
|
|
179
|
+
probe.close(() => resolve(resolved));
|
|
180
|
+
});
|
|
181
|
+
};
|
|
182
|
+
bind(preferred ?? 0, preferred !== void 0);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
//#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
|
+
//#region src/server/Server.ts
|
|
1018
|
+
/**
|
|
1019
|
+
* The HTTP server facade — an observable `node:http` lifecycle composing the
|
|
1020
|
+
* `@src/core` middleware onion around a consumed `@orkestrel/router`
|
|
1021
|
+
* dispatcher.
|
|
1022
|
+
*
|
|
1023
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
1024
|
+
*
|
|
1025
|
+
* @remarks
|
|
1026
|
+
* - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
|
|
1027
|
+
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
1028
|
+
* ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
|
|
1029
|
+
* bound address), and transitions `idle → starting → listening`. `stop()`
|
|
1030
|
+
* transitions to `stopping`: refuses new connections, fires a fresh-per-run
|
|
1031
|
+
* stop signal so in-flight handlers observe cancellation, drains up to the
|
|
1032
|
+
* `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
|
|
1033
|
+
* `destroy()` is the idempotent final teardown.
|
|
1034
|
+
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
1035
|
+
* `close`); a `Request` is built via the router's `buildRequest`, its
|
|
1036
|
+
* `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
|
|
1037
|
+
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
1038
|
+
* `buildRequest`'s own abort, tied to client disconnect, composes with the
|
|
1039
|
+
* server's stop signal via `AbortSignal.any`, so a handler awaiting
|
|
1040
|
+
* `request.signal` observes BOTH); `context.state` is built via
|
|
1041
|
+
* {@link ServerOptions.state} from the connection facts; the composed
|
|
1042
|
+
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
1043
|
+
* written back via `sendResponse`.
|
|
1044
|
+
* - **The built-in boundary** wraps the WHOLE per-request chain, including
|
|
1045
|
+
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
1046
|
+
* throw (e.g. a malformed `Host` header) to a silent `400` with no
|
|
1047
|
+
* `error` emit; everything after (`Request` reconstruction, connection
|
|
1048
|
+
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
1049
|
+
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
1050
|
+
* message; any other throw renders `500` (message hidden unless
|
|
1051
|
+
* `expose`), `report` is invoked (its own throw swallowed), and `error` is
|
|
1052
|
+
* emitted. A server-owned last resort wraps the final `sendResponse`
|
|
1053
|
+
* write itself: if even that fails, the connection is destroyed rather
|
|
1054
|
+
* than left to escape as an unhandled error.
|
|
1055
|
+
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
1056
|
+
* throwing handler is treated as declined and surfaced on `error`, an
|
|
1057
|
+
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
1058
|
+
* - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
1059
|
+
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
1060
|
+
* routes it to the `error` OPTION (not the domain `error` event).
|
|
1061
|
+
*/
|
|
1062
|
+
var Server = class {
|
|
1063
|
+
id = crypto.randomUUID();
|
|
1064
|
+
#dispatcher;
|
|
1065
|
+
#state;
|
|
1066
|
+
#middleware;
|
|
1067
|
+
#upgradeHandlers = [];
|
|
1068
|
+
#emitter;
|
|
1069
|
+
#host;
|
|
1070
|
+
#configuredPort;
|
|
1071
|
+
#drain;
|
|
1072
|
+
#limit;
|
|
1073
|
+
#expose;
|
|
1074
|
+
#report;
|
|
1075
|
+
#timeouts;
|
|
1076
|
+
#http;
|
|
1077
|
+
#abort = createAbort();
|
|
1078
|
+
#status = "idle";
|
|
1079
|
+
#port;
|
|
1080
|
+
#pending = 0;
|
|
1081
|
+
#waiters = [];
|
|
1082
|
+
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");
|
|
1085
|
+
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");
|
|
1087
|
+
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");
|
|
1089
|
+
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`);
|
|
1091
|
+
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
|
+
this.#dispatcher = options.dispatcher;
|
|
1093
|
+
this.#state = options.state;
|
|
1094
|
+
this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
|
|
1095
|
+
this.#host = options.host;
|
|
1096
|
+
this.#configuredPort = options.port;
|
|
1097
|
+
this.#drain = drain;
|
|
1098
|
+
this.#limit = limit;
|
|
1099
|
+
this.#expose = options.expose ?? false;
|
|
1100
|
+
this.#report = options.report;
|
|
1101
|
+
this.#timeouts = timeouts;
|
|
1102
|
+
this.#emitter = new Emitter({
|
|
1103
|
+
on: options.on,
|
|
1104
|
+
error: options.error
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
get status() {
|
|
1108
|
+
return this.#status;
|
|
1109
|
+
}
|
|
1110
|
+
get port() {
|
|
1111
|
+
return this.#port;
|
|
1112
|
+
}
|
|
1113
|
+
get dispatcher() {
|
|
1114
|
+
return this.#dispatcher;
|
|
1115
|
+
}
|
|
1116
|
+
get emitter() {
|
|
1117
|
+
return this.#emitter;
|
|
1118
|
+
}
|
|
1119
|
+
use(middleware) {
|
|
1120
|
+
if (typeof middleware === "function") this.#middleware.push(middleware);
|
|
1121
|
+
else this.#middleware.push(...middleware);
|
|
1122
|
+
}
|
|
1123
|
+
upgrade(handler) {
|
|
1124
|
+
this.#upgradeHandlers.push(handler);
|
|
1125
|
+
}
|
|
1126
|
+
start() {
|
|
1127
|
+
if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
|
|
1128
|
+
this.#status = "starting";
|
|
1129
|
+
this.#abort = createAbort();
|
|
1130
|
+
const server = (0, node_http.createServer)((request, response) => this.#handle(request, response));
|
|
1131
|
+
if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
|
|
1132
|
+
if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
|
|
1133
|
+
if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
|
|
1134
|
+
server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
|
|
1135
|
+
this.#http = server;
|
|
1136
|
+
return new Promise((resolve, reject) => {
|
|
1137
|
+
const onError = (error) => {
|
|
1138
|
+
server.off("listening", onListening);
|
|
1139
|
+
this.#http = void 0;
|
|
1140
|
+
this.#status = "idle";
|
|
1141
|
+
reject(error);
|
|
1142
|
+
};
|
|
1143
|
+
const onListening = () => {
|
|
1144
|
+
server.off("error", onError);
|
|
1145
|
+
const port = this.#resolvePort(server);
|
|
1146
|
+
this.#port = port;
|
|
1147
|
+
this.#status = "listening";
|
|
1148
|
+
this.#emitter.emit("start", port);
|
|
1149
|
+
resolve(port);
|
|
1150
|
+
};
|
|
1151
|
+
server.once("error", onError);
|
|
1152
|
+
server.once("listening", onListening);
|
|
1153
|
+
server.listen(this.#configuredPort ?? 0, this.#host);
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
async stop() {
|
|
1157
|
+
if (this.#status !== "listening") return;
|
|
1158
|
+
this.#status = "stopping";
|
|
1159
|
+
this.#emitter.emit("stop");
|
|
1160
|
+
const server = this.#http;
|
|
1161
|
+
this.#abort.abort();
|
|
1162
|
+
const deadline = createTimeout({ ms: this.#drain });
|
|
1163
|
+
deadline.start();
|
|
1164
|
+
await this.#drainPending(deadline.signal);
|
|
1165
|
+
deadline.clear();
|
|
1166
|
+
const pending = this.#pending;
|
|
1167
|
+
this.#emitter.emit("drain", pending);
|
|
1168
|
+
if (server !== void 0) await this.#close(server, pending > 0);
|
|
1169
|
+
this.#http = void 0;
|
|
1170
|
+
this.#port = void 0;
|
|
1171
|
+
this.#status = "stopped";
|
|
1172
|
+
}
|
|
1173
|
+
async destroy() {
|
|
1174
|
+
if (this.#status === "stopped" && this.#http === void 0) {
|
|
1175
|
+
this.#emitter.destroy();
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
if (!this.#abort.aborted) this.#abort.abort();
|
|
1179
|
+
const server = this.#http;
|
|
1180
|
+
if (server !== void 0) await this.#close(server, true);
|
|
1181
|
+
this.#http = void 0;
|
|
1182
|
+
this.#port = void 0;
|
|
1183
|
+
this.#status = "stopped";
|
|
1184
|
+
this.#emitter.destroy();
|
|
1185
|
+
}
|
|
1186
|
+
#handle(message, response) {
|
|
1187
|
+
const finish = this.#trackStart();
|
|
1188
|
+
response.once("finish", finish);
|
|
1189
|
+
response.once("close", finish);
|
|
1190
|
+
this.#accept(message, response);
|
|
1191
|
+
}
|
|
1192
|
+
async #accept(message, response) {
|
|
1193
|
+
let raw;
|
|
1194
|
+
try {
|
|
1195
|
+
raw = (0, import_server.buildRequest)(message);
|
|
1196
|
+
} catch {
|
|
1197
|
+
await this.#respond(this.#boundary(new _src_core.HTTPError(400, "invalid request")), response);
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
try {
|
|
1201
|
+
const linked = linkSignal(raw.signal, this.#abort.signal);
|
|
1202
|
+
const request = new Request(raw, { signal: linked });
|
|
1203
|
+
const url = new URL(request.url);
|
|
1204
|
+
this.#emitter.emit("request", request.method, url.pathname);
|
|
1205
|
+
const connection = {
|
|
1206
|
+
ip: message.socket.remoteAddress,
|
|
1207
|
+
encrypted: (0, import_server.isEncryptedSocket)(message.socket)
|
|
1208
|
+
};
|
|
1209
|
+
let cached;
|
|
1210
|
+
const context = {
|
|
1211
|
+
url,
|
|
1212
|
+
method: request.method,
|
|
1213
|
+
state: this.#state(connection),
|
|
1214
|
+
body: () => {
|
|
1215
|
+
cached ??= (0, _src_core.readBody)(request, { limit: this.#limit });
|
|
1216
|
+
return cached;
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
const result = await (0, _src_core.compose)(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
|
|
1220
|
+
await this.#respond(result, response);
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
const mapped = this.#boundary(error);
|
|
1223
|
+
if (!(0, _src_core.isHTTPError)(error)) {
|
|
1224
|
+
this.#emitter.emit("error", error);
|
|
1225
|
+
if (this.#report !== void 0) try {
|
|
1226
|
+
this.#report(error);
|
|
1227
|
+
} catch {}
|
|
1228
|
+
}
|
|
1229
|
+
await this.#respond(mapped, response);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
async #respond(result, response) {
|
|
1233
|
+
try {
|
|
1234
|
+
await (0, import_server.sendResponse)(result, response);
|
|
1235
|
+
} catch {
|
|
1236
|
+
response.destroy();
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
#boundary(error) {
|
|
1240
|
+
if ((0, _src_core.isHTTPError)(error)) return new Response(error.message, { status: error.status });
|
|
1241
|
+
const message = this.#expose && error instanceof Error ? error.message : "Internal Server Error";
|
|
1242
|
+
return new Response(message, { status: 500 });
|
|
1243
|
+
}
|
|
1244
|
+
#onUpgrade(request, socket, head) {
|
|
1245
|
+
let handled = false;
|
|
1246
|
+
for (const handler of this.#upgradeHandlers) try {
|
|
1247
|
+
if (handler(request, socket, head)) {
|
|
1248
|
+
handled = true;
|
|
1249
|
+
break;
|
|
1250
|
+
}
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
this.#emitter.emit("error", error);
|
|
1253
|
+
}
|
|
1254
|
+
if (!handled) socket.destroy();
|
|
1255
|
+
this.#emitter.emit("upgrade", request, handled);
|
|
1256
|
+
}
|
|
1257
|
+
#resolvePort(server) {
|
|
1258
|
+
const address = server.address();
|
|
1259
|
+
if (isAddressInfo(address)) return address.port;
|
|
1260
|
+
return 0;
|
|
1261
|
+
}
|
|
1262
|
+
#close(server, force) {
|
|
1263
|
+
return new Promise((resolve) => {
|
|
1264
|
+
server.close(() => resolve());
|
|
1265
|
+
if (force) server.closeAllConnections();
|
|
1266
|
+
else server.closeIdleConnections();
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
#trackStart() {
|
|
1270
|
+
this.#pending += 1;
|
|
1271
|
+
let finished = false;
|
|
1272
|
+
return () => {
|
|
1273
|
+
if (finished) return;
|
|
1274
|
+
finished = true;
|
|
1275
|
+
this.#pending -= 1;
|
|
1276
|
+
if (this.#pending === 0) {
|
|
1277
|
+
const waiters = this.#waiters;
|
|
1278
|
+
this.#waiters = [];
|
|
1279
|
+
for (const wake of waiters) wake();
|
|
1280
|
+
}
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
#drainPending(signal) {
|
|
1284
|
+
if (this.#pending === 0 || signal.aborted) return Promise.resolve();
|
|
1285
|
+
return new Promise((resolve) => {
|
|
1286
|
+
const onDone = () => {
|
|
1287
|
+
signal.removeEventListener("abort", onDone);
|
|
1288
|
+
resolve();
|
|
1289
|
+
};
|
|
1290
|
+
this.#waiters.push(onDone);
|
|
1291
|
+
signal.addEventListener("abort", onDone, { once: true });
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
};
|
|
1295
|
+
//#endregion
|
|
1296
|
+
//#region src/server/factories.ts
|
|
1297
|
+
/**
|
|
1298
|
+
* Create a {@link ServerInterface} — the node face's HTTP server facade over
|
|
1299
|
+
* a consumed `@orkestrel/router` dispatcher.
|
|
1300
|
+
*
|
|
1301
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
1302
|
+
* @param options - {@link ServerOptions}
|
|
1303
|
+
* @returns A {@link ServerInterface}, not yet started
|
|
1304
|
+
*
|
|
1305
|
+
* @example
|
|
1306
|
+
* ```ts
|
|
1307
|
+
* import { createServer } from '@src/server'
|
|
1308
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
1309
|
+
*
|
|
1310
|
+
* const dispatcher = createDispatcher<{ readonly ip?: string }>()
|
|
1311
|
+
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
1312
|
+
*
|
|
1313
|
+
* const server = createServer({
|
|
1314
|
+
* dispatcher,
|
|
1315
|
+
* state: (connection) => ({ ip: connection.ip }),
|
|
1316
|
+
* })
|
|
1317
|
+
* const port = await server.start()
|
|
1318
|
+
* await server.stop()
|
|
1319
|
+
* ```
|
|
1320
|
+
*/
|
|
1321
|
+
function createServer(options) {
|
|
1322
|
+
return new Server(options);
|
|
1323
|
+
}
|
|
1324
|
+
//#endregion
|
|
1325
|
+
exports.Server = Server;
|
|
1326
|
+
exports.createServer = createServer;
|
|
1327
|
+
exports.discoverPort = discoverPort;
|
|
1328
|
+
exports.isAddressInfo = isAddressInfo;
|
|
1329
|
+
|
|
1330
|
+
//# sourceMappingURL=index.cjs.map
|