Files
Rosea/e2e/static-server.ts

106 lines
3.7 KiB
TypeScript

import { createReadStream, statSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { extname, join, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* A throwaway static server for the BUILT app, under the test's control.
*
* It serves `apps/rosea/dist` under the same base path GitHub Pages will use
* (`/Rosea/` unless ROSEA_BASE says otherwise), and 404s everything outside it.
* Serving at `/` would hide every base-path bug (CLAUDE.md §8).
*
* It exists for the offline suite too. Playwright's `context.setOffline` and
* `route().abort()` both act before the service worker is consulted, so they
* test the harness and not the cache (imported from Ludus). The only honest
* "no network" is no server: start one, let the worker precache, close it.
*
* Binds 127.0.0.1 on port 0, so the OS picks a free port (CLAUDE.md §5.7).
*/
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
export const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.webmanifest': 'application/manifest+json; charset=utf-8',
'.svg': 'image/svg+xml',
'.map': 'application/json; charset=utf-8'
};
export interface StaticServer {
/** The app's URL, base path included, e.g. http://127.0.0.1:53211/Rosea/ */
readonly url: string;
readonly origin: string;
readonly close: () => Promise<void>;
/** Serves another build from now on, at the same URL: a new version being published. */
readonly serveFrom: (dir: string) => void;
}
export async function startStaticServer(): Promise<StaticServer> {
try {
statSync(join(DIST, 'index.html'));
} catch (error) {
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
}
let root = DIST;
const server: Server = createServer((req, res) => {
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
if (!path.startsWith(BASE)) {
res.writeHead(404, { 'content-type': 'text/plain' });
res.end(`outside ${BASE}`);
return;
}
const rel = normalize(path.slice(BASE.length) || 'index.html');
const file = join(root, rel);
// Confine to the served folder: a test server is still a server.
if (!file.startsWith(root + sep) && file !== root) {
res.writeHead(403).end();
return;
}
let target = file;
try {
if (statSync(target).isDirectory()) target = join(target, 'index.html');
statSync(target);
} catch {
// Not on disk: an honest 404, which is what Pages would send.
res.writeHead(404, { 'content-type': 'text/plain' });
res.end('not found');
return;
}
res.writeHead(200, {
'content-type': MIME[extname(target)] ?? 'application/octet-stream',
// No HTTP cache, so whatever loads after the server is gone came from the
// service worker and not from the browser's own cache.
'cache-control': 'no-store'
});
createReadStream(target).pipe(res);
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (address === null || typeof address === 'string') throw new Error('static server did not bind a port');
const origin = `http://127.0.0.1:${address.port}`;
return {
origin,
url: `${origin}${BASE}`,
serveFrom: (dir) => {
root = dir;
},
close: () =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
})
};
}