// Universal test fixture: a tiny node:http server. Tests are // run-only (not shipped); importing node:http here is permitted in the // `tests/` directory which is excluded from tier-purity checks in // `src/`. The src tree stays universal. import { createServer, type IncomingMessage, type Server, type ServerResponse, } from "node:http"; export type RouteHandler = ( req: IncomingMessage, res: ServerResponse ) => void | Promise; export interface FixtureServer { readonly url: string; readonly port: number; close(): Promise; } /** * Stand up a localhost `node:http` server with the given route handler. * The returned `url` ends with `/` so it can be used as a `rootUrl`. */ export async function startFixtureServer( handler: RouteHandler ): Promise { const server: Server = createServer((req, res) => { try { const out = handler(req, res); if (out !== undefined) { void Promise.resolve(out).catch((err) => { res.statusCode = 500; res.end(String(err)); }); } } catch (err) { res.statusCode = 500; res.end(String(err)); } }); await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve()) ); const addr = server.address(); if (addr === null || typeof addr === "string") { throw new Error("fixture server did not bind to a TCP port"); } const port = addr.port; return { url: `http://127.0.0.1:${port}/`, port, close: () => new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())) ), }; }