Files
dragology-pd/test/integration.test.ts
T
david fe6f2bfe76 Browser patch editor for Pure Data (closes #1)
Open a .pd file, drag boxes and pull cords, save it back as a file Pd
will load. Dragging is Dragology: `d.vary` moves a box, and a cord drag
is `d.closest(...).whenFar(vary)` over every inlet in the patch, so the
plug snaps to an inlet and cancels on empty space.

The parser is a byte-exact round trip. Two Pd format details that matter:
`#X connect` indices count comments, and `;;` (an empty record) is not the
same as a blank line. Anything unmodelled — arrays, `#X declare`,
subpatches — is preserved verbatim.

Tests run real Pd: patches round trip, an edited patch loads in
`pd -nogui` without new complaints, and the bridge carries a message into
a running Pd and back.

The bridge writes to server/patches/ and runs `pd -nogui` itself, so
saving and hearing the patch is one button.
2026-11-04 19:19:53 -08:00

175 lines
6.4 KiB
TypeScript

import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { addNode, deleteNode, newCordId, reconcile, stateFromPatch } from "../src/editor/ops.ts";
import { nodePorts } from "../src/pd/geometry.ts";
import { parsePd } from "../src/pd/parse.ts";
import { serializePd } from "../src/pd/serialize.ts";
const SAMPLES = join(import.meta.dirname, "..", "public", "samples");
const SYNTH = join(SAMPLES, "synth.pd");
/**
* Load a patch in real Pd and report anything it complains about.
* Pd has no batch mode, so we let it start and then kill it.
*/
function pdFeedback(file: string): Promise<string> {
return new Promise((resolve) => {
const child = spawn("pd", ["-nogui", "-nosound", "-open", file], {
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
const collect = (chunk: Buffer) => {
output += String(chunk);
};
child.stdout.on("data", collect);
child.stderr.on("data", collect);
child.on("error", () => resolve(""));
const timer = setTimeout(() => {
child.kill("SIGTERM");
resolve(output);
}, 2500);
child.on("exit", () => {
clearTimeout(timer);
resolve(output);
});
});
}
/** Pd's own chatter, not a problem with the patch. */
function complaints(output: string): string[] {
return output
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.filter((line) => !/priority \d+ scheduling failed/.test(line))
.filter((line) => !/^Pd-\d/.test(line));
}
function hasPd(): boolean {
return spawnSync("pd", ["-version"], { encoding: "utf8" }).status !== null;
}
function scratch(name: string, text: string): string {
const dir = mkdtempSync(join(tmpdir(), "dragology-pd-"));
const file = join(dir, name);
writeFileSync(file, text);
return file;
}
/**
* The shipped sample contains a line Pd rejects on purpose, so the baseline is
* not empty: we assert that what we write adds nothing new. That is the claim
* a patch editor has to be able to make.
*/
async function assertNoNewComplaints(file: string, label: string) {
const baseline = complaints(await pdFeedback(file));
const copy = scratch("copy.pd", serializePd(stateFromPatch(parsePd(readFileSync(file, "utf8"), "copy.pd"))));
const fresh = complaints(await pdFeedback(copy)).filter((line) => !baseline.includes(line));
assert.deepEqual(fresh, [], `${label}: pd said something new\n${await pdFeedback(copy)}`);
}
test("saving an untouched patch adds no pd complaints", async (t) => {
if (!hasPd()) return t.skip("pd not installed");
await assertNoNewComplaints(SYNTH, "synth.pd");
});
test("an edited patch still parses the way pd wants", async (t) => {
if (!hasPd()) return t.skip("pd not installed");
let state = stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "edited.pd"));
const osc = Object.values(state.nodes).find((n) => n.text === "osc~");
const dac = Object.values(state.nodes).find((n) => n.text.startsWith("dac~"));
assert.ok(osc && dac, "sample has an osc~ and a dac~");
// A cord that was not there before, a moved box, and a new box.
const cordId = newCordId();
state = {
...state,
cords: { ...state.cords, [cordId]: { id: cordId, from: osc.id, outlet: 0, to: dac.id, inlet: 0 } },
nodes: { ...state.nodes, [osc.id]: { ...osc, x: osc.x + 40, y: osc.y + 12 } },
};
state = addNode(state, {
id: "added-1",
kind: "obj",
x: 600,
y: 400,
head: "#X obj",
tail: " osc~ 220",
text: "osc~ 220",
});
const text = serializePd(reconcile(state));
assert.match(text, /#X obj 600 400 osc~ 220;/);
assert.match(text, new RegExp(`#X obj ${osc.x + 40} ${osc.y + 12} osc~;`));
const baseline = complaints(await pdFeedback(SYNTH));
const fresh = complaints(await pdFeedback(scratch("edited.pd", text))).filter(
(line) => !baseline.includes(line),
);
assert.deepEqual(fresh, [], "editing introduced a pd error");
});
test("deleting a node drops its record and its cords", () => {
let state = stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "x.pd"));
const victim = Object.values(state.nodes).find((n) =>
Object.values(state.cords).some((c) => c.to === n.id),
);
assert.ok(victim);
const before = Object.keys(state.cords).length;
const attached = Object.values(state.cords).filter(
(c) => c.to === victim.id || c.from === victim.id,
).length;
assert.ok(attached > 0);
state = deleteNode(state, victim.id);
assert.equal(Object.keys(state.cords).length, before - attached);
assert.equal(state.nodes[victim.id], undefined);
assert.ok(!state.records.some((r) => r.kind === "node" && r.id === victim.id));
assert.equal(
Object.values(state.cords).some((c) => c.to === victim.id || c.from === victim.id),
false,
);
});
test("adding a node puts it where pd expects objects", () => {
const state = addNode(stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "x.pd")), {
id: "added-1",
kind: "obj",
x: 10,
y: 10,
head: "#X obj",
tail: " print hello",
text: "print hello",
});
const records = state.records;
const nodeAt = records.findIndex((r) => r.kind === "node" && r.id === "added-1");
const firstCord = records.findIndex((r) => r.kind === "cord");
assert.ok(nodeAt >= 0);
assert.ok(nodeAt < firstCord, "node record goes before the connect records");
});
test("the parser flags the line pd rejects", () => {
const patch = parsePd(readFileSync(SYNTH, "utf8"), "synth.pd");
assert.equal(patch.warnings.length, 1);
assert.match(patch.warnings[0], /DO NOT EDIT/);
});
test("inlet counts follow the object's arguments", () => {
const node = (text: string) =>
({ id: "n", kind: "obj", x: 0, y: 0, head: "#X obj", tail: ` ${text}`, text }) as const;
assert.deepEqual(nodePorts(node("dac~")), { inlets: 2, outlets: 0 });
assert.deepEqual(nodePorts(node("dac~ 1")), { inlets: 1, outlets: 0 });
assert.deepEqual(nodePorts(node("dac~ 1 2")), { inlets: 2, outlets: 0 });
assert.deepEqual(nodePorts(node("adc~ 1")), { inlets: 0, outlets: 1 });
assert.deepEqual(nodePorts(node("route midi")), { inlets: 1, outlets: 2 });
assert.deepEqual(nodePorts(node("t b b b")), { inlets: 1, outlets: 3 });
assert.deepEqual(nodePorts(node("pack 0 0")), { inlets: 2, outlets: 1 });
assert.deepEqual(nodePorts(node("r midi-vel")), { inlets: 0, outlets: 1 });
});