/* Server-Sent-Events pub/sub so the client's db.stream(path) works like Firebase: on subscribe we send one 'put' with the whole value, then a 'put' for every later change. (The client applies 'put' by replacing the value at the given relative path; null = delete.) */ 'use strict'; const { getTree, norm } = require('./db'); const subs = new Map(); // subPath -> Set function send(res, event, p, data) { try { res.write(`event: ${event}\n`); res.write(`data: ${JSON.stringify({ path: p, data })}\n\n`); } catch (e) { /* closed */ } } function subscribe(path, res) { path = norm(path); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' }); if (!subs.has(path)) subs.set(path, new Set()); subs.get(path).add(res); send(res, 'put', '/', getTree(path)); // initial snapshot res.on('close', () => { const set = subs.get(path); if (set) { set.delete(res); if (!set.size) subs.delete(path); } }); } // call after any write at writePath; pushes the change to every affected subscription function notify(writePath) { writePath = norm(writePath); for (const [subPath, set] of subs) { let evPath, data; if (writePath === subPath) { evPath = '/'; data = getTree(subPath); } else if (subPath === '' || writePath.startsWith(subPath + '/')) { evPath = '/' + (subPath ? writePath.slice(subPath.length + 1) : writePath); data = getTree(writePath); } else if (subPath.startsWith(writePath + '/')) { evPath = '/'; data = getTree(subPath); } else continue; for (const res of set) send(res, 'put', evPath, data); } } const hb = setInterval(() => { for (const set of subs.values()) for (const res of set) { try { res.write(': ping\n\n'); } catch (e) { /* closed */ } } }, 25000); if (hb.unref) hb.unref(); module.exports = { subscribe, notify };