Files
romm/frontend/scripts/precompress.ts
Sam Dornan 1f231c84f4 test(precompress): close the gaps the review found in the gzip_static guards
The nginx guard only read the http-level default.conf and the three raw
location bodies, so two ways of reintroducing the ROM-corruption bug went
undetected. Both were confirmed against the suite before this change, each
leaving all seven tests green:

- gzip_static added at server scope in the template, with the locations left
  intact: /library/ and /cache/ inherit it, and a request for Game.nes returns
  Game.nes.gz's bytes.
- gzip_static removed from the fingerprinted-assets regex location, which the
  parametrised list never covered, silently dropping precompressed bundles.

Parse the template's location blocks instead, honouring braces inside the
quoted regex matcher, and assert against server scope, each build-output
location including the regex one, and any location that gains the directive.
A prefix match would have let /assets/romm/resources/ pass as expected, so
matchers resolve exactly and only the regex is keyed by its opening.

Also tie MIN_BYTES to nginx's gzip_min_length with a test rather than a
comment, cover the "gzip made it bigger" branch that the extension filter
kept unreachable, drop an em dash, and correct a comment that claimed every
file without a .gz sibling is gzipped on the fly, which is untrue for types
outside gzip_types.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HDXxq3vAxJVGhm1pQuK8V7
2026-09-12 04:49:06 +00:00

90 lines
2.7 KiB
TypeScript

/**
* precompress: a build plugin that writes a .gz sibling for each built asset.
*
* nginx serves these directly via `gzip_static`, so the bundle is compressed
* once at build time rather than on every cold page load.
*
* Level 9 is affordable because it runs once. The ratio lands within a percent
* of what nginx produces at runtime, so the win is the CPU, not the bytes.
* A file without a .gz sibling is served normally, gzipped on the fly only
* if its type is in nginx's gzip_types.
*/
import { readdir, readFile, stat, writeFile } from "node:fs/promises";
import { extname, join, resolve } from "node:path";
import { constants, gzipSync } from "node:zlib";
import type { Plugin } from "vite";
// gzip_static serves a .gz sibling whatever gzip_types says, so this list alone
// decides what is precompressed. Already-compressed formats only grow.
const COMPRESSIBLE = new Set([
".css",
".html",
".js",
".json",
".map",
".mjs",
".svg",
".txt",
".wasm",
".webmanifest",
".xml",
]);
// Must equal nginx's gzip_min_length, or the precompressed set stops matching
// what the server will serve. test_static_precompression.py asserts they agree.
const MIN_BYTES = 1024;
async function* walk(dir: string): AsyncGenerator<string> {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) yield* walk(path);
else if (entry.isFile()) yield path;
}
}
export function precompress(): Plugin {
let outDir = "";
return {
name: "romm:precompress",
apply: "build",
// `post` so the service worker vite-plugin-pwa emits is compressed too.
enforce: "post",
configResolved(config) {
outDir = resolve(config.root, config.build.outDir);
},
async closeBundle() {
let raw = 0;
let packed = 0;
let count = 0;
for await (const path of walk(outDir)) {
if (!COMPRESSIBLE.has(extname(path))) continue;
const { size } = await stat(path);
if (size < MIN_BYTES) continue;
const gzipped = gzipSync(await readFile(path), {
level: constants.Z_BEST_COMPRESSION,
});
// A .gz larger than its source would make nginx serve the worse one.
if (gzipped.byteLength >= size) continue;
await writeFile(`${path}.gz`, gzipped);
raw += size;
packed += gzipped.byteLength;
count += 1;
}
const mib = (bytes: number) => (bytes / 1024 ** 2).toFixed(1);
this.info(
count === 0
? "nothing to compress"
: `${count} files, ${mib(raw)} MiB -> ${mib(packed)} MiB ` +
`(${Math.round((1 - packed / raw) * 100)}% smaller)`,
);
},
};
}