posipaki 0.47.0 → 0.48.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 (36) hide show
  1. package/dist/actor-C8DzeQeT.js +258 -0
  2. package/dist/actor-C8DzeQeT.js.map +1 -0
  3. package/dist/index-B3FcBNz7.d.ts +105 -0
  4. package/dist/index-B3FcBNz7.d.ts.map +1 -0
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/port/index.d.ts +3 -0
  8. package/dist/port/index.js +3 -0
  9. package/dist/port/node.d.ts +73 -0
  10. package/dist/port/node.d.ts.map +1 -0
  11. package/dist/port/node.js +353 -0
  12. package/dist/port/node.js.map +1 -0
  13. package/dist/port-DowG9tgl.js +493 -0
  14. package/dist/port-DowG9tgl.js.map +1 -0
  15. package/dist/process-eCAv2tIS.d.ts.map +1 -1
  16. package/dist/reactor-CWPBP7qN.d.ts +135 -0
  17. package/dist/reactor-CWPBP7qN.d.ts.map +1 -0
  18. package/dist/remote/gateway-cli.js +54 -54
  19. package/dist/remote/gateway-cli.js.map +1 -1
  20. package/dist/remote/index.d.ts +71 -13
  21. package/dist/remote/index.d.ts.map +1 -1
  22. package/dist/remote/index.js +15 -19
  23. package/dist/remote/index.js.map +1 -1
  24. package/dist/remote/node.d.ts +11 -7
  25. package/dist/remote/node.d.ts.map +1 -1
  26. package/dist/remote/node.js +44 -36
  27. package/dist/remote/node.js.map +1 -1
  28. package/dist/{version-DRbb_jh2.js → version-BsegZXH2.js} +2 -2
  29. package/dist/{version-DRbb_jh2.js.map → version-BsegZXH2.js.map} +1 -1
  30. package/dist/{websocket-GFSUt3YC.d.ts → websocket-AU2aygxx.d.ts} +49 -24
  31. package/dist/websocket-AU2aygxx.d.ts.map +1 -0
  32. package/dist/{websocket-Dnorztuc.js → websocket-DgE0_5HU.js} +513 -134
  33. package/dist/websocket-DgE0_5HU.js.map +1 -0
  34. package/package.json +9 -1
  35. package/dist/websocket-Dnorztuc.js.map +0 -1
  36. package/dist/websocket-GFSUt3YC.d.ts.map +0 -1
