import WebSocket from "ws" class client { constructor() { this.url = `ws://localhost:${10000}` this.ws = null this.seq = 0 this.handlers = new Map() console.log(process.cwd()) } connect() { return new Promise((resolve, reject) => { this.ws = new WebSocket(this.url) this.ws.on("message", msg => this.onMessage(msg)) this.ws.on("open", () => { console.log("[forms] connected") resolve() }) this.ws.on("error", err => { reject(err) }) this.ws.on("close", () => { console.log("[forms] disconnected") }) }) } register(type, schema) { this.ws.send(JSON.stringify({ op: "register", type, schema })) } add(type, data) { this.ws.send(JSON.stringify({ op: "add", type, data })) } watch(form, handler) { if (!this.handlers.has(form)) { this.handlers.set(form, new Set()) } this.handlers.get(form).add(handler) this.ws.send(JSON.stringify({ op: "replay", form, fromSeq: this.seq })) } onMessage(raw) { const msg = JSON.parse(raw.toString()) if (msg.type === "hello") { this.seq = msg.seq return } if (msg.type === "add") { this.seq = msg.seq const set = this.handlers.get(msg.form) if (set) { for (const fn of set) { fn(msg.data, msg) } } } } } export default { client: client }