// Static loopback server for a Flutter web build, on an OS-assigned port. // Extension-less paths (`/runs/7`) fall back to index.html, as the Pipelines // proxy serves the single page. import { createServer } from 'node:http'; import { readFile, stat } from 'node:fs/promises'; import { once } from 'node:events'; import { extname, join, resolve, sep } from 'node:path'; const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.wasm': 'application/wasm', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.ttf': 'font/ttf', '.otf': 'font/otf', '.woff': 'font/woff', '.woff2': 'font/woff2', }; /** Serves [dir]; resolves to `{ origin, close() }`. */ export async function serveBuild(dir) { const root = resolve(dir); if (!(await stat(join(root, 'index.html')).catch(() => null))) { throw new Error(`No index.html in ${root}; build the probe first (see README).`); } const server = createServer(async (req, res) => { try { const pathname = decodeURIComponent(new URL(req.url, 'http://x').pathname); let file = resolve(root, '.' + pathname); if (file !== root && !file.startsWith(root + sep)) return res.writeHead(403).end(); try { if ((await stat(file)).isDirectory()) file = join(file, 'index.html'); } catch { if (!extname(pathname)) file = join(root, 'index.html'); } const body = await readFile(file); res.writeHead(200, { 'content-type': MIME[extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store', }).end(body); } catch { res.writeHead(404).end('not found'); } }); server.listen(0, '127.0.0.1'); await once(server, 'listening'); return { origin: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((done) => { server.closeAllConnections?.(); server.close(() => done()); }), }; }