import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { WebSocket } from "ws"; const HERE = join(import.meta.dirname, ".."); const hasPd = spawnSync("pd", ["-version"], { encoding: "utf8" }).status !== null; /** * A patch that proves both directions of the bridge: * * - anything arriving on :8081 is printed, and pd's stdout is forwarded to * the browser as log lines; * - a second after loading, it sends `pin 42` back to the bridge on :8091. * * (`netsend` only accepts its own methods, so arbitrary data has to go * through a `send ...` message rather than being piped in raw.) */ const LOOPBACK_PATCH = `#N canvas 0 0 400 300 10; #X obj 20 20 netreceive -u 8081; #X msg 20 50 connect 127.0.0.1 8091; #X obj 20 80 netsend -u; #X obj 120 20 loadbang; #X obj 120 50 print in; #X obj 220 20 del 400; #X msg 220 50 send pin 42; #X obj 220 0 loadbang; #X connect 3 0 1 0; #X connect 1 0 2 0; #X connect 0 0 4 0; #X connect 7 0 5 0; #X connect 5 0 6 0; #X connect 6 0 2 0; `; function startBridge(dir: string, port: number) { const child = spawn( process.execPath, [join(HERE, "server", "bridge.mjs"), "--port", String(port), "--silent", "--dir", dir], { stdio: ["ignore", "pipe", "pipe"] }, ); let output = ""; child.stdout.on("data", (c) => (output += String(c))); child.stderr.on("data", (c) => (output += String(c))); return { child, log: () => output }; } async function waitForPort(port: number, timeoutMs = 5000) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const ok = await new Promise((resolve) => { const socket = new WebSocket(`ws://127.0.0.1:${port}`); socket.on("open", () => { socket.close(); resolve(true); }); socket.on("error", () => resolve(false)); }); if (ok) return; await new Promise((r) => setTimeout(r, 100)); } throw new Error("bridge never accepted a connection"); } /** Collect bridge messages until `match` is satisfied. */ function collect(socket: WebSocket) { const messages: unknown[] = []; const waiters: { match: (m: any) => boolean; resolve: (m: any) => void }[] = []; socket.on("message", (data) => { const message = JSON.parse(String(data)); messages.push(message); for (const waiter of [...waiters]) { if (waiter.match(message)) { waiters.splice(waiters.indexOf(waiter), 1); waiter.resolve(message); } } }); return { messages, next(match: (m: any) => boolean, timeoutMs = 5000): Promise { const existing = messages.find(match); if (existing) return Promise.resolve(existing); return new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error("timed out waiting for message")), timeoutMs); waiters.push({ match, resolve: (m) => { clearTimeout(timer); resolve(m); }, }); }); }, }; } test("bridge round trips a message through a running pd", async (t) => { if (!hasPd) return t.skip("pd not installed"); const port = 8300 + Math.floor(Math.random() * 400); const dir = mkdtempSync(join(tmpdir(), "dragology-bridge-")); const bridge = startBridge(dir, port); let socket: WebSocket | null = null; try { await waitForPort(port); socket = new WebSocket(`ws://127.0.0.1:${port}`); // Attach before the socket opens: the bridge sends `hello` immediately, // and a message emitted with no listener is lost. const inbox = collect(socket); await new Promise((r) => socket!.on("open", r)); const hello = await inbox.next((m) => m.type === "hello"); assert.equal(hello.pdRunning, false); assert.equal(hello.toPdPort, 8081); assert.equal(hello.fromPdPort, 8091); socket.send(JSON.stringify({ type: "save", name: "loop.pd", text: LOOPBACK_PATCH })); await inbox.next((m) => m.type === "log" && /saved/.test(m.line)); socket.send(JSON.stringify({ type: "run", file: "loop.pd" })); const running = await inbox.next((m) => m.type === "pd-status" && m.running === true, 8000); assert.match(running.file, /loop\.pd$/); // pd announces itself once the patch has loaded. const echoed = await inbox.next((m) => m.type === "from-pd" && m.receiver === "pin", 10000); assert.deepEqual(echoed.args, ["42"]); // And a message from the browser reaches the patch's netreceive. socket.send(JSON.stringify({ type: "send", receiver: "pin", args: [42] })); const printed = await inbox.next( (m) => m.type === "log" && /in: pin 42/.test(m.line), 8000, ); assert.match(printed.line, /in: pin 42/); } finally { socket?.close(); bridge.child.kill("SIGTERM"); } }); test("bridge refuses to write outside its patches directory", async () => { const port = 8700 + Math.floor(Math.random() * 200); const dir = mkdtempSync(join(tmpdir(), "dragology-bridge-")); const bridge = startBridge(dir, port); let socket: WebSocket | null = null; try { await waitForPort(port); socket = new WebSocket(`ws://127.0.0.1:${port}`); // Attach before the socket opens: the bridge sends `hello` immediately, // and a message emitted with no listener is lost. const inbox = collect(socket); await new Promise((r) => socket!.on("open", r)); socket.send(JSON.stringify({ type: "save", name: "../../escape.pd", text: "#N canvas 0 0 1 1 10;\n" })); const saved = await inbox.next((m) => m.type === "saved"); assert.equal(saved.file.startsWith(dir), true, `wrote to ${saved.file}`); } finally { socket?.close(); bridge.child.kill("SIGTERM"); } });