@northtalk/ts 0.0.0-stage → 0.2.0

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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/UNICODE-LICENSE.txt +39 -0
  4. package/base64-DORMd3Hv.js +6621 -0
  5. package/binary-value-CEmh60GC.d.ts +15 -0
  6. package/capabilities-CH0FkRMq.js +1301 -0
  7. package/checker-Dc1jl2WH.js +6657 -0
  8. package/core-DptnvQT9.d.ts +14 -0
  9. package/debug-CQBxKnJB.d.ts +3065 -0
  10. package/debug.d.ts +3 -0
  11. package/debug.js +2 -0
  12. package/driver.d.ts +41 -0
  13. package/driver.js +152 -0
  14. package/encoding-nlrpj-Pb.js +99 -0
  15. package/engine-BGaJ9dAk.js +326 -0
  16. package/engine-vbYInVYF.d.ts +86 -0
  17. package/errors-LYJZ_c8h.js +3735 -0
  18. package/group-B742gg4T.js +10170 -0
  19. package/http-capability-CSTkw1Yt.js +728 -0
  20. package/http.d.ts +59 -0
  21. package/http.js +465 -0
  22. package/index.d.ts +651 -0
  23. package/index.js +44 -0
  24. package/manifest-BscyH_rW.d.ts +70 -0
  25. package/manifest-DjsxDSuB.js +129 -0
  26. package/message-layer.d.ts +12 -0
  27. package/message-layer.js +4 -0
  28. package/notify.d.ts +3 -0
  29. package/notify.js +2 -0
  30. package/objects-DJ3QtCCs.d.ts +640 -0
  31. package/objects-Db7IB5vQ.js +91 -0
  32. package/operation-promises-EgZXG5N_.js +23 -0
  33. package/package.json +70 -4
  34. package/readers-BFPuosPk.d.ts +25 -0
  35. package/readers-CjJHKHvH.js +482 -0
  36. package/request-pump-binary-DdY3X-yl.js +2246 -0
  37. package/router--71qvxtY.js +343 -0
  38. package/router-Zhrw5l__.d.ts +55 -0
  39. package/session.d.ts +9 -0
  40. package/session.js +3510 -0
  41. package/setup.d.ts +3 -0
  42. package/setup.js +193 -0
  43. package/sha256-B_kyYw3Z.js +124 -0
  44. package/sqlite.d.ts +74 -0
  45. package/sqlite.js +529 -0
  46. package/store-capability-OZp4hXmj.js +390 -0
  47. package/store-hJrRULMx.js +60 -0
  48. package/store.d.ts +21 -0
  49. package/store.js +4 -0
  50. package/user-capability-BK4Asg7D.js +276 -0
  51. package/wasm.d.ts +243 -0
  52. package/wasm.js +1737 -0
