DevelopAnalyses
@holtkeeper/bundles
Measures what a frontend build or a published package ships and compares it between releases: total and initial-load bytes (raw, gzip, brotli) per entrypoint, per asset, and which npm packages and app modules make up the size. It reads the build output, so it works with any bundler: Vite, Rollup, webpack, esbuild, Bun.
Pipeline
Section titled “Pipeline”Each step is a separate export and can be replaced.
- Build (optional) —
buildProject({ dir, command, runner?, env?, signal?, timeoutMs? })runs the command the caller chooses (e.g.['bun', 'run', 'build']) through aCommandRunnerfrom@holtkeeper/execand throwsCommandErroron failure. - Entrypoints — an
EntrypointResolverturns the dist directory into{ name, initial, lazy }[].followImportsthen completes the lists by scanning ES moduleimport/export from(initial) andimport()(lazy) in the JS files. - Measure — every file in dist except
defaultIgnore(**/*.map,.vite/**,**/stats.json,**/webpack-stats/**,asset-manifest.json), precompressed copies (x.js.gz,x.js.brnext tox.js) andignoreglobs gets a kind (js,css,html,image,font,other), raw size, gzip (level 9) and brotli (quality 11) size. - Names —
normalizeAssetNamesremoves content hashes so assets match across builds (assets/index-B3x9kQz1.js→assets/index.js,main.3f2a1b9c.css→main.css). Hashes made only of letters (index-kdfefdxf.js) look like words to a single-file check, so the build adds evidence: one stem in one directory repeated with two or more different single-case JS or CSS tokens of the same length, 8 or more characters, at least one with a digit or without a word shape (no vowel, or four consonants in a row), marks those tokens as hashes:chunk-rkgagbvp.jsandchunk-mnbvcxzq.jsdo,locale-german.jsandlocale-french.jsdo not. The length and alphabet of every hash found, even a single one, are then applied to the remaining files of the same extension. A word suffix (app-frontend.js,icon-squirrel.svg) is kept unless it has exactly the length and alphabet of a hash on that file type in the same build. When two files still share a name (chunk-a.js,chunk-b.js), each gets the first source of its source map:chunk.js [react],chunk.js [src/lazy.ts]. PassnormalizeNameto use your own rule. - Attribution — source maps of JS and CSS split each asset’s bytes between original sources, which
sourceOriginmaps to npm packages or app modules. - Compare and report —
compareBundles(previous, current)diffs two results;bundleAnalysisturns them into aReport.
import { analyzeBundle, bundleAnalysis } from '@holtkeeper/bundles'
const data = await analyzeBundle({ dist: 'dist', build: { dir: '/path/to/app', command: ['bun', 'run', 'build'] },})Pointing it at a build
Section titled “Pointing it at a build”| Bundler | What to enable | Resolver used |
|---|---|---|
| Vite / Rollup | build.manifest: true, build.sourcemap: true (or 'hidden') |
viteManifestResolver |
| webpack | devtool: 'source-map'; write stats.json into output.path, or rely on index.html |
webpackStatsResolver / htmlResolver |
| Create React App | GENERATE_SOURCEMAP=true (default); asset-manifest.json is read |
webpackStatsResolver |
| esbuild / Bun | sourcemap: 'linked' or 'external', ES module output |
htmlResolver / importGraphResolver |
Without entries or resolver, analyzeBundle tries defaultResolvers() in order and uses the first one that finds anything:
viteManifestResolver()—.vite/manifest.jsonormanifest.json: eachisEntrychunk with its CSS and static imports, recursively;dynamicImportsbecome lazy. HTML entries (src: 'index.html') include the page.webpackStatsResolver()—stats.jsonentrypoints[name].assets, lazy chunks throughchunks[].children; orasset-manifest.jsonwith anentrypointslist.htmlResolver()— one entrypoint per HTML page (index.html→index,admin/index.html→admin): the page,<script src>,<link rel=stylesheet|modulepreload|preload>and imports in inline module scripts. Root-relative URLs with a deploy base (/app/assets/x.js) are matched to dist files, also relative to the page’s folder when the site root is a subfolder of dist (frontend/game.htmlloading/scripts/x.js).importGraphResolver()— every JS file that no other JS file imports.
Configure entrypoints explicitly with entries: [{ name: 'admin', globs: ['assets/admin-*.js'] }], or pass any resolver; combine your own with firstEntrypoints(...resolvers). Set followImports: false when the resolver already returns complete lists.
analyzeBundle returns BundleData, plain JSON validated by bundleDataSchema:
assets[]—file, normalizedname,kind,raw,gzip,brotli,mapped(bytes explained by a source map).entrypoints[]—name,initialandlazyfiles,initialSizeandlazySize,packages(npm packages plus(app)and(unmapped)) and appmodulesover initial and lazy JS/CSS.packages[]— every package over all assets withbytes,gzip,versions(from pnpm/bun store paths or the installedpackage.json),instances(install paths; more than one means it is bundled twice),modulesandentrypoints.modules[],unmapped,tool(vite,webpack,bun, … when recognised),build(command and duration when it ran).
Targets
Section titled “Targets”A bundle record holds BundleRecordData { targets, notes? }: every thing one run measured, and on a record without targets whose detection found nothing, notes saying why. A BundleTarget has a name, a source (build or package), for packages a version and its publish time at, a status and either data (BundleData) or, when failed, the error. Package targets add package: PackageInfo (unpacked bytes and files of the whole archive, dependencies, peerDependencies, and entrypointsFound when there were more entrypoints than were measured). Records from before targets hold a bare BundleData; bundleTargets(data) reads both (the old shape is one app build) and bundleAnalysisSchema validates both.
analyzeBuildTarget({ name, dir, dist, command?, runner?, env?, entries?, ignore?, root?, signal?, timeoutMs? })builds (whencommandis set) and measures one target.distmay list candidates; the first that exists after the build is measured. It never throws for a failed build or a missing output: the target comes backfailedwith the end of the error, so a release that no longer builds is a gap in history. Aborts still reject.analyzePackage({ name, version, files, publishedAt? })measures one published version from its unpacked archive (paths without the top folder). Assets are the shipped files without declarations, Markdown, licenses, changelogs andpackage.json(packageIgnore); entrypoints are its export subpaths (packageEntries: thebrowser,import,module,default,requireornodetarget of eachexportssubpath, nevertypes,*patterns expanded over the archive; withoutexportsthemodule, a stringbrowserormainfield), completed by following ES module imports inside the package. At mostMAX_PACKAGE_ENTRIES(100) entrypoints are measured; when a package has more,PackageInfo.entrypointsFoundkeeps how many it had, so reports say e.g.measured 100 of 240 entrypoints; source maps the package ships attribute bytes. Imports of dependencies are not followed: sizes are the package’s own code. Failures become afailedtarget.bundleSeries(records)turnsbundlerecords ({ id, createdAt, ref?, data }) into oneBundleSeries { name, source, points }per target name, sorted by name. Builds get one point per record; a package version counts once, from the newest record measuring it. Points (BundlePoint) carry the record id, ref, version,at(publish time, else the record’s), status and error, total sizes, JS and CSS gzip, initial and lazy sizes per entrypoint andPackageInfo, ordered byat.findTargetPoint(records, { name, version?, analysisId? })locates one point (newest without either) and the closest earlier point that measured fine;targetReport(current, previous?)renders it like a single build, plus a Package section with archive size, files and dependencies (new ones tagged) for package targets.
Report
Section titled “Report”A record with one target is reported like that target (targetReport, compared with the target of the same name in the previous record). A record without targets shows a warning and its notes (why detection found nothing and which analyzers.bundle options would fix it) as a list, or, without notes, that every published version was measured before. A record with several shows metrics over all of them (total gzip of measured targets, targets, not measured) and a Targets table with each one’s sizes, change against the same target in the previous record, largest initial load and status (failed, or truncated for packages measured on part of their entrypoints); failed and truncated targets and changes over the thresholds are listed above it. The details of one target are in Quality › Bundles of the web app.
For a single target, bundleAnalysis (kind bundle, or createBundleAnalysis({ growthPercent, growthBytes, heavyPackageBytes, treemapModules }) for other thresholds) produces:
- Metrics — JS gzip, CSS gzip, initial load of the largest entrypoint, number of entrypoints, number of packages; deltas against the previous record,
better: 'down'for sizes. - Overview — bar chart of initial gzip per entrypoint (previous vs current) and issues: a warning when a package was measured on only
MAX_PACKAGE_ENTRIESof its entrypoints (also the hint of the Entrypoints metric), entrypoints that grew or shrank by more than 5 % or 10 kB gzip, new packages over 5 kB gzip, packages that grew by more than 10 kB, packages newly bundled in several versions (or all duplicates when there is no previous record). - Entrypoints — raw / gzip / brotli of the initial load with deltas, lazy size with delta, and a table of lazy chunks per entrypoint.
- Composition — treemap entrypoint → package, with
(app)broken down into modules. - Packages — raw and estimated gzip size, delta, share of all JS and CSS gzip, versions, entrypoints,
added/removed/duplicatetags. - Assets — normalized name, file, kind, sizes, delta,
added/removed/changedtags.
Metrics
Section titled “Metrics”bundleAnalysis.metrics (bundleMetrics) stores BundleMetrics with every record:
targets— oneBundleTargetMetricsper target name, sorted by name; for packages the highest version the record measured. Each hasname,source,version,status,gzip(JS and CSS gzip bytes of every asset),initial(initial gzip of the largest entrypoint),delta(gzipminus the previous record’s target of the same name) and, when a budget applies,budgetandverdict.failed— targets whose build or download failed.
Budgets come from the budgets option of the bundle analyzer (@holtkeeper/analyzers): maximum gzip bytes keyed by target name or by a glob over names (@acme/*), validated by bundleBudgetsSchema. An exact name wins over globs, then the first matching glob in the order they are written. A target is over above its budget, near from 90% of it, else ok; failed targets get no verdict. budgetFor(budgets, name) and budgetVerdict(gzip, budget) are that rule, exported so repository health judges budgets the same way. judgeTarget(target, budgets) judges a stored target by the budgets that apply now: with budgets (the option is set for the repository) its budget for the target’s name, otherwise the budget stored with the target; the verdict needs both a budget and a size. Repository health and the Quality › Bundles overview both use it, so a budget changed in the settings shows without a new measurement.
Attribution limits
Section titled “Attribution limits”- Bytes are attributed per source map segment: a segment owns the generated text up to the next segment on the line. Text before the first segment of a line, segments without a source, line breaks, and files without a map count as
(unmapped). Totals always add up to the asset size. - Package gzip sizes are estimates: each asset’s gzip size is split in proportion to raw bytes. Raw bytes are exact.
- Bundler-generated code (runtime, helpers, module wrappers) is often unmapped or mapped to the first module of a chunk. Vite and webpack runtime ids map to
viteandwebpack; other virtual ids (\0...) to(virtual). - Index source maps (
sections) are not supported; their assets count as unmapped. - Package versions need pnpm/bun store paths or the project’s
node_moduleson disk at analysis time; otherwise duplicates are detected by install path only. - Import following uses a regex over ES module output. CommonJS or SystemJS chunks and imports built from expressions are not followed; use a manifest resolver or
entriesfor them. - Paths in source maps resolve against the map’s directory and are reported relative to
root(default:build.dir, else the parent ofdist). In monorepos, setrootto the app directory; sources outside it keep../paths.