import { readFile } from "node:fs"; import { createServer, type Server, type ServerResponse } from "node:http"; export type TuneDashboard = { url: string; update(html: string, jsonlPath: string): void; broadcast(): void; close(): void; }; export async function startTuneDashboard( html: string, jsonlPath: string, ): Promise { let currentHtml = html; let currentJsonlPath = jsonlPath; let closed = false; const clients = new Set(); const server = createServer((req, res) => { const url = new URL(req.url ?? "/", "http://127.0.0.1"); if (url.pathname === "/events") { res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }); res.write("retry: 1000\n\n"); clients.add(res); res.on("close", () => clients.delete(res)); return; } if (url.pathname === "/") { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", }); res.end(currentHtml); return; } if (url.pathname === "/session.jsonl") { readFile(currentJsonlPath, (error, data) => { if (error) { res.writeHead(404); res.end(); return; } res.writeHead(200, { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store", }); res.end(data); }); return; } res.writeHead(404); res.end(); }); const port = await listen(server); return { url: `http://127.0.0.1:${port}`, update(nextHtml, nextJsonlPath) { currentHtml = nextHtml; currentJsonlPath = nextJsonlPath; }, broadcast() { for (const client of clients) { try { client.write("event: jsonl-updated\n"); client.write(`data: ${Date.now()}\n\n`); } catch { clients.delete(client); } } }, close() { if (closed) return; closed = true; for (const client of clients) client.end(); clients.clear(); server.close(); }, }; } function listen(server: Server): Promise { return new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => { server.off("error", reject); const address = server.address(); if (!address || typeof address === "string") { reject(new Error("Failed to bind tune dashboard server")); return; } resolve(address.port); }); }); }