import { Bert } from "./bert.js"; import { Duplex } from "node:stream"; const log = (msg) => process.stderr.write(`${msg}\r\n`); export class Port extends Duplex { bert; originalStdout; fakeStdout = () => true; constructor(allBinariesAsString, mapKeyAsAtom, decodeUndefinedValues) { super({ objectMode: true }); this.bert = new Bert(allBinariesAsString, mapKeyAsAtom, decodeUndefinedValues); this.originalStdout = process.stdout; process.stdout.write = this.fakeStdout; process.stdin.on("readable", () => { while (this._read()) { } }); } _read() { const lenBytes = process.stdin.read(4); if (lenBytes) { const termLen = this.bert.bytesToInt(lenBytes, 4, true); log(`Got incoming term length: ${termLen} (bytes: <<${lenBytes.toString('hex').match(/../g).map((hex) => parseInt(`0x${hex}`).toString()).join(', ')}>>).`); const termBytes = process.stdin.read(termLen); if (termBytes) { const decoded = this.bert.decode(termBytes); this.push(decoded); return decoded; } else { log("Term read got erroneous null."); return null; } } else return null; } _write(obj, encodingOrCallback, callback) { const actualCallback = callback || typeof encodingOrCallback === "function" ? encodingOrCallback : undefined; try { const term = this.bert.encode(obj, true); const len = Buffer.alloc(4); len.writeUInt32BE(term.length, 0); this.originalStdout.write(len); this.originalStdout.write(term, actualCallback); return true; } catch (error) { log(`Error writing: ${error}`); return false; } } } export class Server { port; handler; state = undefined; handleTerm = (term) => { if (this.state === undefined) { this.state = term; } else { this.handler(term, (t) => this.port.write(t), this.state, (reply, ...extraArgs) => { if (reply === "reply") this.port.write(term); if (reply === "reply" && extraArgs.length === 2) { this.state = extraArgs[1]; } else if (reply === "noreply" && extraArgs.length === 1) { this.state = extraArgs[0]; } }); } }; constructor(port, handler) { this.port = port; this.handler = handler; port.on("readable", () => { let term; while (term = port.read()) { this.handleTerm(term); } }); } }