import express from 'express'; import path from 'node:path'; import client from './core/discord.js'; import { addSSEClient, removeSSEClient, sseBroadcast, getSSEClientCount } from './core/sse.js'; import { loadState, getFullState } from './core/persistence.js'; import { getPlugins, registerPlugin, PluginContext } from './core/plugin.js'; import radioPlugin from './plugins/radio/index.js'; // ── Config ── const PORT = Number(process.env.PORT ?? 8080); const DATA_DIR = process.env.DATA_DIR ?? '/data'; const DISCORD_TOKEN = process.env.DISCORD_TOKEN ?? ''; // ── Persistence ── loadState(); // ── Express ── const app = express(); app.use(express.json()); app.use(express.static(path.join(import.meta.dirname ?? __dirname, '..', '..', 'web', 'dist'))); // ── Plugin Context ── const ctx: PluginContext = { client, dataDir: DATA_DIR }; // ── SSE Events ── app.get('/api/events', (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', }); res.flushHeaders(); // Send snapshot from all plugins const snapshot: Record = { type: 'snapshot' }; for (const p of getPlugins()) { if (p.getSnapshot) { Object.assign(snapshot, p.getSnapshot(ctx)); } } try { res.write(`data: ${JSON.stringify(snapshot)}\n\n`); } catch {} const ping = setInterval(() => { try { res.write(':\n\n'); } catch {} }, 15_000); addSSEClient(res); _req.on('close', () => { removeSSEClient(res); clearInterval(ping); try { res.end(); } catch {} }); }); // ── Health ── app.get('/api/health', (_req, res) => { res.json({ status: 'ok', uptime: process.uptime(), plugins: getPlugins().map(p => ({ name: p.name, version: p.version })), sseClients: getSSEClientCount(), }); }); // ── API: List plugins ── app.get('/api/plugins', (_req, res) => { res.json(getPlugins().map(p => ({ name: p.name, version: p.version, description: p.description, }))); }); // NOTE: SPA fallback is added in boot() AFTER plugin routes // ── Discord Ready ── client.once('ready', async () => { console.log(`[Discord] Logged in as ${client.user?.tag}`); console.log(`[Discord] Serving ${client.guilds.cache.size} guild(s)`); for (const p of getPlugins()) { if (p.onReady) { try { await p.onReady(ctx); } catch (e) { console.error(`[Plugin:${p.name}] onReady error:`, e); } } } }); // ── Init Plugins ── async function boot(): Promise { // ── Register plugins ── registerPlugin(radioPlugin); // Init all plugins for (const p of getPlugins()) { try { await p.init(ctx); p.registerRoutes?.(app, ctx); console.log(`[Plugin:${p.name}] Initialized`); } catch (e) { console.error(`[Plugin:${p.name}] Init error:`, e); } } // SPA Fallback (MUST be after plugin routes) app.get('*', (_req, res) => { res.sendFile(path.join(import.meta.dirname ?? __dirname, '..', '..', 'web', 'dist', 'index.html')); }); // Start Express app.listen(PORT, () => console.log(`[HTTP] Listening on :${PORT}`)); // Login Discord if (DISCORD_TOKEN) { await client.login(DISCORD_TOKEN); } else { console.warn('[Discord] No DISCORD_TOKEN set - running without Discord'); } } // ── Graceful Shutdown ── async function shutdown(signal: string): Promise { console.log(`\n[${signal}] Shutting down...`); for (const p of getPlugins()) { if (p.destroy) { try { await p.destroy(ctx); } catch (e) { console.error(`[Plugin:${p.name}] destroy error:`, e); } } } client.destroy(); process.exit(0); } process.on('SIGTERM', () => shutdown('SIGTERM')); process.on('SIGINT', () => shutdown('SIGINT')); process.on('uncaughtException', (err) => { console.error('Uncaught:', err); }); process.on('unhandledRejection', (err) => { console.error('Unhandled:', err); }); process.on('warning', (w) => { if (w.name === 'TimeoutNegativeWarning') return; console.warn(w.name + ': ' + w.message); }); boot().catch(console.error);