@@ -0,0 +1,353 @@
1
+ import { n as held, r as splitChannel, t as portActor } from "../actor-C8DzeQeT.js";
2
+ import { spawn } from "node:child_process";
3
+ //#region src/port/node/spawn.ts
4
+ const DEFAULT_KILL_AFTER_MS = 5e3;
5
+ /** A command as a channel of bytes: stdout in, stdin out, and its exit when it closes. */
6
+ function spawnPort(command, options = {}) {
7
+ return spawnPorts(command, options).then((ports) => ports.stdout);
8
+ }
9
+ /** One process, its stdout and its stderr, each a channel that ends with the same exit. */
10
+ async function spawnPorts(command, options = {}) {
11
+ const [file, ...args] = command;
12
+ if (file === void 0) throw new Error("spawnPort: there is no command to run");
13
+ const child = spawn(file, args, {
14
+ cwd: options.cwd,
15
+ env: options.env
16
+ });
17
+ await started(child, file);
18
+ const out = bytesOf(child.stdout, "stdout");
19
+ const err = bytesOf(child.stderr, "stderr");
20
+ let exit = null;
21
+ let ended = false;
22
+ const closers = /* @__PURE__ */ new Set();
23
+ const failers = /* @__PURE__ */ new Set();
24
+ const end = (why) => {
25
+ if (ended) return;
26
+ ended = true;
27
+ exit = why;
28
+ for (const closer of [...closers]) closer(why);
29
+ };
30
+ child.on("error", (error) => {
31
+ for (const failer of [...failers]) failer(error);
32
+ });
33
+ child.on("close", (code, signal) => end(code !== null ? {
34
+ kind: "exit",
35
+ code
36
+ } : {
37
+ kind: "signal",
38
+ signal: signal ?? "unknown"
39
+ }));
40
+ const close = (reason) => {
41
+ return shutdown(child, options.killAfterMs ?? DEFAULT_KILL_AFTER_MS).catch(() => void 0);
42
+ };
43
+ const onClose = (handler) => {
44
+ if (exit !== null) {
45
+ handler(exit);
46
+ return () => {};
47
+ }
48
+ closers.add(handler);
49
+ return () => {
50
+ closers.delete(handler);
51
+ };
52
+ };
53
+ const onError = (handler) => {
54
+ failers.add(handler);
55
+ return () => {
56
+ failers.delete(handler);
57
+ };
58
+ };
59
+ const stderr = {
60
+ send: () => Promise.reject(/* @__PURE__ */ new Error("stderr carries the process's output; it has no input")),
61
+ onFrame: err.onFrame,
62
+ onClose,
63
+ onError,
64
+ close
65
+ };
66
+ return {
67
+ stdout: {
68
+ send: (frame) => write(child, frame),
69
+ onFrame: out.onFrame,
70
+ onClose,
71
+ onError,
72
+ close
73
+ },
74
+ stderr
75
+ };
76
+ }
77
+ /** Resolves once the child exists, rejects when the command could not be started at all. */
78
+ function started(child, file) {
79
+ return new Promise((resolve, reject) => {
80
+ child.once("spawn", () => resolve());
81
+ child.once("error", (error) => reject(/* @__PURE__ */ new Error(`spawnPort: could not start ${file}: ${error.message}`)));
82
+ });
83
+ }
84
+ /** One output stream as the frames of a channel, kept until somebody reads them. */
85
+ function bytesOf(stream, label) {
86
+ const readers = /* @__PURE__ */ new Set();
87
+ const frames = {
88
+ send: () => Promise.reject(/* @__PURE__ */ new Error(`${label} carries the process's output; it has no input`)),
89
+ onFrame(handler) {
90
+ readers.add(handler);
91
+ return () => {
92
+ readers.delete(handler);
93
+ };
94
+ },
95
+ onClose: () => () => {},
96
+ onError: () => () => {},
97
+ close: () => Promise.resolve()
98
+ };
99
+ stream?.on("data", (chunk) => {
100
+ const bytes = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
101
+ for (const reader of [...readers]) reader(bytes);
102
+ });
103
+ return held(frames);
104
+ }
105
+ /** Writes to the child's stdin, and settles when the write is out. */
106
+ function write(child, frame) {
107
+ const stdin = child.stdin;
108
+ if (stdin === null || stdin.destroyed) return Promise.reject(/* @__PURE__ */ new Error("the process's stdin is closed"));
109
+ return new Promise((resolve, reject) => {
110
+ stdin.write(frame, (error) => error === null || error === void 0 ? resolve() : reject(error));
111
+ });
112
+ }
113
+ /** Ends stdin, and kills what is still there after the grace. */
114
+ async function shutdown(child, killAfterMs) {
115
+ if (child.exitCode !== null || child.signalCode !== null) return;
116
+ const closed = new Promise((resolve) => {
117
+ child.once("close", () => resolve());
118
+ });
119
+ child.stdin?.end();
120
+ const timer = setTimeout(() => {
121
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
122
+ }, killAfterMs);
123
+ timer.unref?.();
124
+ await closed;
125
+ clearTimeout(timer);
126
+ }
127
+ //#endregion
128
+ //#region src/port/node/process.ts
129
+ /** Parts as their text: what a line port carries. Octets that came with a line are not text and are dropped. */
130
+ function lines(parts) {
131
+ const readers = /* @__PURE__ */ new Set();
132
+ const closers = /* @__PURE__ */ new Set();
133
+ const failers = /* @__PURE__ */ new Set();
134
+ parts.onFrame(({ line }) => {
135
+ for (const reader of [...readers]) reader(line);
136
+ });
137
+ parts.onClose((reason) => {
138
+ for (const closer of [...closers]) closer(reason);
139
+ });
140
+ parts.onError((error) => {
141
+ for (const failer of [...failers]) failer(error);
142
+ });
143
+ return {
144
+ send: (line) => parts.send({
145
+ line,
146
+ bytes: null
147
+ }),
148
+ onFrame(handler) {
149
+ readers.add(handler);
150
+ return () => {
151
+ readers.delete(handler);
152
+ };
153
+ },
154
+ onClose(handler) {
155
+ closers.add(handler);
156
+ return () => {
157
+ closers.delete(handler);
158
+ };
159
+ },
160
+ onError(handler) {
161
+ failers.add(handler);
162
+ return () => {
163
+ failers.delete(handler);
164
+ };
165
+ },
166
+ close: (reason) => parts.close(reason)
167
+ };
168
+ }
169
+ /** The child's octets, frame for frame. */
170
+ const BinaryPort = portActor({
171
+ name: "binary-port",
172
+ open: (args) => spawnPort(args.command, args)
173
+ });
174
+ /** The same child, cut into lines. */
175
+ const Utf8Port = portActor({
176
+ name: "utf8-port",
177
+ open: async (args) => lines(splitChannel(await spawnPort(args.command, args)))
178
+ });
179
+ //#endregion
180
+ //#region src/port/node/listener.ts
181
+ /**
182
+ * A server whose requests arrive as pairs of ports.
183
+ *
184
+ * `identify` runs before a pair exists, so a refused request costs no stream and the caller reads a status with
185
+ * the reason in it. The request body is the inbound port; the response body is the outbound one.
186
+ */
187
+ function httpListener(options = {}) {
188
+ const runtime = globalThis.Bun;
189
+ if (runtime === void 0) throw new Error("httpListener: this needs Bun's server");
190
+ const waiting = [];
191
+ const buffered = [];
192
+ let closed = false;
193
+ let server = null;
194
+ const take = (pair) => {
195
+ const next = waiting.shift();
196
+ if (next === void 0) {
197
+ buffered.push(pair);
198
+ return;
199
+ }
200
+ next.accept(pair);
201
+ };
202
+ server = runtime.serve({
203
+ port: options.port ?? 0,
204
+ hostname: options.hostname,
205
+ async fetch(request) {
206
+ if (closed) return new Response("listener is closed", { status: 503 });
207
+ let meta;
208
+ try {
209
+ meta = options.identify === void 0 ? void 0 : await options.identify(request);
210
+ } catch (error) {
211
+ return new Response(error instanceof Error ? error.message : String(error), { status: 401 });
212
+ }
213
+ const outbound = responsePort();
214
+ take({
215
+ inbound: requestPort(request),
216
+ outbound: outbound.channel,
217
+ meta
218
+ });
219
+ return new Response(outbound.body);
220
+ }
221
+ });
222
+ return {
223
+ get port() {
224
+ return server === null ? 0 : server.port;
225
+ },
226
+ accept() {
227
+ const next = buffered.shift();
228
+ if (next !== void 0) return Promise.resolve(next);
229
+ if (closed) return Promise.reject(/* @__PURE__ */ new Error("httpListener: closed"));
230
+ return new Promise((accept, refuse) => {
231
+ waiting.push({
232
+ accept,
233
+ refuse
234
+ });
235
+ });
236
+ },
237
+ async close() {
238
+ closed = true;
239
+ for (const next of waiting.splice(0)) next.refuse(/* @__PURE__ */ new Error("httpListener: closed"));
240
+ await server?.stop(true);
241
+ server = null;
242
+ }
243
+ };
244
+ }
245
+ /** The request's body as the inbound port: frames as they arrive, ended when the body is. */
246
+ function requestPort(request) {
247
+ const readers = /* @__PURE__ */ new Set();
248
+ const closers = /* @__PURE__ */ new Set();
249
+ let ended = false;
250
+ const end = () => {
251
+ if (ended) return;
252
+ ended = true;
253
+ for (const closer of [...closers]) closer(void 0);
254
+ };
255
+ const inbound = {
256
+ send: () => Promise.reject(/* @__PURE__ */ new Error("a request body has no input; that side is the caller's")),
257
+ onFrame(handler) {
258
+ readers.add(handler);
259
+ return () => {
260
+ readers.delete(handler);
261
+ };
262
+ },
263
+ onClose(handler) {
264
+ if (ended) {
265
+ handler(void 0);
266
+ return () => {};
267
+ }
268
+ closers.add(handler);
269
+ return () => {
270
+ closers.delete(handler);
271
+ };
272
+ },
273
+ onError() {
274
+ return () => {};
275
+ },
276
+ close: async () => {
277
+ await request.body?.cancel().catch(() => void 0);
278
+ end();
279
+ }
280
+ };
281
+ const reader = request.body?.getReader();
282
+ const port = held(inbound);
283
+ (async () => {
284
+ if (reader === void 0) {
285
+ end();
286
+ return;
287
+ }
288
+ for (;;) {
289
+ const chunk = await reader.read();
290
+ if (chunk.done) {
291
+ end();
292
+ return;
293
+ }
294
+ for (const target of [...readers]) target(chunk.value);
295
+ }
296
+ })();
297
+ return port;
298
+ }
299
+ /** The response's channel, and the body a `Response` is built from. One stream, written by the channel. */
300
+ function responsePort() {
301
+ const readers = /* @__PURE__ */ new Set();
302
+ const closers = /* @__PURE__ */ new Set();
303
+ let ended = false;
304
+ const end = () => {
305
+ if (ended) return;
306
+ ended = true;
307
+ for (const closer of [...closers]) closer(void 0);
308
+ };
309
+ return {
310
+ channel: {
311
+ async send(frame) {
312
+ if (ended) throw new Error("this response is over");
313
+ for (const reader of [...readers]) reader(frame);
314
+ },
315
+ onFrame() {
316
+ return () => {};
317
+ },
318
+ onClose(handler) {
319
+ if (ended) {
320
+ handler(void 0);
321
+ return () => {};
322
+ }
323
+ closers.add(handler);
324
+ return () => {
325
+ closers.delete(handler);
326
+ };
327
+ },
328
+ onError() {
329
+ return () => {};
330
+ },
331
+ async close() {
332
+ end();
333
+ }
334
+ },
335
+ body: new ReadableStream({
336
+ start(controller) {
337
+ readers.add((frame) => controller.enqueue(frame));
338
+ closers.add(() => {
339
+ try {
340
+ controller.close();
341
+ } catch {}
342
+ });
343
+ },
344
+ cancel() {
345
+ end();
346
+ }
347
+ })
348
+ };
349
+ }
350
+ //#endregion
351
+ export { BinaryPort, Utf8Port, httpListener, spawnPort, spawnPorts };
352
+
353
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","names":[],"sources":["../../src/port/node/spawn.ts","../../src/port/node/process.ts","../../src/port/node/listener.ts"],"sourcesContent":["// ── a spawned command as a port ─────────────────────────────────────────────\n//\n// The child's stdout is the channel's frames, its stdin is what `send` writes, and the way it ended is the\n// channel's close reason. Nothing else crosses: a child's stderr is discarded, because stderr is a stream the\n// child writes while it runs and not a fact about how it ended. `spawnPorts` is the same process with both of\n// its output streams.\n//\n// Closing is stdin's end of stream first. A program that reads its input exits on EOF, which is the polite\n// half; the process is killed `killAfterMs` later if it is still there, which is the other half.\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport { held } from \"../held.js\";\nimport type { Channel } from \"../channel.js\";\n/** How a process ended: it exited with a code, or a signal terminated it. */\nexport type ProcessEnd =\n | { readonly kind: \"exit\"; readonly code: number }\n | { readonly kind: \"signal\"; readonly signal: string };\nexport interface SpawnPortOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** How long the process may live after its stdin is closed. Default 5000 ms, then SIGKILL. */\n killAfterMs?: number;\n}\nexport interface ProcessPorts {\n readonly stdout: Channel<Uint8Array, ProcessEnd>;\n readonly stderr: Channel<Uint8Array, ProcessEnd>;\n}\nconst DEFAULT_KILL_AFTER_MS = 5_000;\n/** A command as a channel of bytes: stdout in, stdin out, and its exit when it closes. */\nexport function spawnPort(\n command: string[],\n options: SpawnPortOptions = {},\n): Promise<Channel<Uint8Array, ProcessEnd>> {\n return spawnPorts(command, options).then((ports) => ports.stdout);\n}\n/** One process, its stdout and its stderr, each a channel that ends with the same exit. */\nexport async function spawnPorts(\n command: string[],\n options: SpawnPortOptions = {},\n): Promise<ProcessPorts> {\n const [file, ...args] = command;\n if (file === undefined) throw new Error(\"spawnPort: there is no command to run\");\n const child = spawn(file, args, { cwd: options.cwd, env: options.env });\n await started(child, file);\n const out = bytesOf(child.stdout, \"stdout\");\n const err = bytesOf(child.stderr, \"stderr\");\n let exit: ProcessEnd | null = null;\n let ended = false;\n const closers = new Set<(reason: ProcessEnd) => void>();\n const failers = new Set<(error: unknown) => void>();\n const end = (why: ProcessEnd): void => {\n if (ended) return;\n ended = true;\n exit = why;\n for (const closer of [...closers]) closer(why);\n };\n child.on(\"error\", (error) => {\n for (const failer of [...failers]) failer(error);\n });\n // `close` rather than `exit`: it follows the end of both streams, so no frame is lost behind the ending.\n // Node gives a code or a signal and never both; that is the OS's one status word, split in two.\n child.on(\"close\", (code, signal) =>\n end(code !== null ? { kind: \"exit\", code } : { kind: \"signal\", signal: signal ?? \"unknown\" }),\n );\n const close = (reason?: string): Promise<void> => {\n return shutdown(child, options.killAfterMs ?? DEFAULT_KILL_AFTER_MS).catch(() => undefined);\n };\n const onClose = (handler: (reason: ProcessEnd) => void): (() => void) => {\n if (exit !== null) {\n handler(exit);\n return () => {};\n }\n closers.add(handler);\n return () => {\n closers.delete(handler);\n };\n };\n const onError = (handler: (error: unknown) => void): (() => void) => {\n failers.add(handler);\n return () => {\n failers.delete(handler);\n };\n };\n const stderr: Channel<Uint8Array, ProcessEnd> = {\n send: () => Promise.reject(new Error(\"stderr carries the process's output; it has no input\")),\n onFrame: err.onFrame,\n onClose,\n onError,\n close,\n };\n return {\n stdout: { send: (frame) => write(child, frame), onFrame: out.onFrame, onClose, onError, close },\n stderr,\n };\n}\n/** Resolves once the child exists, rejects when the command could not be started at all. */\nfunction started(child: ChildProcess, file: string): Promise<void> {\n return new Promise((resolve, reject) => {\n child.once(\"spawn\", () => resolve());\n child.once(\"error\", (error: Error) =>\n reject(new Error(`spawnPort: could not start ${file}: ${error.message}`)),\n );\n });\n}\n/** One output stream as the frames of a channel, kept until somebody reads them. */\nfunction bytesOf(stream: Readable | null, label: string): Channel<Uint8Array, ProcessEnd> {\n const readers = new Set<(frame: Uint8Array) => void>();\n const frames: Channel<Uint8Array, ProcessEnd> = {\n send: () => Promise.reject(new Error(`${label} carries the process's output; it has no input`)),\n onFrame(handler) {\n readers.add(handler);\n return () => {\n readers.delete(handler);\n };\n },\n // The stream ending is not the process ending: the port reports that, from the process's own exit.\n onClose: () => () => {},\n onError: () => () => {},\n close: () => Promise.resolve(),\n };\n stream?.on(\"data\", (chunk: Buffer) => {\n const bytes = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n for (const reader of [...readers]) reader(bytes);\n });\n return held(frames);\n}\n/** Writes to the child's stdin, and settles when the write is out. */\nfunction write(child: ChildProcess, frame: Uint8Array): Promise<void> {\n const stdin = child.stdin;\n if (stdin === null || stdin.destroyed) return Promise.reject(new Error(\"the process's stdin is closed\"));\n return new Promise((resolve, reject) => {\n stdin.write(frame, (error) => (error === null || error === undefined ? resolve() : reject(error)));\n });\n}\n/** Ends stdin, and kills what is still there after the grace. */\nasync function shutdown(child: ChildProcess, killAfterMs: number): Promise<void> {\n if (child.exitCode !== null || child.signalCode !== null) return;\n const closed = new Promise<void>((resolve) => {\n child.once(\"close\", () => resolve());\n });\n child.stdin?.end();\n const timer = setTimeout(() => {\n if (child.exitCode === null && child.signalCode === null) child.kill(\"SIGKILL\");\n }, killAfterMs);\n timer.unref?.();\n await closed;\n clearTimeout(timer);\n}\n","// ── the two ports that wrap a process ───────────────────────────────────────\n//\n// Both are `portActor` over `spawnPort`: one carries the child's octets as they are, the other puts the splitter\n// underneath and carries lines. The names are the contract — an actor definition is spawned by name.\n\nimport type { Message } from \"../../types.js\";\nimport { portActor } from \"../actor.js\";\nimport type { Channel, Part } from \"../channel.js\";\nimport { splitChannel } from \"../split.js\";\nimport { spawnPort, type ProcessEnd } from \"./spawn.js\";\n\n/** How a process port is started. */\nexport interface ProcessPortArgs {\n command: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** How long the process may live after its stdin is closed. Default 5000 ms, then SIGKILL. */\n killAfterMs?: number;\n}\n\n\n\n/** Parts as their text: what a line port carries. Octets that came with a line are not text and are dropped. */\nfunction lines(parts: Channel<Part, ProcessEnd>): Channel<string, ProcessEnd> {\n const readers = new Set<(line: string) => void>();\n const closers = new Set<(reason: ProcessEnd) => void>();\n const failers = new Set<(error: unknown) => void>();\n\n parts.onFrame(({ line }) => {\n for (const reader of [...readers]) reader(line);\n });\n parts.onClose((reason) => {\n for (const closer of [...closers]) closer(reason);\n });\n parts.onError((error) => {\n for (const failer of [...failers]) failer(error);\n });\n\n return {\n send: (line) => parts.send({ line, bytes: null }),\n onFrame(handler) {\n readers.add(handler);\n return () => {\n readers.delete(handler);\n };\n },\n onClose(handler) {\n closers.add(handler);\n return () => {\n closers.delete(handler);\n };\n },\n onError(handler) {\n failers.add(handler);\n return () => {\n failers.delete(handler);\n };\n },\n close: (reason) => parts.close(reason),\n };\n}\n\n/** The child's octets, frame for frame. */\nexport const BinaryPort = portActor<ProcessPortArgs, Uint8Array, ProcessEnd>({\n name: \"binary-port\",\n open: (args) => spawnPort(args.command, args),\n});\n\n/** The same child, cut into lines. */\nexport const Utf8Port = portActor<ProcessPortArgs, string, ProcessEnd>({\n name: \"utf8-port\",\n open: async (args) => lines(splitChannel(await spawnPort(args.command, args))),\n});\n","// ── an HTTP server as a port listener ───────────────────────────────────────\n//\n// One request is one pair of ports: the request's body is what the far side sends, the response's body is what we\n// send back, and the `Response` is built here because this is the only place that knows HTTP. A handler above\n// sees a pair and nothing about the protocol.\n//\n// The body is built before the handler runs, because a server must answer with a `Response` in the same turn it is\n// asked: writes go into the response's stream, and closing the outbound port ends it.\n\nimport type { Channel } from \"../channel.js\";\nimport { held } from \"../held.js\";\nimport type { PortListener, PortPair } from \"../reactor.js\";\n\nexport interface HttpListenerOptions<Meta> {\n port?: number;\n hostname?: string;\n /** Admission before a body is made: what it returns is the pair's meta; throwing refuses the request. */\n identify?(request: Request): Meta | Promise<Meta>;\n}\n\n/** A port listener that is also an HTTP server: the port it bound, and the pairs it hands out. */\nexport interface HttpListener<Meta> extends PortListener<Uint8Array, Uint8Array, Meta> {\n readonly port: number;\n}\n\n/** The Bun server this wraps, as little of it as is used here. */\ninterface BunServer {\n readonly port: number;\n stop(force?: boolean): void | Promise<void>;\n}\n\ninterface BunRuntime {\n serve(options: {\n port: number;\n hostname?: string;\n fetch(request: Request): Response | Promise<Response>;\n }): BunServer;\n}\n\n/**\n * A server whose requests arrive as pairs of ports.\n *\n * `identify` runs before a pair exists, so a refused request costs no stream and the caller reads a status with\n * the reason in it. The request body is the inbound port; the response body is the outbound one.\n */\nexport function httpListener<Meta = unknown>(options: HttpListenerOptions<Meta> = {}): HttpListener<Meta> {\n const runtime = (globalThis as { Bun?: BunRuntime }).Bun;\n if (runtime === undefined) throw new Error(\"httpListener: this needs Bun's server\");\n\n const waiting: Array<{ accept: (pair: PortPair<Uint8Array, Uint8Array, Meta, void>) => void; refuse: (error: Error) => void }> = [];\n const buffered: Array<PortPair<Uint8Array, Uint8Array, Meta, void>> = [];\n let closed = false;\n let server: BunServer | null = null;\n\n const take = (pair: PortPair<Uint8Array, Uint8Array, Meta, void>): void => {\n const next = waiting.shift();\n if (next === undefined) {\n buffered.push(pair);\n return;\n }\n next.accept(pair);\n };\n\n const bound = runtime.serve({\n port: options.port ?? 0,\n hostname: options.hostname,\n async fetch(request: Request): Promise<Response> {\n if (closed) return new Response(\"listener is closed\", { status: 503 });\n let meta: Meta;\n try {\n meta = options.identify === undefined ? (undefined as Meta) : await options.identify(request);\n } catch (error) {\n return new Response(error instanceof Error ? error.message : String(error), { status: 401 });\n }\n const outbound = responsePort();\n take({ inbound: requestPort(request), outbound: outbound.channel, meta });\n return new Response(outbound.body);\n },\n });\n server = bound;\n\n return {\n get port() {\n return server === null ? 0 : server.port;\n },\n accept(): Promise<PortPair<Uint8Array, Uint8Array, Meta, void>> {\n const next = buffered.shift();\n if (next !== undefined) return Promise.resolve(next);\n if (closed) return Promise.reject(new Error(\"httpListener: closed\"));\n return new Promise((accept, refuse) => {\n waiting.push({ accept, refuse });\n });\n },\n async close(): Promise<void> {\n closed = true;\n for (const next of waiting.splice(0)) next.refuse(new Error(\"httpListener: closed\"));\n await server?.stop(true);\n server = null;\n },\n };\n}\n\n/** The request's body as the inbound port: frames as they arrive, ended when the body is. */\nfunction requestPort(request: Request): Channel<Uint8Array, void> {\n const readers = new Set<(frame: Uint8Array) => void>();\n const closers = new Set<(reason: void) => void>();\n let ended = false;\n\n const end = (): void => {\n if (ended) return;\n ended = true;\n for (const closer of [...closers]) closer(undefined);\n };\n\n const inbound: Channel<Uint8Array, void> = {\n send: () => Promise.reject(new Error(\"a request body has no input; that side is the caller's\")),\n onFrame(handler) {\n readers.add(handler);\n return () => {\n readers.delete(handler);\n };\n },\n onClose(handler) {\n if (ended) {\n handler(undefined);\n return () => {};\n }\n closers.add(handler);\n return () => {\n closers.delete(handler);\n };\n },\n onError() {\n return () => {};\n },\n close: async () => {\n await request.body?.cancel().catch(() => undefined);\n end();\n },\n };\n\n const reader = request.body?.getReader();\n // Held before the first read: a body can arrive in the same turn the pair is handed out.\n const port = held(inbound);\n void (async () => {\n if (reader === undefined) {\n end();\n return;\n }\n for (;;) {\n const chunk = await reader.read();\n if (chunk.done) {\n end();\n return;\n }\n for (const target of [...readers]) target(chunk.value);\n }\n })();\n\n return port;\n}\n\n/** The response's channel, and the body a `Response` is built from. One stream, written by the channel. */\nfunction responsePort(): { channel: Channel<Uint8Array, void>; body: ReadableStream<Uint8Array> } {\n const readers = new Set<(frame: Uint8Array) => void>();\n const closers = new Set<(reason: void) => void>();\n let ended = false;\n\n const end = (): void => {\n if (ended) return;\n ended = true;\n for (const closer of [...closers]) closer(undefined);\n };\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n readers.add((frame) => controller.enqueue(frame));\n closers.add(() => {\n try {\n controller.close();\n } catch {\n // Already closed by the platform: nothing here has an opinion about it.\n }\n });\n },\n cancel() {\n // The caller stopped reading: the channel is over from this side too.\n end();\n },\n });\n\n const channel: Channel<Uint8Array, void> = {\n async send(frame) {\n if (ended) throw new Error(\"this response is over\");\n for (const reader of [...readers]) reader(frame);\n },\n onFrame() {\n return () => {};\n },\n onClose(handler) {\n if (ended) {\n handler(undefined);\n return () => {};\n }\n closers.add(handler);\n return () => {\n closers.delete(handler);\n };\n },\n onError() {\n return () => {};\n },\n async close() {\n end();\n },\n };\n\n return { channel, body };\n}\n"],"mappings":";;;AA2BA,MAAM,wBAAwB;;AAE9B,SAAgB,UACd,SACA,UAA4B,CAAC,GACa;CAC1C,OAAO,WAAW,SAAS,OAAO,CAAC,CAAC,MAAM,UAAU,MAAM,MAAM;AAClE;;AAEA,eAAsB,WACpB,SACA,UAA4B,CAAC,GACN;CACvB,MAAM,CAAC,MAAM,GAAG,QAAQ;CACxB,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,uCAAuC;CAC/E,MAAM,QAAQ,MAAM,MAAM,MAAM;EAAE,KAAK,QAAQ;EAAK,KAAK,QAAQ;CAAI,CAAC;CACtE,MAAM,QAAQ,OAAO,IAAI;CACzB,MAAM,MAAM,QAAQ,MAAM,QAAQ,QAAQ;CAC1C,MAAM,MAAM,QAAQ,MAAM,QAAQ,QAAQ;CAC1C,IAAI,OAA0B;CAC9B,IAAI,QAAQ;CACZ,MAAM,0BAAU,IAAI,IAAkC;CACtD,MAAM,0BAAU,IAAI,IAA8B;CAClD,MAAM,OAAO,QAA0B;EACrC,IAAI,OAAO;EACX,QAAQ;EACR,OAAO;EACP,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,GAAG;CAC/C;CACA,MAAM,GAAG,UAAU,UAAU;EAC3B,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,KAAK;CACjD,CAAC;CAGD,MAAM,GAAG,UAAU,MAAM,WACvB,IAAI,SAAS,OAAO;EAAE,MAAM;EAAQ;CAAK,IAAI;EAAE,MAAM;EAAU,QAAQ,UAAU;CAAU,CAAC,CAC9F;CACA,MAAM,SAAS,WAAmC;EAChD,OAAO,SAAS,OAAO,QAAQ,eAAe,qBAAqB,CAAC,CAAC,YAAY,KAAA,CAAS;CAC5F;CACA,MAAM,WAAW,YAAwD;EACvE,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