Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 177 additions & 7 deletions scripts/measure-reference-pages.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
* @output Each reference page's first-load JavaScript, minified and
* gzip, its static module graph (modules reached and kept, module depth)
* and this build's chunks (count, depth), base against head, with the
* deltas. With `--unused-on`, a pass or fail line per named page against
* INV10's 0.3 KB limit. `--json` prints the same as JSON
* deltas. `--bundler rolldown` builds each page with Vite (Rolldown) and
* keeps the esbuild sizes beside it. With `--unused-on`, a pass or fail
* line per named page against INV10's 0.3 KB limit, on the sizes of the
* chosen bundler. `--json` prints the same as JSON
* @position Run by people and review agents with `pnpm size:pages`; not a CI
* job. Builds each page with the size report's esbuild options
* (.github/scripts/lib/component-size.js), as the import-boundaries check
Expand Down Expand Up @@ -74,6 +76,7 @@ const pick = ({
moduleDepth,
chunks,
depth,
esbuild,
}) => ({
min,
gzip,
Expand All @@ -82,6 +85,7 @@ const pick = ({
moduleDepth,
chunks,
depth,
...(esbuild === undefined ? {} : {esbuild}),
});

/**
Expand All @@ -102,6 +106,14 @@ export function comparePages(base, head, {unusedOn = []} = {}) {
moduleDepth: head[page].moduleDepth - base[page].moduleDepth,
chunks: head[page].chunks - base[page].chunks,
depth: head[page].depth - base[page].depth,
...(head[page].esbuild === undefined
? {}
: {
esbuild: {
min: head[page].esbuild.min - base[page].esbuild.min,
gzip: head[page].esbuild.gzip - base[page].esbuild.gzip,
},
}),
},
}));
const verdicts = unusedOn.map(name => {
Expand Down Expand Up @@ -136,9 +148,13 @@ function size({min, gzip}) {
}

/** The comparison as a Markdown table and one line per verdict. */
export function formatComparison({pages, verdicts}, {base, head}) {
export function formatComparison(
{pages, verdicts},
{base, head, bundler = 'esbuild'},
) {
const built = bundler === 'rolldown' ? ', built by Vite with Rolldown' : '';
const lines = [
`First-load JavaScript per reference page (minified / gzip bytes), ${base} → ${head}:`,
`First-load JavaScript per reference page${built} (minified / gzip bytes), ${base} → ${head}:`,
'',
'| Page (components) | Base | Head | Change |',
'| --- | ---: | ---: | ---: |',
Expand Down Expand Up @@ -167,6 +183,19 @@ export function formatComparison({pages, verdicts}, {base, head}) {
`| ${row.page} | ${shape(row.base)} | ${shape(row.head)} | ${signed(row.delta.chunks)} / ${signed(row.delta.depth)} |`,
),
);
if (pages.some(row => row.head.esbuild !== undefined)) {
lines.push(
'',
'The same pages built by esbuild with code splitting, for the earlier trend (minified / gzip bytes):',
'',
'| Page | Base | Head | Change |',
'| --- | ---: | ---: | ---: |',
...pages.map(
row =>
`| ${row.page} | ${size(row.base.esbuild)} | ${size(row.head.esbuild)} | ${signed(row.delta.esbuild.min)} / ${signed(row.delta.esbuild.gzip)} |`,
),
);
}
if (verdicts.length > 0) lines.push('');
for (const verdict of verdicts) {
lines.push(
Expand Down Expand Up @@ -397,14 +426,141 @@ export async function measurePage(distDir, components) {
};
}

async function measurePages(distDir, pages) {
/** Whether `id` is a package the app brings itself (`APP_EXTERNALS`). */
function isAppExternal(id) {
return APP_EXTERNALS.some(pattern =>
pattern.endsWith('/*')
? id.startsWith(pattern.slice(0, -1))
: id === pattern,
);
}

/**
* Rolldown's output chunks in the shape of an esbuild metafile's `outputs`,
* so the shared walks read both builds alike: each chunk's static and
* dynamic imports, and each module's rendered bytes as `bytesInOutput`.
* Modules without a file path (a bundler's virtual helpers) are left out of
* `inputs`.
*/
export function rolldownOutputs(output) {
const outputs = {};
const textByPath = new Map();
let entryOutput;
const chunks = output.filter(item => item.type === 'chunk');
const files = new Set(chunks.map(chunk => chunk.fileName));
// A chunk's imports also name the packages the build leaves external.
const edge = kind => file => ({
path: file,
kind,
...(files.has(file) ? {} : {external: true}),
});
for (const chunk of chunks) {
if (chunk.isEntry) entryOutput = chunk.fileName;
textByPath.set(chunk.fileName, chunk.code);
outputs[chunk.fileName] = {
imports: [
...(chunk.imports ?? []).map(edge('import-statement')),
...(chunk.dynamicImports ?? []).map(edge('dynamic-import')),
],
inputs: Object.fromEntries(
Object.entries(chunk.modules ?? {})
.filter(([id]) => !id.startsWith('\0'))
.map(([id, module]) => [id, {bytesInOutput: module.renderedLength}]),
),
};
}
if (entryOutput === undefined) {
throw new Error('The Rolldown build has no entry chunk.');
}
return {outputs, textByPath, entryOutput};
}

/**
* What a page loads up front in a Rolldown build: the entry chunk and the
* chunks it imports statically, as `min` and `gzip` bytes, `keptModules`,
* `chunks` and `depth`, by the same walks as the esbuild figures. `import()`
* targets load later, so they are not part of it.
*/
export function rolldownPageStats(output, entryModule) {
const {outputs, textByPath, entryOutput} = rolldownOutputs(output);
const text = eagerText(outputs, textByPath, entryOutput);
return {
min: Buffer.byteLength(text),
gzip: gzipBytes(text),
keptModules: keptModuleCount(outputs, entryOutput, entryModule),
...chunkGraphStats(outputs, entryOutput),
};
}

/**
* One page as a production Vite app bundle, built by Rolldown, as a consumer
* of the built package ships it: Vite's defaults, module preload included.
*/
export async function measurePageRolldown(distDir, components) {
const {build} = await import('vite');
const root = path.dirname(distDir);
// The dist resolves Core's own dependencies from the side's root.
const modules = path.join(root, 'node_modules');
if (!fs.existsSync(modules)) {
fs.symlinkSync(path.join(REPO, CORE, 'node_modules'), modules);
}
const entryModule = path.join(root, '__astryx-reference-page-rolldown__.mjs');
fs.writeFileSync(
entryModule,
components
.map(
name =>
`export {${name}} from ${JSON.stringify(componentModule(distDir, name))};`,
)
.join('\n'),
);
const result = await build({
root,
configFile: false,
logLevel: 'silent',
mode: 'production',
build: {
write: false,
minify: true,
rolldownOptions: {
input: entryModule,
external: isAppExternal,
preserveEntrySignatures: 'strict',
},
},
});
const {output} = Array.isArray(result) ? result[0] : result;
return rolldownPageStats(output, entryModule);
}

/**
* Each page's figures. With Rolldown, its build gives the up-front sizes,
* kept modules and chunks, and the esbuild figures stay under `esbuild`,
* so the esbuild trend stays readable.
*/
async function measurePages(distDir, pages, bundler = 'esbuild') {
const sizes = {};
for (const [page, components] of Object.entries(pages)) {
sizes[page] = {components, ...(await measurePage(distDir, components))};
const esbuild = await measurePage(distDir, components);
if (bundler === 'esbuild') {
sizes[page] = {components, ...esbuild};
continue;
}
const {modules, moduleDepth, ...esbuildBuild} = esbuild;
sizes[page] = {
components,
modules,
moduleDepth,
...(await measurePageRolldown(distDir, components)),
esbuild: esbuildBuild,
};
}
return sizes;
}

/** The bundlers a page can be built with. */
export const BUNDLERS = ['esbuild', 'rolldown'];

/** What `--help` prints. */
export const USAGE = `Usage: pnpm size:pages --base <ref|dist> [options]

Expand All @@ -422,6 +578,9 @@ Options:
against INV10's limit of 0.3 KB gzip (${UNUSED_FEATURE_LIMIT_BYTES} B),
and exits 1 on a failure
--page <name=A,B> Adds a page that imports components A and B
--bundler <name> esbuild (default) or rolldown: rolldown builds each page as a
production Vite app and keeps the esbuild sizes beside it;
--unused-on then reads the Rolldown sizes
--json Prints the comparison as JSON
-h, --help Prints this help

Expand All @@ -435,6 +594,7 @@ export function parseArgs(argv) {
unusedOn: [],
extraPages: {},
json: false,
bundler: 'esbuild',
help: false,
};
if (argv.includes('--help') || argv.includes('-h')) {
Expand All @@ -443,7 +603,14 @@ export function parseArgs(argv) {
for (let index = 0; index < argv.length; index += 1) {
const flag = argv[index];
if (flag === '--base') args.base = argv[++index];
else if (flag === '--head') args.head = argv[++index];
else if (flag === '--bundler') {
args.bundler = argv[++index];
if (!BUNDLERS.includes(args.bundler)) {
throw new Error(
`--bundler must be one of ${BUNDLERS.join(', ')}, got "${args.bundler}"`,
);
}
} else if (flag === '--head') args.head = argv[++index];
else if (flag === '--unused-on') {
args.unusedOn.push(...argv[++index].split(',').filter(Boolean));
} else if (flag === '--page') {
Expand Down Expand Up @@ -473,17 +640,20 @@ async function main(argv) {
const baseSizes = await measurePages(
buildCore(args.base, path.join(workDir, 'base')),
pages,
args.bundler,
);
const headSizes = await measurePages(
buildCore(args.head, path.join(workDir, 'head')),
pages,
args.bundler,
);
const comparison = comparePages(baseSizes, headSizes, {
unusedOn: args.unusedOn,
});
const labels = {
base: args.base,
head: args.head === '.' ? 'the working tree' : args.head,
...(args.bundler === 'esbuild' ? {} : {bundler: args.bundler}),
};
console.log(
args.json
Expand Down
Loading
Loading