package/http.d.ts ADDED
@@ -0,0 +1,59 @@
1
+
2
+ import { Jt as Group, Qt as HttpImpl, b as PumpResult, ht as ObjectKindDef, mt as ObjectKind, q as Value } from "./debug-CQBxKnJB.js";
3
+ //#region src/http/router.d.ts
4
+ /** The largest request body the router reads by default: 1 MiB. */
5
+ export declare const HTTP_DEFAULT_MAX_BODY_BYTES: number;
6
+ type HttpHostOptions = {
7
+ /**
8
+ * Whether a Grant may listen on this address, from its binding. The
9
+ * default allows any; a refusal fails `serve` with `bad address`.
10
+ */
11
+ allow?: (host: string, port: number, binding: unknown) => boolean;
12
+ /** The host a `serve` without `host` listens on: `127.0.0.1` by default. */
13
+ defaultHost?: string;
14
+ /** The port a `serve` without `port` listens on: 0, any free port, by default. */
15
+ defaultPort?: number;
16
+ /** Defines the `httpExchange` Object Kind; the TS Core's by default. Pass the Core's own for the Zig Host Adapter. */
17
+ defineObjectKind?: <N>(k: ObjectKindDef<N>) => ObjectKind<N>;
18
+ /** Told of each 500's cause and each refused Delivery. Never sent to the client. */
19
+ log?: (message: string) => void;
20
+ /** A larger request body is answered 413 without a Delivery. */
21
+ maxBodyBytes?: number;
22
+ /** When set, every `serve` listens on this port, whatever it asked for. */
23
+ portOverride?: number;
24
+ };
25
+ type HttpAddress = {
26
+ host: string;
27
+ port: number;
28
+ };
29
+ type HttpHost = {
30
+ /** Every address listening now, in the order the listeners bound. */
31
+ addresses(): HttpAddress[];
32
+ /** Stops accepting, answers every open exchange 503 and closes every listener. */
33
+ close(): Promise<void>;
34
+ /** A Group the Host discards: removes its registrations and answers its open exchanges 503. */
35
+ detach(group: Group): void;
36
+ /**
37
+ * Waits up to `ms` for the open exchanges to be answered, then answers the
38
+ * rest 503. Call `stopAccepting` first so no new ones arrive.
39
+ */
40
+ drain(ms: number): Promise<void>;
41
+ /** The `HttpImpl` to give `httpCapability`. */
42
+ readonly impl: HttpImpl;
43
+ /** `onPump` for a Group's driver: `pumped(group, result)` bound to it. */
44
+ onPump(group: Group): (result: PumpResult) => void;
45
+ /** The exchanges delivered and not yet answered. */
46
+ readonly openExchanges: number;
47
+ /** After each Pump of the Group returns: settles exchanges from its reports, in order. */
48
+ pumped(group: Group, result: Pick<PumpResult, 'reports'>): void;
49
+ /** The Serve Registrations held. */
50
+ readonly registrations: number;
51
+ /** Stops accepting connections. New requests on open connections are answered 503. */
52
+ stopAccepting(): void;
53
+ };
54
+ /** The one argument chapter 7 gives an HTTP Exchange's Delivery, without `exchange`. */
55
+ export declare const requestFields: (method: string, target: string, rawHeaders: readonly string[], body: Uint8Array) => [string, Value][];
56
+ /** Creates the HTTP router. Give `impl` to `httpCapability`, and call `pumped` after each Pump. */
57
+ export declare const createHttpHost: (o?: HttpHostOptions) => HttpHost;
58
+ //#endregion
59
+ export type { HttpAddress, HttpHost, HttpHostOptions };
package/http.js ADDED
@@ -0,0 +1,465 @@
1
+
2
+ import { F as num, K as text, M as map, d as bytes, i as ScriptError, k as listValues, t as HostError, u as bool } from "./errors-LYJZ_c8h.js";
3
+ import { t as defineObjectKind } from "./objects-Db7IB5vQ.js";
4
+ import { u as shape } from "./capabilities-CH0FkRMq.js";
5
+ import { Buffer } from "node:buffer";
6
+ import { createServer } from "node:http";
7
+ //#region src/http/router.ts
8
+ /** The largest request body the router reads by default: 1 MiB. */
9
+ const HTTP_DEFAULT_MAX_BODY_BYTES = 1048576;
10
+ const hostErrorOf = (code, message) => new ScriptError(code, message);
11
+ const wholeOf = (v) => {
12
+ if (v.kind !== "number") return;
13
+ const n = Number(v.toString());
14
+ return Number.isSafeInteger(n) ? n : void 0;
15
+ };
16
+ const decode = (part) => {
17
+ try {
18
+ return decodeURIComponent(part);
19
+ } catch {
20
+ return part;
21
+ }
22
+ };
23
+ const byCodePoint = (a, b) => a < b ? -1 : a > b ? 1 : 0;
24
+ /** The one argument chapter 7 gives an HTTP Exchange's Delivery, without `exchange`. */
25
+ const requestFields = (method, target, rawHeaders, body) => {
26
+ const q = target.indexOf("?");
27
+ const path = q < 0 ? target : target.slice(0, q);
28
+ const query = /* @__PURE__ */ new Map();
29
+ for (const [k, v] of new URLSearchParams(q < 0 ? "" : target.slice(q + 1))) query.set(k, [...query.get(k) ?? [], v]);
30
+ const headers = /* @__PURE__ */ new Map();
31
+ for (let i = 0; i + 1 < rawHeaders.length; i += 2) {
32
+ const name = rawHeaders[i].toLowerCase();
33
+ headers.set(name, [...headers.get(name) ?? [], rawHeaders[i + 1]]);
34
+ }
35
+ return [
36
+ ["method", text(method.toUpperCase())],
37
+ ["path", text(path)],
38
+ ["segments", listValues(path.split("/").filter(Boolean).map((part) => text(decode(part))))],
39
+ ["query", map([...query].sort(([a], [b]) => byCodePoint(a, b)).map(([k, vs]) => [k, vs.length === 1 ? text(vs[0]) : listValues(vs.map((v) => text(v)))]))],
40
+ ["headers", map([...headers].sort(([a], [b]) => byCodePoint(a, b)).map(([k, vs]) => [k, k === "set-cookie" ? listValues(vs.map((v) => text(v))) : text(vs.join(", "))]))],
41
+ ["body", bytes(body)]
42
+ ];
43
+ };
44
+ const plainAnswer = (res, status) => {
45
+ if (res.headersSent || res.writableEnded || res.destroyed) return;
46
+ const body = `${status === 404 ? "Not Found" : status === 413 ? "Payload Too Large" : status === 503 ? "Service Unavailable" : "Internal Server Error"}\n`;
47
+ res.writeHead(status, {
48
+ "content-type": "text/plain; charset=utf-8",
49
+ "content-length": Buffer.byteLength(body)
50
+ });
51
+ res.end(body);
52
+ };
53
+ const addressKey = (host, port) => `${host} ${port}`;
54
+ const failed = (outcome) => outcome === "unhandled" ? 404 : outcome === "cancelled" || outcome === "dropped" ? 503 : 500;
55
+ const addressValue = (a) => map([["host", text(a.host)], ["port", num(a.port)]]);
56
+ /** Creates the HTTP router. Give `impl` to `httpCapability`, and call `pumped` after each Pump. */
57
+ const createHttpHost = (o = {}) => {
58
+ const log = o.log ?? (() => {});
59
+ const maxBody = o.maxBodyBytes ?? 1048576;
60
+ const exchangeKind = (o.defineObjectKind ?? defineObjectKind)({
61
+ name: "httpExchange",
62
+ props: { closed: {
63
+ get: (x) => bool(x.native.closed),
64
+ getCost: { fuel: 1 },
65
+ shape: shape.bool
66
+ } }
67
+ });
68
+ const groupIds = /* @__PURE__ */ new WeakMap();
69
+ let nextGroup = 0;
70
+ let nextExchange = 0;
71
+ const groupId = (g) => {
72
+ let id = groupIds.get(g);
73
+ if (id === void 0) {
74
+ id = ++nextGroup;
75
+ groupIds.set(g, id);
76
+ }
77
+ return id;
78
+ };
79
+ const ownerKeyOf = (g, script, grant) => JSON.stringify([
80
+ groupId(g),
81
+ script,
82
+ grant
83
+ ]);
84
+ const registrations = /* @__PURE__ */ new Map();
85
+ const byAddress = /* @__PURE__ */ new Map();
86
+ const listeners = /* @__PURE__ */ new Set();
87
+ const exchanges = /* @__PURE__ */ new Map();
88
+ const runs = /* @__PURE__ */ new Map();
89
+ let stopping = false;
90
+ let open = 0;
91
+ const closeListener = (l) => {
92
+ if (!listeners.delete(l)) return;
93
+ if (l.address) byAddress.delete(addressKey(l.address.host, l.address.port));
94
+ if (l.server.listening) {
95
+ l.server.close();
96
+ l.server.closeIdleConnections();
97
+ }
98
+ };
99
+ const remove = (r) => {
100
+ if (registrations.get(r.key) !== r) return;
101
+ registrations.delete(r.key);
102
+ r.listener.registrations.delete(r);
103
+ if (r.listener.registrations.size === 0 && r.listener.address) closeListener(r.listener);
104
+ };
105
+ const answer = (x, status) => {
106
+ if (x.answered) return;
107
+ x.answered = true;
108
+ open--;
109
+ plainAnswer(x.res, status);
110
+ };
111
+ const finish = (x) => {
112
+ const byDelivery = exchanges.get(x.group);
113
+ if (x.delivery) byDelivery?.delete(x.delivery);
114
+ if (x.run) runs.get(x.group)?.delete(x.run);
115
+ if (x.object) try {
116
+ x.group.dispose(x.object);
117
+ } catch {}
118
+ };
119
+ const settle = (x, status, why) => {
120
+ if (!x.answered && status === 500 && why !== void 0) log(`http: ${status} for delivery ${x.delivery}: ${why}`);
121
+ answer(x, status);
122
+ finish(x);
123
+ };
124
+ const deliver = (r, x, fields) => {
125
+ const { group, script: name } = r.owner;
126
+ const id = `x${++nextExchange}`;
127
+ try {
128
+ x.object = group.object(exchangeKind, id, x);
129
+ const script = group.script(name);
130
+ if (!script) throw new HostError("invalid value", `no Script ${name}`);
131
+ x.delivery = script.deliver({
132
+ name: r.message,
133
+ args: [map([...fields, ["exchange", x.object.value]])]
134
+ });
135
+ } catch (error) {
136
+ if (error?.name === "MailboxFull") answer(x, 503);
137
+ else {
138
+ log(`http: delivery to ${name} refused: ${String(error)}`);
139
+ remove(r);
140
+ answer(x, 500);
141
+ }
142
+ if (x.object) try {
143
+ group.dispose(x.object);
144
+ } catch {}
145
+ return;
146
+ }
147
+ let byDelivery = exchanges.get(group);
148
+ if (!byDelivery) {
149
+ byDelivery = /* @__PURE__ */ new Map();
150
+ exchanges.set(group, byDelivery);
151
+ }
152
+ byDelivery.set(x.delivery, x);
153
+ };
154
+ const match = (l, path) => {
155
+ let best;
156
+ for (const r of l.registrations) if (path.startsWith(r.prefix) && (!best || r.prefix.length > best.prefix.length)) best = r;
157
+ return best;
158
+ };
159
+ const handle = (l, req, res) => {
160
+ if (stopping) {
161
+ res.setHeader("connection", "close");
162
+ plainAnswer(res, 503);
163
+ return;
164
+ }
165
+ if (Number(req.headers["content-length"] ?? 0) > maxBody) {
166
+ res.setHeader("connection", "close");
167
+ plainAnswer(res, 413);
168
+ req.resume();
169
+ return;
170
+ }
171
+ const chunks = [];
172
+ let size = 0;
173
+ let tooLarge = false;
174
+ req.on("data", (chunk) => {
175
+ size += chunk.length;
176
+ if (size > maxBody) {
177
+ if (!tooLarge) {
178
+ tooLarge = true;
179
+ res.setHeader("connection", "close");
180
+ plainAnswer(res, 413);
181
+ }
182
+ return;
183
+ }
184
+ chunks.push(chunk);
185
+ });
186
+ req.on("error", () => {});
187
+ req.on("end", () => {
188
+ if (tooLarge || res.destroyed) return;
189
+ const target = req.url ?? "/";
190
+ const path = target.split("?", 1)[0];
191
+ const r = match(l, path);
192
+ if (!r) {
193
+ plainAnswer(res, 404);
194
+ return;
195
+ }
196
+ if (stopping) {
197
+ plainAnswer(res, 503);
198
+ return;
199
+ }
200
+ const x = {
201
+ answered: false,
202
+ closed: false,
203
+ group: r.owner.group,
204
+ res
205
+ };
206
+ open++;
207
+ res.on("close", () => {
208
+ if (!x.answered) x.closed = true;
209
+ });
210
+ deliver(r, x, requestFields(req.method ?? "GET", target, req.rawHeaders, new Uint8Array(Buffer.concat(chunks))));
211
+ });
212
+ };
213
+ const bind = (l, port) => {
214
+ l.server.on("error", (error) => {
215
+ if (l.address) {
216
+ log(`http: listener error: ${String(error)}`);
217
+ return;
218
+ }
219
+ const code = error.code === "EADDRINUSE" ? "address in use" : "bad address";
220
+ for (const { call, registration } of l.pending) {
221
+ remove(registration);
222
+ call.fail(hostErrorOf(code, `${l.host}:${port}: ${error.message}`));
223
+ }
224
+ l.pending = [];
225
+ for (const r of l.registrations) remove(r);
226
+ listeners.delete(l);
227
+ if (port !== 0) byAddress.delete(addressKey(l.host, port));
228
+ });
229
+ l.server.listen(port, l.host, () => {
230
+ const bound = l.server.address();
231
+ const actual = bound && typeof bound === "object" ? bound.port : port;
232
+ l.address = {
233
+ host: l.host,
234
+ port: actual
235
+ };
236
+ byAddress.set(addressKey(l.host, actual), l);
237
+ for (const { call } of l.pending) call.answer(map([["host", text(l.host)], ["port", num(actual)]]));
238
+ l.pending = [];
239
+ if (l.registrations.size === 0 || stopping) closeListener(l);
240
+ });
241
+ };
242
+ const serve = (call, name, prefix, message, options) => {
243
+ const host = options.get("host").asText() ?? o.defaultHost ?? "127.0.0.1";
244
+ const portValue = options.get("port");
245
+ const asked = o.portOverride ?? (portValue.kind === "nothing" ? o.defaultPort ?? 0 : wholeOf(portValue));
246
+ if (asked === void 0 || asked < 0 || asked > 65535 || host === "" || stopping || !(o.allow?.(host, asked, call.binding) ?? true)) {
247
+ call.fail(hostErrorOf("bad address", `${host}:${String(asked)}`));
248
+ return;
249
+ }
250
+ const ownerKey = ownerKeyOf(call.group, call.scriptName, call.grantName);
251
+ const key = JSON.stringify([ownerKey, name]);
252
+ const existing = registrations.get(key);
253
+ if (existing && existing.prefix === prefix && existing.message === message && existing.asked.host === host && existing.asked.port === asked) {
254
+ if (existing.listener.address) call.answer(addressValue(existing.listener.address));
255
+ else existing.listener.pending.push({
256
+ call,
257
+ registration: existing
258
+ });
259
+ return;
260
+ }
261
+ let l = asked === 0 ? void 0 : byAddress.get(addressKey(host, asked));
262
+ if (l) {
263
+ for (const r of l.registrations) if (r.prefix === prefix && r.ownerKey !== ownerKey) {
264
+ call.fail(hostErrorOf("address in use", `${host}:${asked}${prefix} is served by another owner`));
265
+ return;
266
+ }
267
+ }
268
+ const fresh = !l;
269
+ if (!l) {
270
+ const server = createServer();
271
+ l = {
272
+ host,
273
+ pending: [],
274
+ registrations: /* @__PURE__ */ new Set(),
275
+ server
276
+ };
277
+ const listener = l;
278
+ server.on("request", (req, res) => handle(listener, req, res));
279
+ listeners.add(l);
280
+ if (asked !== 0) byAddress.set(addressKey(host, asked), l);
281
+ }
282
+ const registration = {
283
+ asked: {
284
+ host,
285
+ port: asked
286
+ },
287
+ key,
288
+ listener: l,
289
+ message,
290
+ name,
291
+ owner: {
292
+ group: call.group,
293
+ script: call.scriptName,
294
+ grant: call.grantName
295
+ },
296
+ ownerKey,
297
+ prefix
298
+ };
299
+ l.registrations.add(registration);
300
+ registrations.set(key, registration);
301
+ if (existing) {
302
+ existing.listener.registrations.delete(existing);
303
+ if (existing.listener !== l && existing.listener.registrations.size === 0 && existing.listener.address) closeListener(existing.listener);
304
+ }
305
+ if (l.address) call.answer(addressValue(l.address));
306
+ else {
307
+ l.pending.push({
308
+ call,
309
+ registration
310
+ });
311
+ if (fresh) bind(l, asked);
312
+ }
313
+ };
314
+ const unserve = (call, name) => {
315
+ const ownerKey = ownerKeyOf(call.group, call.scriptName, call.grantName);
316
+ const r = registrations.get(JSON.stringify([ownerKey, name]));
317
+ if (r) remove(r);
318
+ };
319
+ const respond = (call, exchange, response) => {
320
+ const x = exchange.native;
321
+ if (exchange.kind.name !== "httpExchange" || !x || x.group !== call.group || call.delivery === void 0 || call.delivery !== x.delivery) throw hostErrorOf("not owner", "this Run did not receive the exchange");
322
+ if (x.answered) throw hostErrorOf("already responded", "the exchange is answered");
323
+ if (x.closed || x.res.destroyed) {
324
+ x.closed = true;
325
+ throw hostErrorOf("exchange closed", "the client has gone");
326
+ }
327
+ const headers = [];
328
+ const given = response.get("headers");
329
+ for (const [k, v] of given.kind === "map" ? given.entries() : []) headers.push([k, v.kind === "list" ? Array.from({ length: v.length }, (_, i) => v.index(i + 1).asText()) : v.asText()]);
330
+ const has = (name) => headers.some(([k]) => k.toLowerCase() === name);
331
+ const body = response.get("body");
332
+ const json = response.get("json");
333
+ let payload = /* @__PURE__ */ new Uint8Array();
334
+ if (json.kind === "text") {
335
+ payload = Buffer.from(json.asText(), "utf8");
336
+ if (!has("content-type")) headers.push(["content-type", "application/json"]);
337
+ } else if (body.kind === "text") {
338
+ payload = Buffer.from(body.asText(), "utf8");
339
+ if (!has("content-type")) headers.push(["content-type", "text/plain; charset=utf-8"]);
340
+ } else if (body.kind === "bytes") payload = body.asBytes();
341
+ const status = wholeOf(response.get("status")) ?? 200;
342
+ try {
343
+ for (const [k, v] of headers) x.res.setHeader(k, v);
344
+ x.res.statusCode = status;
345
+ x.res.setHeader("content-length", payload.byteLength);
346
+ } catch (error) {
347
+ for (const name of x.res.getHeaderNames()) x.res.removeHeader(name);
348
+ throw new HostError("invalid value", `http: unusable response headers: ${String(error)}`);
349
+ }
350
+ x.answered = true;
351
+ open--;
352
+ x.res.end(payload);
353
+ };
354
+ const pumped = (group, result) => {
355
+ const byDelivery = exchanges.get(group);
356
+ let byRun = runs.get(group);
357
+ const ofRun = (run) => {
358
+ const d = run === void 0 ? void 0 : byRun?.get(run);
359
+ return d === void 0 ? void 0 : byDelivery?.get(d);
360
+ };
361
+ for (const report of result.reports) switch (report.kind) {
362
+ case "stop":
363
+ for (const r of registrations.values()) if (r.owner.group === group && r.owner.script === report.script) remove(r);
364
+ break;
365
+ case "run started": {
366
+ const x = report.delivery && byDelivery?.get(report.delivery);
367
+ if (x) {
368
+ x.run = report.run;
369
+ if (!byRun) {
370
+ byRun = /* @__PURE__ */ new Map();
371
+ runs.set(group, byRun);
372
+ }
373
+ byRun.set(report.run, report.delivery);
374
+ }
375
+ break;
376
+ }
377
+ case "run end": {
378
+ const x = report.delivery && byDelivery?.get(report.delivery) || ofRun(report.run);
379
+ if (x && (x.run === void 0 || x.run === report.run)) {
380
+ const why = report.outcome === "completed" ? "the Run ended without responding" : report.error ? `${report.outcome}: ${report.error.code}: ${report.error.message}` : `${report.outcome}${report.limit ? ` (${report.limit})` : ""}`;
381
+ settle(x, failed(report.outcome), why);
382
+ }
383
+ break;
384
+ }
385
+ case "unhandled": {
386
+ const x = byDelivery?.get(report.delivery);
387
+ if (x) settle(x, 404);
388
+ break;
389
+ }
390
+ case "run discarded": {
391
+ const x = ofRun(report.run);
392
+ if (x) settle(x, stopping ? 503 : 500, `run discarded: ${report.reason}`);
393
+ break;
394
+ }
395
+ case "causal work": {
396
+ const x = byDelivery?.get(report.rootDelivery);
397
+ if (x && report.liveRuns === 0 && report.queuedMessages === 0) settle(x, stopping ? 503 : 500, "its work ended without a Run");
398
+ break;
399
+ }
400
+ }
401
+ };
402
+ const detach = (group) => {
403
+ for (const r of registrations.values()) if (r.owner.group === group) remove(r);
404
+ for (const x of exchanges.get(group)?.values() ?? []) answer(x, 503);
405
+ exchanges.delete(group);
406
+ runs.delete(group);
407
+ };
408
+ const stopAccepting = () => {
409
+ stopping = true;
410
+ for (const l of listeners) if (l.server.listening) {
411
+ l.server.close();
412
+ l.server.closeIdleConnections();
413
+ }
414
+ };
415
+ const answerAll = (status) => {
416
+ for (const byDelivery of exchanges.values()) for (const x of byDelivery.values()) answer(x, status);
417
+ };
418
+ const drain = async (ms) => {
419
+ const until = Date.now() + ms;
420
+ while (open > 0 && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 10));
421
+ answerAll(503);
422
+ };
423
+ const close = async () => {
424
+ stopAccepting();
425
+ answerAll(503);
426
+ const closing = [...listeners].map((l) => new Promise((resolve) => {
427
+ if (!l.server.listening) {
428
+ resolve();
429
+ return;
430
+ }
431
+ l.server.close(() => resolve());
432
+ l.server.closeAllConnections();
433
+ }));
434
+ for (const l of listeners) {
435
+ for (const { call } of l.pending) call.fail(hostErrorOf("bad address", "the Host is closing"));
436
+ l.pending = [];
437
+ }
438
+ listeners.clear();
439
+ byAddress.clear();
440
+ registrations.clear();
441
+ await Promise.all(closing);
442
+ };
443
+ return {
444
+ impl: {
445
+ serve,
446
+ unserve,
447
+ respond
448
+ },
449
+ addresses: () => [...listeners].flatMap((l) => l.address ? [{ ...l.address }] : []),
450
+ close,
451
+ detach,
452
+ drain,
453
+ onPump: (group) => (result) => pumped(group, result),
454
+ get openExchanges() {
455
+ return open;
456
+ },
457
+ pumped,
458
+ get registrations() {
459
+ return registrations.size;
460
+ },
461
+ stopAccepting
462
+ };
463
+ };
464
+ //#endregion
465
+ export { HTTP_DEFAULT_MAX_BODY_BYTES, createHttpHost, requestFields };