/** * Web Dashboard — Web Server * * AUTO-GENERATED by Phoenix VCS * Serves the web client HTML, plus health/metrics/modules endpoints. */ import { createServer, IncomingMessage, ServerResponse } from 'node:http'; import * as analyticsPanel from './analytics-panel.js'; import * as dashboardPage from './dashboard-page.js'; import * as styles from './styles.js'; import * as taskListDisplay from './task-list-display.js'; // ─── Metrics ───────────────────────────────────────────────────────────────── const _svcMetrics = { requests_total: 0, requests_by_path: {} as Record, errors_total: 0, uptime_start: Date.now(), }; // ─── Module Registry ───────────────────────────────────────────────────────── const _svcModules = { 'analytics-panel': analyticsPanel, 'dashboard-page': dashboardPage, 'styles': styles, 'task-list-display': taskListDisplay, }; // ─── HTML Renderer ─────────────────────────────────────────────────────────── function renderPage(): string { // Collect CSS from style modules let css = ''; try { const styleMod = styles as Record; for (const key of Object.keys(styleMod)) { const val = styleMod[key]; if (typeof val === 'function' && /css|style/i.test(key)) { const result = (val as Function)(); if (typeof result === 'string') css += result; else if (result && typeof result === 'object' && 'generateCSS' in result) { css += (result as { generateCSS: () => string }).generateCSS(); } } } } catch { /* style module may not have expected exports */ } // Collect HTML from UI modules const sections: string[] = []; try { const uiMod = analyticsPanel as Record; for (const key of Object.keys(uiMod)) { const val = uiMod[key]; // Look for factory functions that return objects with render/renderHTML if (typeof val === 'function' && /^create|^make|^render|^build/i.test(key)) { try { const instance = (val as Function)(); if (typeof instance === 'string' && instance.includes('<')) { sections.push(instance); } else if (instance && typeof instance === 'object') { const obj = instance as Record; if (typeof obj.render === 'function') { const html = (obj.render as Function)(); if (typeof html === 'string') sections.push(html); } else if (typeof obj.renderHTML === 'function') { const html = (obj.renderHTML as Function)(); if (typeof html === 'string') sections.push(html); } } } catch { /* factory may require args */ } } } } catch { /* module may not have renderable exports */ } try { const uiMod = dashboardPage as Record; for (const key of Object.keys(uiMod)) { const val = uiMod[key]; // Look for factory functions that return objects with render/renderHTML if (typeof val === 'function' && /^create|^make|^render|^build/i.test(key)) { try { const instance = (val as Function)(); if (typeof instance === 'string' && instance.includes('<')) { sections.push(instance); } else if (instance && typeof instance === 'object') { const obj = instance as Record; if (typeof obj.render === 'function') { const html = (obj.render as Function)(); if (typeof html === 'string') sections.push(html); } else if (typeof obj.renderHTML === 'function') { const html = (obj.renderHTML as Function)(); if (typeof html === 'string') sections.push(html); } } } catch { /* factory may require args */ } } } } catch { /* module may not have renderable exports */ } try { const uiMod = taskListDisplay as Record; for (const key of Object.keys(uiMod)) { const val = uiMod[key]; // Look for factory functions that return objects with render/renderHTML if (typeof val === 'function' && /^create|^make|^render|^build/i.test(key)) { try { const instance = (val as Function)(); if (typeof instance === 'string' && instance.includes('<')) { sections.push(instance); } else if (instance && typeof instance === 'object') { const obj = instance as Record; if (typeof obj.render === 'function') { const html = (obj.render as Function)(); if (typeof html === 'string') sections.push(html); } else if (typeof obj.renderHTML === 'function') { const html = (obj.renderHTML as Function)(); if (typeof html === 'string') sections.push(html); } } } catch { /* factory may require args */ } } } } catch { /* module may not have renderable exports */ } return ` Web Dashboard
${sections.join('\n')}
`; } // ─── Router ────────────────────────────────────────────────────────────────── type Handler = (req: IncomingMessage, res: ServerResponse) => void | Promise; const routes: Record = { '/': (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(renderPage()); }, '/health': (_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok', service: 'Web Dashboard', uptime: Math.floor((Date.now() - _svcMetrics.uptime_start) / 1000), modules: Object.keys(_svcModules), })); }, '/metrics': (_req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ..._svcMetrics, uptime_seconds: Math.floor((Date.now() - _svcMetrics.uptime_start) / 1000), }, null, 2)); }, '/modules': (_req, res) => { const info = Object.entries(_svcModules).map(([name, mod]) => { const phoenix = (mod as Record)._phoenix as Record | undefined; return { name, risk_tier: phoenix?.risk_tier ?? 'unknown', exports: Object.keys(mod).filter(k => k !== '_phoenix'), }; }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(info, null, 2)); }, }; // ─── Server ────────────────────────────────────────────────────────────────── function handleRequest(req: IncomingMessage, res: ServerResponse): void { const url = req.url ?? '/'; const path = url.split('?')[0]; _svcMetrics.requests_total++; _svcMetrics.requests_by_path[path] = (_svcMetrics.requests_by_path[path] ?? 0) + 1; const handler = routes[path]; if (handler) { try { handler(req, res); } catch (err) { _svcMetrics.errors_total++; res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: String(err) })); } } else { res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Not Found', path, available: Object.keys(routes), })); } } export function startServer(port?: number): { server: ReturnType; port: number; ready: Promise } { const requestedPort = port ?? parseInt(process.env.WEB_DASHBOARD_PORT ?? process.env.PORT ?? '3002', 10); const server = createServer(handleRequest); let actualPort = requestedPort; const ready = new Promise(resolve => { server.listen(requestedPort, () => { const addr = server.address(); if (addr && typeof addr === 'object') actualPort = addr.port; result.port = actualPort; console.log(`Web Dashboard listening on http://localhost:${actualPort}`); console.log(` / — web client`); console.log(` /health — health check`); console.log(` /metrics — request metrics`); console.log(` /modules — registered modules`); resolve(); }); }); const result = { server, port: actualPort, ready }; return result; } // Start when run directly const isMain = process.argv[1]?.endsWith('/web-dashboard/server.js') || process.argv[1]?.endsWith('/web-dashboard/server.ts'); if (isMain) { startServer(); }