#!/usr/bin/env node // Writes brotli (.br) and gzip (.gz) siblings for the compressible files of a // Flutter web build, which the web proxy sends to browsers that accept them // (web/src/appFiles.js). Run once per build by scripts/app_build.py: // // node scripts/precompress_web.mjs // // A variant is kept only when it saves at least a tenth of the file. import { readdir, readFile, stat, writeFile } from "node:fs/promises"; import { extname, join } from "node:path"; import { promisify } from "node:util"; import { brotliCompress, constants, gzip } from "node:zlib"; const COMPRESSIBLE = new Set([".js", ".mjs", ".wasm", ".json", ".ttf", ".otf", ".html", ".css", ".svg", ".txt", ".frag", ".bin"]); // Flutter's licence notices have no extension. const NAMED = new Set(["NOTICES"]); const MIN_BYTES = 1024; const brotli = promisify(brotliCompress); const gz = promisify(gzip); async function* files(dir) { for (const entry of await readdir(dir, { withFileTypes: true })) { const path = join(dir, entry.name); if (entry.isDirectory()) yield* files(path); else if (entry.isFile()) yield path; } } async function compress(path) { const body = await readFile(path); const [br, gzipped] = await Promise.all([ brotli(body, { params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY, [constants.BROTLI_PARAM_SIZE_HINT]: body.length, }, }), gz(body, { level: 9 }), ]); let saved = 0; for (const [suffix, data] of [[".br", br], [".gz", gzipped]]) { if (data.length > body.length * 0.9) continue; await writeFile(path + suffix, data); saved = Math.max(saved, body.length - data.length); } return { size: body.length, saved }; } const root = process.argv[2]; if (!root) { console.error("usage: precompress_web.mjs "); process.exit(2); } const work = []; for await (const path of files(root)) { const name = path.split(/[\\/]/).pop(); if (!(COMPRESSIBLE.has(extname(path).toLowerCase()) || NAMED.has(name))) continue; if ((await stat(path)).size < MIN_BYTES) continue; work.push(path); } // zlib's async calls run on libuv's thread pool, a few at a time. let size = 0; let saved = 0; for (let i = 0; i < work.length; i += 4) { for (const result of await Promise.all(work.slice(i, i + 4).map(compress))) { size += result.size; saved += result.saved; } } console.log(`Precompressed ${work.length} files: ${(size / 1e6).toFixed(1)} MB, ${(saved / 1e6).toFixed(1)} MB smaller with brotli.`);