import type { PatchState } from "../editor/ops.ts"; export type BridgeMessage = | { type: "hello"; pdRunning: boolean; toPdPort: number; fromPdPort: number } | { type: "from-pd"; receiver: string; args: string[] } | { type: "log"; stream: "stdout" | "stderr"; line: string } | { type: "pd-status"; running: boolean; file: string | null } | { type: "error"; message: string }; export type BridgeStatus = "disconnected" | "connecting" | "open"; /** * Thin WebSocket client for `server/bridge.mjs`. * * The bridge is optional: the editor works on files alone, and the socket * only exists to run a patch in a real Pd and to poke named receivers. */ export class Bridge { private ws: WebSocket | null = null; private listeners = new Set<(m: BridgeMessage) => void>(); private statusListeners = new Set<(s: BridgeStatus) => void>(); constructor(private url: string) {} onMessage(fn: (m: BridgeMessage) => void) { this.listeners.add(fn); return () => this.listeners.delete(fn); } onStatus(fn: (s: BridgeStatus) => void) { this.statusListeners.add(fn); return () => this.statusListeners.delete(fn); } private emitStatus(status: BridgeStatus) { for (const fn of this.statusListeners) fn(status); } connect() { if (this.ws) return; this.emitStatus("connecting"); const ws = new WebSocket(this.url); this.ws = ws; ws.onopen = () => this.emitStatus("open"); ws.onclose = () => { this.ws = null; this.emitStatus("disconnected"); }; ws.onerror = () => this.emitStatus("disconnected"); ws.onmessage = (event) => { let message: BridgeMessage; try { message = JSON.parse(String(event.data)); } catch { return; } for (const fn of this.listeners) fn(message); }; } disconnect() { this.ws?.close(); this.ws = null; this.emitStatus("disconnected"); } send(message: unknown): boolean { if (this.ws?.readyState !== WebSocket.OPEN) return false; this.ws.send(JSON.stringify(message)); return true; } get isOpen() { return this.ws?.readyState === WebSocket.OPEN; } }