// The web's own server (PEP-225): Next.js 16 does not accept WebSockets, so this wraps it — // plain HTTP goes to Next, `upgrade` on /api/ws to the tab's live channel that // instrumentation.ts registered (lib/live-server.ts), other upgrades (dev HMR) to Next. // Usage: node server.ts [--dev] [-p 3100] import { createServer } from "node:http"; import type { Duplex } from "node:stream"; const dev = process.argv.includes("--dev"); const pIdx = process.argv.indexOf("-p"); const port = Number(pIdx > 0 ? process.argv[pIdx + 1] : (process.env.PORT ?? 3100)); const env = process.env as Record; env.NODE_ENV ??= dev ? "development" : "production"; const { default: next } = await import("next"); const app = next({ dev, dir: import.meta.dirname, port, hostname: "localhost" }); const handle = app.getRequestHandler(); await app.prepare(); const nextUpgrade = app.getUpgradeHandler(); type LiveWs = { handleUpgrade(req: import("node:http").IncomingMessage, socket: Duplex, head: Buffer): void }; const live = () => (globalThis as { __peppaLiveWs?: LiveWs }).__peppaLiveWs; const server = createServer((req, res) => void handle(req, res)); server.on("upgrade", (req, socket: Duplex, head: Buffer) => { if (req.url?.split("?")[0] === "/api/ws") { const ws = live(); if (ws) return ws.handleUpgrade(req, socket, head); socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); return; } void nextUpgrade(req, socket, head); }); server.listen(port, () => console.log(`peppa web: http://localhost:${port} (${dev ? "dev" : "production"}, WebSocket /api/ws)`)); const shutdown = () => { server.close(); setTimeout(() => process.exit(0), 3000).unref(); }; process.on("SIGTERM", shutdown); process.on("SIGINT", shutdown);