// Courtside server entry point. One process: HTTP pages + WebSocket fan-out + SQLite. import { createServer } from 'node:http'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; import { WebSocketServer } from 'ws'; import { Store } from './store.js'; import { Registry } from './state.js'; import { Auth } from './auth.js'; import { buildRouter } from './routes.js'; import { HttpError, send, serveStatic } from './http.js'; import { publicState } from './public-state.js'; const here = dirname(fileURLToPath(import.meta.url)); const env = process.env; const PORT = Number(env.PORT ?? 3000); const HOST = env.HOST ?? '0.0.0.0'; const DB_PATH = env.DB_PATH ?? join(here, '..', 'data', 'courtside.sqlite'); const store = new Store(DB_PATH); const registry = new Registry(store); const auth = new Auth({ password: env.ADMIN_PASSWORD, secret: env.SESSION_SECRET, trustCfAccess: env.TRUST_CF_ACCESS === 'true' }); const router = buildRouter({ registry, auth, store }); const staticRoot = join(here, 'public'); const server = createServer(async (req, res) => { const url = new URL(req.url, 'http://x'); try { if (url.pathname.startsWith('/static/')) return await serveStatic(res, staticRoot, url.pathname.slice('/static'.length), url.searchParams.has('v')); const m = router.match(req.method, url.pathname); if (!m) throw new HttpError(404, 'Not found'); await m.handler(req, res, m.params); } catch (e) { const status = e instanceof HttpError ? e.status : 500; if (status === 500) console.error(`[${new Date().toISOString()}] ${req.method} ${req.url}`, e); if (!res.headersSent) send.html(res, `
${escape(e.message)}
`, status); else res.end(); } }); // ---------- WebSocket: /ws/