@shing.wong/sure-wasm-helper 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,6 +68,10 @@ const host = await createLoopbackHost({
68
68
  onWsMessage: ({ data, isBinary, send }) => {
69
69
  send(isBinary ? data : { echo: data });
70
70
  },
71
+ // Fires once per socket, including after terminate(); async errors are logged.
72
+ onWsClose: ({ context, code, reason }) => {
73
+ console.log("socket closed", code, reason, context);
74
+ },
71
75
  });
72
76
 
73
77
  console.log(host.uiUrl, host.relayUrl);
@@ -78,6 +82,50 @@ The UI server sends `cross-origin-opener-policy: same-origin` and
78
82
  `cross-origin-embedder-policy: require-corp`, which is what cross-origin
79
83
  isolated browser features (OPFS sync handles, `SharedArrayBuffer`) require.
80
84
 
85
+ By default the WebSocket relay lives on a second loopback port and `relayUrl`
86
+ points at it. Pass `relayPort: false` for single-port mode: no second server is
87
+ created, upgrades are handled on the UI port, `host.relayPort` equals
88
+ `host.uiPort`, and `host.relayUrl` is `ws://<host>:<uiPort>/`. A plain HTTP GET
89
+ on that port still serves the UI (with COOP/COEP) rather than a 426 response.
90
+ `onWsClose` is called exactly once per accepted socket with
91
+ `{ context, req, code, reason }`; `reason` is UTF-8 decoded and empty when the
92
+ client sends none, and callback errors are logged without crashing the server.
93
+
94
+ ## WASI sockets
95
+
96
+ ```ts
97
+ import { createWasiSocketPort } from "@shing.wong/sure-wasm-helper/wasi-socket";
98
+
99
+ const port = createWasiSocketPort({
100
+ componentPath: "socket.component.wasm",
101
+ runtime: "wasmtime",
102
+ });
103
+
104
+ const result = await port.connect({
105
+ address: "127.0.0.1:25",
106
+ message: "EHLO example",
107
+ timeoutMs: 30_000,
108
+ maxBytes: 1024 * 1024,
109
+ });
110
+
111
+ const handle = await port.listen({
112
+ address: "127.0.0.1:0",
113
+ onLine: (line) => console.log(line),
114
+ onError: (error) => console.error(error.code, error.message),
115
+ });
116
+ handle.close(); // SIGTERM
117
+ ```
118
+
119
+ `WasiConnectOptions.maxBytes` (default 1 MiB) bounds the combined stdout and
120
+ stderr that `connect()` collects; a chunk that would exceed it kills the child
121
+ and rejects with `E_WASI_SOCKET_OVERFLOW`. `WasiListenOptions.onError` receives
122
+ async child errors as `E_WASI_SOCKET_FAILED`; the adapter always attaches an
123
+ `error` listener, so omitting the callback cannot crash the process.
124
+ `WasiSocketPortOptions.resolveImpl` overrides runtime discovery, primarily for
125
+ tests: combine `runtime: "no-such-runtime"` with
126
+ `resolveImpl: async () => "/mock/wasmtime"` and an injected `spawnImpl` to run
127
+ without wasmtime on the host.
128
+
81
129
  ## Packaging
82
130
 
83
131
  ```bash
@@ -11,7 +11,12 @@ export interface LoopbackHostOptions {
11
11
  /** Bind address. Defaults to loopback; overriding it exposes the host. */
12
12
  host?: string;
13
13
  port?: number;
14
- relayPort?: number;
14
+ /**
15
+ * Relay port. Pass `false` for single-port mode: no second server is
16
+ * started, WebSocket upgrades are handled on the UI server, and the handle
17
+ * reports `relayPort === uiPort` plus `relayUrl = ws://<host>:<uiPort>/`.
18
+ */
19
+ relayPort?: number | false;
15
20
  noOpen?: boolean;
16
21
  /** Return true when the request is fully handled. */
17
22
  onHttp?: (req: IncomingMessage, res: ServerResponse) => boolean | void | Promise<boolean | void>;
@@ -24,6 +29,12 @@ export interface LoopbackHostOptions {
24
29
  reason?: string;
25
30
  } | boolean | void | Promise<unknown>;
26
31
  onWsMessage?: (info: WsMessageInfo) => void | Promise<void>;
32
+ /**
33
+ * Called once when an accepted WebSocket closes, including after
34
+ * `terminate()`. `reason` is decoded UTF-8 (empty when absent). Errors are
35
+ * logged and never crash the server.
36
+ */
37
+ onWsClose?: (info: WsCloseInfo) => void | Promise<void>;
27
38
  maxFrameBytes?: number;
