// Pre-compress the big boot payloads beside themselves: .br (brotli) and .gz (gzip -9). // The image server serves .br / .gz with Content-Encoding when the client accepts it. // Usage: node precompress.mjs [dist-dir] (skips files whose .br is newer than the source) import { brotliCompressSync, gzipSync, constants } from 'node:zlib'; import { readdirSync, statSync, readFileSync, writeFileSync, existsSync } from 'node:fs'; import { join } from 'node:path'; const root = process.argv[2] || new URL('./dist/', import.meta.url).pathname; const MIN = 256 * 1024; // only worth it for big payloads const want = (p) => !/\.(html|json|webmanifest|svg|png|bak)$/.test(p); // every big payload: kernels, libs, inits, bundles function walk(d, out = []) { for (const e of readdirSync(d, { withFileTypes: true })) { const p = join(d, e.name); if (e.isDirectory()) walk(p, out); else out.push(p); } return out; } let n = 0, inB = 0, brB = 0, gzB = 0; for (const p of walk(root)) { if (p.endsWith('.br') || p.endsWith('.gz')) continue; const st = statSync(p); if (st.size < MIN || !want(p)) continue; const br = p + '.br', gz = p + '.gz'; if (existsSync(br) && statSync(br).mtimeMs >= st.mtimeMs && existsSync(gz) && statSync(gz).mtimeMs >= st.mtimeMs) continue; const src = readFileSync(p); const t0 = Date.now(); const b = brotliCompressSync(src, { params: { [constants.BROTLI_PARAM_QUALITY]: 9, [constants.BROTLI_PARAM_SIZE_HINT]: src.length, [constants.BROTLI_PARAM_LGWIN]: 24 } }); const g = gzipSync(src, { level: 9 }); writeFileSync(br, b); writeFileSync(gz, g); n++; inB += src.length; brB += b.length; gzB += g.length; console.log(`${p.replace(root, '')}: ${(src.length / 1048576).toFixed(1)} MB -> br ${(b.length / 1048576).toFixed(1)} MB, gz ${(g.length / 1048576).toFixed(1)} MB (${Date.now() - t0} ms)`); } console.log(`compressed ${n} files: ${(inB / 1048576).toFixed(1)} MB -> br ${(brB / 1048576).toFixed(1)} MB (${(100 * brB / (inB || 1)).toFixed(0)}%), gz ${(gzB / 1048576).toFixed(1)} MB`);