import type { Database } from "bun:sqlite"; import type { Message } from "./db"; import index from "./index.html"; // The whole app: an HTML page, a JSON API, and a WebSocket that pushes // new messages to every open page. export function startServer(db: Database, port: number) { const sockets = new Set>(); const list = db.query("SELECT * FROM messages ORDER BY id DESC LIMIT 50"); const insert = db.query("INSERT INTO messages (author, body) VALUES (?, ?) RETURNING *"); const server = Bun.serve({ port, development: process.env.NODE_ENV !== "production" && { hmr: true, console: true }, routes: { "/": index, "/healthz": new Response("ok"), "/api/messages": { GET: () => Response.json(list.all()), POST: async (req, server) => { const { body } = (await req.json().catch(() => ({}))) as { body?: unknown }; const text = String(body ?? "").trim().slice(0, 280); if (!text) return Response.json({ error: "body is required" }, { status: 400 }); // exe.dev's proxy says who is signed in, and strips this header from visitors. const email = req.headers.get("x-exedev-email"); const author = email ? email.split("@")[0]! : "a visitor"; const message = insert.get(author, text) as Message; server.publish("messages", JSON.stringify(message)); return Response.json(message, { status: 201 }); }, }, "/ws": (req, server) => server.upgrade(req) ? undefined : new Response("WebSocket expected", { status: 400 }), }, websocket: { open(ws) { sockets.add(ws); ws.subscribe("messages"); }, close(ws) { sockets.delete(ws); }, message() {}, }, }); // Close open WebSockets ("going away"; pages reconnect), then let // requests in flight finish. server.stop() alone waits for every socket. async function stop() { for (const ws of sockets) ws.close(1001, "Server restarting"); await server.stop(); } return { server, stop }; }