28
39
  openBrowser?: boolean;
29
40
  log?: (message: string) => void;
@@ -38,13 +49,29 @@ export interface WsMessageInfo {
38
49
  /** Buffer/Uint8Array/ArrayBuffer -> binary frame; string -> text; else JSON. */
39
50
  send: (payload: unknown) => void;
40
51
  }
52
+ export interface WsCloseInfo {
53
+ /** Whatever onWsUpgrade returned in `{ context }`. */
54
+ context: unknown;
55
+ req: IncomingMessage;
56
+ code: number;
57
+ /** Close reason decoded as UTF-8; empty when the client sent none. */
58
+ reason: string;
59
+ }
41
60
  export interface LoopbackHostHandle {
42
61
  uiPort: number;
62
+ /** Relay port; equal to `uiPort` in single-port (`relayPort: false`) mode. */
43
63
  relayPort: number;
44
64
  uiUrl: string;
65
+ /** Relay WebSocket URL; on the UI port in single-port mode. */
45
66
  relayUrl: string;
46
67
  close(): Promise<void>;
47
68
  }
69
+ /**
70
+ * True when `file` is `root` itself or lives below it on the given separator.
71
+ * `separator` defaults to the platform separator; pass `"/"` or `"\\"`
72
+ * explicitly when checking paths that came from another platform.
73
+ */
74
+ export declare function isPathWithin(root: string, file: string, separator?: string): boolean;
48
75
  /**
49
76
  * Start the UI and relay servers. Resolves only after both are listening.
50
77
  *
@@ -5,7 +5,7 @@
5
5
  import { spawn } from "node:child_process";
6
6
  import { createServer } from "node:http";
7
7
  import { readFile, stat } from "node:fs/promises";
8
- import { extname, join, posix, resolve } from "node:path";
8
+ import { extname, join, posix, resolve, sep } from "node:path";
9
9
  import { WebSocket, WebSocketServer } from "ws";
10
10
  const DEFAULT_MAX_FRAME_BYTES = 1024 * 1024;
11
11
  /** Slack above maxFrameBytes so an oversized frame reaches our handler first. */
