51 lines
2.5 KiB
JavaScript
51 lines
2.5 KiB
JavaScript
import { build } from 'esbuild';
|
|
import { existsSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
|
|
import { join, relative, resolve, sep } from 'node:path';
|
|
|
|
const walk = dir => readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
|
|
entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)]);
|
|
|
|
// Version the entire application module graph, including lazy imports. Versioning
|
|
// only an HTML entry does not invalidate its unversioned dependencies in browsers.
|
|
export async function versionSiteAssets(root, buildId, pages) {
|
|
root = realpathSync(root);
|
|
const jsRoot = join(root, 'js');
|
|
const version = url => {
|
|
const parsed = new URL(url, 'https://build.invalid/');
|
|
parsed.searchParams.set('v', buildId);
|
|
return url.split(/[?#]/)[0] + parsed.search + parsed.hash;
|
|
};
|
|
const files = walk(jsRoot).filter(file => file.endsWith('.js'));
|
|
const result = await build({
|
|
entryPoints: files, outdir: jsRoot, outbase: jsRoot,
|
|
bundle: true, format: 'esm', write: false, treeShaking: false,
|
|
minify: false, charset: 'utf8', logLevel: 'silent',
|
|
plugins: [{ name: 'version-app-imports', setup(builder) {
|
|
builder.onResolve({ filter: /.*/ }, args => {
|
|
if (args.kind === 'entry-point') return;
|
|
const path = args.path.split(/[?#]/)[0];
|
|
if (path.startsWith('.') || path.startsWith('/')) {
|
|
const target = path.startsWith('/') ? resolve(root, '.' + path) : resolve(args.resolveDir, path);
|
|
const rel = relative(jsRoot, target);
|
|
if (!rel.startsWith('..' + sep) && !rel.startsWith(sep) && target.endsWith('.js')) {
|
|
if (!existsSync(target)) throw new Error(`Missing application module: ${args.path} in ${args.importer}`);
|
|
return { path: version(args.path), external: true };
|
|
}
|
|
}
|
|
// Keep import-map entries and vendor URLs identical: Three must remain
|
|
// a single shared instance across the viewers and their addons.
|
|
return { path: args.path, external: true };
|
|
});
|
|
} }],
|
|
});
|
|
for (const output of result.outputFiles) writeFileSync(output.path, output.contents);
|
|
for (const page of pages) {
|
|
const file = join(root, page);
|
|
const html = readFileSync(file, 'utf8').replace(
|
|
/(<(?:script|link)\b[^>]*?\b(?:src|href)\s*=\s*)(["'])(\/?(?:js\/[^"']+\.js|css\/[^"']+\.css)(?:\?[^"'#]*)?(?:#[^"']*)?)\2/gi,
|
|
(_, prefix, quote, url) => `${prefix}${quote}${version(url)}${quote}`,
|
|
);
|
|
writeFileSync(file, html);
|
|
}
|
|
}
|