Generates the nginx rules for prerendered pages

Pages now map to their html file, other forms get one redirect, unknown URLs
get a real 404 and responses are compressed. A browser-free test suite runs the
rules against a real nginx, in CI only so far.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 03:00:07 +01:00
co-authored by Claude Opus 5.5
parent 4f32042410
commit 33334b889d
16 changed files with 1389 additions and 36 deletions
+88
View File
@@ -0,0 +1,88 @@
import { randomBytes } from 'node:crypto';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { pagePaths } from '../../config/canonicalUrls.ts';
import { NOT_FOUND_FILE, pageFile } from '../../config/pageFiles.ts';
// Een kleine site in de tijdelijke map met dezelfde vorm als dist/client, voor
// de serverregeltests: elk paginabestand, de map soorten-fotoshoots/ naast
// soorten-fotoshoots.html (BR-HST-07) en assets met hoofdletters in de naam.
// Zo hangen die tests niet af van een build.
export interface FixtureSite {
dir: string;
// Bestand (relatief aan dir) naar de tekst die erin staat, zodat een test
// aan het antwoord kan zien welk bestand geserveerd is
markers: ReadonlyMap<string, string>;
remove(): Promise<void>;
}
// Alles boven de 256 bytes van gzip_min_length, anders blijft het onbewerkt
const padding = ' vulling'.repeat(80);
export const markerOf = (file: string) => `fixture:${file}`;
export async function createFixtureSite(): Promise<FixtureSite> {
const dir = await mkdtemp(join(tmpdir(), 'andreaslop-fixture-'));
const markers = new Map<string, string>();
const write = async (file: string, content: string | Buffer) => {
const target = join(dir, file);
await mkdir(dirname(target), { recursive: true });
await writeFile(target, content);
};
const writeMarked = async (
file: string,
wrap: (text: string) => string,
) => {
markers.set(file, markerOf(file));
await write(file, wrap(markerOf(file)));
};
for (const path of [...pagePaths, null]) {
const file = path === null ? NOT_FOUND_FILE : pageFile(path);
await writeMarked(
file,
(marker) =>
`<!doctype html><html><body><p>${marker}</p><!--${padding}--></body></html>`,
);
}
await writeMarked(
'robots.txt',
(marker) => `${marker}\nUser-agent: *\nAllow: /\n`,
);
await writeMarked(
'sitemap.xml',
(marker) =>
`<?xml version="1.0"?><urlset><!--${marker}${padding}--></urlset>`,
);
await write('favicon.png', randomBytes(64));
await writeMarked(
'assets/index-AbC123xYz.js',
(marker) => `// ${marker}\n${'console.log("regel");\n'.repeat(200)}`,
);
await writeMarked(
'assets/style-Qw9.css',
(marker) => `/* ${marker} */\n${'.a{color:red}\n'.repeat(200)}`,
);
await writeMarked(
'assets/icon-Zz1.svg',
(marker) =>
`<svg xmlns="http://www.w3.org/2000/svg"><!--${marker}${padding}--></svg>`,
);
await writeMarked('assets/data.json', (marker) =>
JSON.stringify({ marker, vulling: padding }),
);
await writeMarked(
'assets/readme.txt',
(marker) => `${marker}\n${'tekst\n'.repeat(200)}`,
);
await write('assets/font-Ab.woff2', randomBytes(2048));
return {
dir,
markers,
remove: () => rm(dir, { recursive: true, force: true }),
};
}
+206
View File
@@ -0,0 +1,206 @@
import { execFile, spawn, type ChildProcess } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { nginxTestConf } from '../../config/serverConfig.ts';
// Start een echte, onbevoorrechte nginx met het gegenereerde testblok
// (BR-HST-24). Alleen voor de serverregeltests: eigen prefixmap, eigen poort,
// geen systeemconfiguratie.
const execFileAsync = promisify(execFile);
// Waar nginx kan staan: NGINX_BIN, het PATH, de twee bekende Windows-plekken
const windowsPaths = [
'C:\\nginx\\nginx.exe',
'C:\\Users\\Bryan\\scoop\\apps\\nginx\\current\\nginx.exe',
];
export function findNginx(): string | undefined {
const fromEnv = process.env.NGINX_BIN;
if (fromEnv) return existsSync(fromEnv) ? fromEnv : undefined;
const names = process.platform === 'win32' ? ['nginx.exe'] : ['nginx'];
const separator = process.platform === 'win32' ? ';' : ':';
for (const dir of (process.env.PATH ?? '').split(separator)) {
for (const name of names) {
if (dir && existsSync(join(dir, name))) return join(dir, name);
}
}
// Op Linux staat nginx soms in sbin, buiten het PATH van een gebruiker
for (const path of ['/usr/sbin/nginx', ...windowsPaths]) {
if (existsSync(path)) return path;
}
return undefined;
}
// nginx 1.24 kent .js als application/javascript, vanaf 1.25.2 als
// text/javascript (de Pi draait 1.30.6). Beide tabellen worden getest.
export type MimeVariant = 'new' | 'old';
const mimeTable = (variant: MimeVariant) => `types {
text/html html;
text/css css;
${variant === 'old' ? 'application/javascript' : 'text/javascript'} js;
image/svg+xml svg;
application/json json;
text/xml xml;
text/plain txt;
image/png png;
font/woff2 woff2;
}`;
// Alle nog lopende instanties, voor het opruimen als het proces stopt
const running = new Set<{ child: ChildProcess; tmp: string }>();
process.on('exit', () => {
for (const { child, tmp } of running) {
child.kill();
try {
rmSync(tmp, { recursive: true, force: true });
} catch {
// Opruimen bij afsluiten mag falen
}
}
});
// nginx onder Windows wil voorwaartse slashes in de configuratie
const slashed = (path: string) => path.replace(/\\/g, '/');
async function freePort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = createServer();
probe.once('error', reject);
probe.listen(0, '127.0.0.1', () => {
const address = probe.address();
probe.close(() =>
typeof address === 'object' && address
? resolve(address.port)
: reject(new Error('geen poort gekregen')),
);
});
});
}
export interface RunningNginx {
origin: string;
version: string;
stop(): Promise<void>;
}
export async function startNginx(options: {
siteDir: string;
mimeVariant?: MimeVariant;
}): Promise<RunningNginx> {
const bin = findNginx();
if (!bin) throw new Error('nginx niet gevonden');
const { mimeVariant = 'new' } = options;
const tmp = await mkdtemp(join(tmpdir(), 'andreaslop-nginx-'));
const port = await freePort();
const serverFile = join(tmp, 'andreaslop-test.conf');
const confFile = join(tmp, 'nginx.conf');
const errorLog = join(tmp, 'error.log');
const temp = (name: string) => `"${slashed(join(tmp, name))}"`;
await writeFile(
serverFile,
nginxTestConf({
listen: `127.0.0.1:${port}`,
root: slashed(options.siteDir),
}),
);
await writeFile(
confFile,
`daemon off;
pid "${slashed(join(tmp, 'nginx.pid'))}";
error_log "${slashed(errorLog)}";
events {}
http {
${mimeTable(mimeVariant)}
client_body_temp_path ${temp('client_body')};
proxy_temp_path ${temp('proxy')};
fastcgi_temp_path ${temp('fastcgi')};
uwsgi_temp_path ${temp('uwsgi')};
scgi_temp_path ${temp('scgi')};
access_log off;
include "${slashed(serverFile)}";
}
`,
);
// nginx -v schrijft naar stderr
const { stdout, stderr } = await execFileAsync(bin, ['-v']);
const version = (stdout + stderr).trim();
await execFileAsync(bin, [
'-t',
'-p',
`${slashed(tmp)}/`,
'-c',
slashed(confFile),
'-e',
slashed(errorLog),
]).catch((error: { stderr?: string }) => {
throw new Error(`nginx -t keurt de configuratie af:\n${error.stderr}`);
});
const child = spawn(
bin,
[
'-p',
`${slashed(tmp)}/`,
'-c',
slashed(confFile),
'-e',
slashed(errorLog),
],
{ stdio: 'ignore' },
);
const entry = { child, tmp };
running.add(entry);
let exited = false;
child.once('exit', () => {
exited = true;
});
const stop = async () => {
if (!exited) {
const done = new Promise<void>((resolve) =>
child.once('exit', () => resolve()),
);
child.kill();
// Mocht nginx op SIGTERM niet reageren, dan alsnog hard stoppen
const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
await done;
clearTimeout(timer);
}
running.delete(entry);
await rm(tmp, { recursive: true, force: true });
};
const origin = `http://127.0.0.1:${port}`;
const deadline = Date.now() + 5000;
for (;;) {
if (exited) {
const log = existsSync(errorLog)
? readFileSync(errorLog, 'utf8')
: '(geen foutlog)';
await stop();
throw new Error(`nginx stopte bij het starten:\n${log}`);
}
try {
await fetch(origin + '/');
break;
} catch {
if (Date.now() > deadline) {
await stop();
throw new Error('nginx antwoordde niet binnen 5 seconden');
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
}
return { origin, version, stop };
}