@@ -25,6 +25,14 @@ const MEDIA_TYPES = {
25
25
  function isRecord(value) {
26
26
  return typeof value === "object" && value !== null && !Array.isArray(value);
27
27
  }
28
+ /**
29
+ * True when `file` is `root` itself or lives below it on the given separator.
30
+ * `separator` defaults to the platform separator; pass `"/"` or `"\\"`
31
+ * explicitly when checking paths that came from another platform.
32
+ */
33
+ export function isPathWithin(root, file, separator = sep) {
34
+ return file === root || file.startsWith(`${root}${separator}`);
35
+ }
28
36
  function listen(server, port, host) {
29
37
  return new Promise((resolvePort, reject) => {
30
38
  const onError = (error) => reject(error);
@@ -100,7 +108,6 @@ export async function createLoopbackHost(options) {
100
108
  const host = options.host ?? "127.0.0.1";
101
109
  const uiDir = resolve(options.uiDir);
102
110
  const requestedUiPort = options.port ?? options.defaultUiPort ?? 8788;
103
- const requestedRelayPort = options.relayPort ?? options.defaultRelayPort ?? 8787;
104
111
  const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
105
112
  const log = options.log ?? ((message) => console.warn(message));
106
113
  let uiDirOk = true;
@@ -156,7 +163,7 @@ export async function createLoopbackHost(options) {
156
163
  const normalized = posix.normalize(pathname);
157
164
  const relative = normalized === "/" ? "index.html" : normalized.replace(/^\/+/, "");
158
165
  const file = resolve(join(uiDir, relative));
159
- if (file !== uiDir && !file.startsWith(`${uiDir}/`)) {
166
+ if (!isPathWithin(uiDir, file)) {
160
167
  res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
161
168
  res.end("bad path");
162
169
  return;
@@ -192,31 +199,43 @@ export async function createLoopbackHost(options) {
192
199
  });
193
200
  const uiPort = await listen(uiServer, requestedUiPort, host);
194
201
  const uiUrl = `http://${host}:${uiPort}/`;
195
- const relayServer = createServer((_req, res) => {
196
- const body = JSON.stringify({
197
- error: "upgrade required",
198
- message: `${options.appName}: this port speaks WebSocket only. Open the UI at ${uiUrl}`,
199
- uiUrl,
200
- });
201
- res.writeHead(426, {
202
- "content-type": "application/json; charset=utf-8",
203
- "cache-control": "no-store",
204
- connection: "close",
205
- });
206
- res.end(body);
207
- });
202
+ const wss = new WebSocketServer({ noServer: true, maxPayload: maxFrameBytes + FRAME_SLACK_BYTES });
203
+ const contexts = new WeakMap();
204
+ let relayServer = null;
208
205
  let relayPort;
209
- try {
210
- relayPort = await listen(relayServer, requestedRelayPort, host);
206
+ let relayUrl;
207
+ if (options.relayPort === false) {
208
+ // Single-port mode: WebSocket upgrades share the UI origin. There is no
209
+ // second server and therefore no relay-only 426 response.
210
+ relayPort = uiPort;
211
+ relayUrl = `ws://${host}:${uiPort}/`;
211
212
  }
212
- catch (error) {
213
- await closeServer(uiServer);
214
- throw error;
213
+ else {
214
+ const requestedRelayPort = options.relayPort ?? options.defaultRelayPort ?? 8787;
215
+ relayServer = createServer((_req, res) => {
216
+ const body = JSON.stringify({
217
+ error: "upgrade required",
218
+ message: `${options.appName}: this port speaks WebSocket only. Open the UI at ${uiUrl}`,
219
+ uiUrl,
220
+ });
221
+ res.writeHead(426, {
222
+ "content-type": "application/json; charset=utf-8",
223
+ "cache-control": "no-store",
224
+ connection: "close",
225
+ });
226
+ res.end(body);
227
+ });
228
+ try {
229
+ relayPort = await listen(relayServer, requestedRelayPort, host);
230
+ }
231
+ catch (error) {
232
+ await closeServer(uiServer);
233
+ throw error;
234
+ }
235
+ relayUrl = `ws://${host}:${relayPort}/`;
215
236
  }
216
- const relayUrl = `ws://${host}:${relayPort}/`;
217
- const wss = new WebSocketServer({ noServer: true, maxPayload: maxFrameBytes + FRAME_SLACK_BYTES });
218
- const contexts = new WeakMap();
219
- relayServer.on("upgrade", (req, socket, head) => {
237
+ const upgradeServer = relayServer ?? uiServer;
238
+ upgradeServer.on("upgrade", (req, socket, head) => {
220
239
  void (async () => {
221
240
  let decision;
222
241
  try {
@@ -242,6 +261,27 @@ export async function createLoopbackHost(options) {
242
261
  });
243
262
  wss.on("connection", (ws, req) => {
244
263
  const context = contexts.get(ws);
264
+ let closeNotified = false;
265
+ ws.on("close", (code, reason) => {
266
+ // `terminate()` also emits `close`; guard so cleanup runs exactly once.
267
+ if (closeNotified)
268
+ return;
269
+ closeNotified = true;
270
+ const info = {
271
+ context,
272
+ req,
273
+ code,
274
+ reason: reason && reason.length > 0 ? reason.toString("utf8") : "",
275
+ };
276
+ try {
277
+ void Promise.resolve(options.onWsClose?.(info)).catch((error) => {
278
+ log(`${options.appName}: onWsClose failed: ${String(error)}`);
279
+ });
280
+ }
281
+ catch (error) {
282
+ log(`${options.appName}: onWsClose failed: ${String(error)}`);
283
+ }
284
+ });
245
285
  ws.on("message", (raw, isBinary) => {
246
286
  const bytes = frameBytes(raw);
247
287
  if (bytes > maxFrameBytes) {
@@ -316,5 +356,5 @@ export function resolveUiFile(uiDir, pathname) {
316
356
  const base = resolve(uiDir);
317
357
  const relative = normalized === "/" ? "index.html" : normalized.replace(/^\/+/, "");
318
358
  const file = resolve(join(base, relative));
319
- return file === base || file.startsWith(`${base}/`) ? file : null;
359
+ return isPathWithin(base, file) ? file : null;
320
360
  }
@@ -1,5 +1,6 @@
1
1
  import { type ChildProcess } from "node:child_process";
2
2
  import type { Readable } from "node:stream";
3
+ import { HelperError } from "./wasm-loader.js";
3
4
  export interface WasiSpawnedProcess {
4
5
  stdout: Readable | null;
5
6
  stderr: Readable | null;
@@ -22,12 +23,16 @@ export interface WasiSocketPortOptions {
22
23
  env?: NodeJS.ProcessEnv;
23
24
  /** Injectable spawn for tests. Defaults to node:child_process.spawn. */
24
25
  spawnImpl?: WasiSpawnImpl;
26
+ /** Injectable runtime resolver for tests. Defaults to `resolveRuntime`. */
27
+ resolveImpl?: (runtime: string) => Promise<string | null>;
25
28
  }
26
29
  export interface WasiConnectOptions {
27
30
  address: string;
28
31
  message?: string;
29
32
  tls?: boolean;
30
33
  timeoutMs?: number;
34
+ /** Cap on combined stdout+stderr bytes. Defaults to 1 MiB. */
35
+ maxBytes?: number;
31
36
  }
32
37
  export interface WasiConnectResult {
33
38
  connected: boolean;
@@ -37,6 +42,8 @@ export interface WasiConnectResult {
37
42
  export interface WasiListenOptions {
38
43
  address: string;
39
44
  onLine: (line: string) => void;
45
+ /** Receives async child errors instead of an unhandled EventEmitter error. */
46
+ onError?: (err: HelperError) => void;
40
47
  }
41
48
  export interface WasiListenHandle {
42
49
  close(): void;
@@ -58,10 +65,16 @@ export declare class WasiSocketPort {
58
65
  readonly runtime: string;
59
66
  private readonly env;
60
67
  private readonly spawnImpl;
68
+ private readonly resolveImpl;
61
69
  constructor(options: WasiSocketPortOptions);
70
+ /**
71
+ * Check the component once and resolve the runtime once. Both `available()`
72
+ * and the launch paths go through this, so a connect/listen never re-checks
73
+ * prerequisites independently.
74
+ */
75
+ private resolvePrerequisites;
62
76
  /** True when both the runtime and the component file are usable. */
63
77
  available(): Promise<boolean>;
64
- private runtimePath;
65
78
  /** Open a connection, optionally send one message, and collect the reply. */
66
79
  connect(options: WasiConnectOptions): Promise<WasiConnectResult>;
67
80
  /**
@@ -73,5 +86,8 @@ export declare class WasiSocketPort {
73
86
  listen(options: WasiListenOptions): Promise<WasiListenHandle>;
74
87
  }
75
88
  export declare function createWasiSocketPort(options: WasiSocketPortOptions): WasiSocketPort;
76
- /** Present so callers can test the child type without importing node types. */
89
+ /**
90
+ * Present so callers can test the child type without importing node types.
91
+ * The `spawn` import above stays live because `defaultSpawn` uses it.
92
+ */
77
93
  export type WasiChild = ChildProcess;
@@ -65,36 +65,50 @@ export class WasiSocketPort {
65
65
  runtime;
66
66
  env;
67
67
  spawnImpl;
68
+ resolveImpl;
68
69
  constructor(options) {
69
70
  this.componentPath = options.componentPath;
70
71
  this.runtime = options.runtime ?? "wasmtime";
71
72
  this.env = { ...process.env, ...(options.env ?? {}) };
72
73
  this.spawnImpl = options.spawnImpl ?? defaultSpawn;
74
+ this.resolveImpl = options.resolveImpl ?? resolveRuntime;
73
75
  }
74
- /** True when both the runtime and the component file are usable. */
75
- async available() {
76
+ /**
77
+ * Check the component once and resolve the runtime once. Both `available()`
78
+ * and the launch paths go through this, so a connect/listen never re-checks
79
+ * prerequisites independently.
80
+ */
81
+ async resolvePrerequisites() {
76
82
  try {
77
83
  await access(this.componentPath, constants.R_OK);
78
84
  }
79
85
  catch {
80
- return false;
86
+ return null;
81
87
  }
82
- return (await resolveRuntime(this.runtime)) !== null;
83
- }
84
- async runtimePath() {
85
- if (!(await this.available())) {
86
- throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `WASI socket prerequisites missing: runtime '${this.runtime}' or component '${this.componentPath}'`);
88
+ let runtimePath;
89
+ try {
90
+ runtimePath = await this.resolveImpl(this.runtime);
87
91
  }
88
- const resolved = await resolveRuntime(this.runtime);
89
- if (!resolved) {
90
- throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `runtime '${this.runtime}' not found on PATH`);
92
+ catch {
93
+ return null;
91
94
  }
92
- return resolved;
95
+ if (!runtimePath)
96
+ return null;
97
+ return { runtimePath, componentPath: this.componentPath };
98
+ }
99
+ /** True when both the runtime and the component file are usable. */
100
+ async available() {
101
+ return (await this.resolvePrerequisites()) !== null;
93
102
  }
94
103
  /** Open a connection, optionally send one message, and collect the reply. */
95
104
  async connect(options) {
96
- const runtimePath = await this.runtimePath();
105
+ const prerequisites = await this.resolvePrerequisites();
106
+ if (!prerequisites) {
107
+ throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `WASI socket prerequisites missing: runtime '${this.runtime}' or component '${this.componentPath}'`);
108
+ }
109
+ const runtimePath = prerequisites.runtimePath;
97
110
  const timeoutMs = options.timeoutMs ?? 30000;
111
+ const maxBytes = options.maxBytes ?? 1024 * 1024;
98
112
  const args = argsFor("connect", {
99
113
  componentPath: this.componentPath,
100
114
  address: options.address,
@@ -115,6 +129,7 @@ export class WasiSocketPort {
115
129
  return new Promise((resolve, reject) => {
116
130
  let stdout = "";
117
131
  let stderr = "";
132
+ let totalBytes = 0;
118
133
  let settled = false;
119
134
  const timer = setTimeout(() => {
120
135
  if (settled)
@@ -123,12 +138,35 @@ export class WasiSocketPort {
123
138
  child.kill("SIGKILL");
124
139
  reject(new HelperError("E_WASI_SOCKET_TIMEOUT", `connect timed out after ${timeoutMs}ms`));
125
140
  }, timeoutMs);
141
+ /**
142
+ * Account for one chunk before it is appended. A chunk that would push
143
+ * the combined output past `maxBytes` kills the child and settles once;
144
+ * later data/close/error events are ignored.
145
+ */
146
+ const account = (chunk, stream) => {
147
+ if (settled)
148
+ return false;
149
+ const size = typeof chunk === "string" ? Buffer.byteLength(chunk, "utf8") : chunk.byteLength;
150
+ if (totalBytes + size > maxBytes) {
151
+ settled = true;
152
+ clearTimeout(timer);
153
+ child.kill("SIGKILL");
154
+ reject(new HelperError("E_WASI_SOCKET_OVERFLOW", `connect ${stream} exceeded the ${maxBytes}-byte maxBytes cap`));
155
+ return false;
156
+ }
157
+ totalBytes += size;
158
+ return true;
159
+ };
126
160
  child.stdout?.setEncoding("utf8");
127
161
  child.stderr?.setEncoding("utf8");
128
162
  child.stdout?.on("data", (chunk) => {
163
+ if (!account(chunk, "stdout"))
164
+ return;
129
165
  stdout += String(chunk);
130
166
  });
131
167
  child.stderr?.on("data", (chunk) => {
168
+ if (!account(chunk, "stderr"))
169
+ return;
132
170
  stderr += String(chunk);
133
171
  });
134
172
  child.on("error", (error) => {
@@ -154,7 +192,11 @@ export class WasiSocketPort {
154
192
  * sends SIGTERM and returns immediately.
155
193
  */
156
194
  async listen(options) {
157
- const runtimePath = await this.runtimePath();
195
+ const prerequisites = await this.resolvePrerequisites();
196
+ if (!prerequisites) {
197
+ throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `WASI socket prerequisites missing: runtime '${this.runtime}' or component '${this.componentPath}'`);
198
+ }
199
+ const runtimePath = prerequisites.runtimePath;
158
200
  const args = argsFor("listen", {
159
201
  componentPath: this.componentPath,
160
202
  address: options.address,
@@ -192,13 +234,22 @@ export class WasiSocketPort {
192
234
  }
193
235
  });
194
236
  child.on("error", (error) => {
195
- emit(`error: ${error.message}`);
237
+ // Keep a listener attached even without a callback so an async spawn
238
+ // failure can never become an unhandled EventEmitter error.
239
+ if (!options.onError)
240
+ return;
241
+ try {
242
+ options.onError(failed(`listen child failed: ${error.message}`, error));
243
+ }
244
+ catch {
245
+ // A consumer's callback must not take down the child's stream.
246
+ }
196
247
  });
197
248
  child.on("close", () => {
198
- if (buffer.length > 0) {
199
- emit(buffer.replace(/\r$/, ""));
200
- buffer = "";
201
- }
249
+ const trailing = buffer.replace(/\r$/, "");
250
+ buffer = "";
251
+ if (trailing.length > 0)
252
+ emit(trailing);
202
253
  });
203
254
  return {
204
255
  close() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shing.wong/sure-wasm-helper",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Generic WASM reactor host, loopback UI/WebSocket host, WASI socket adapter, SEA packager, self-updater and cold-start bench",
5
5
  "type": "module",
6
6
  "license": "MIT",