Open History to see the last commit
1#!/usr/bin/env node
2/**
3 * Compare the shipped size of packages with their merge-base on a base branch.
4 *
5 * Code weight is what users download and parse, so this measures shipped
6 * bytes after gzip and brotli, not source lines: comments, names, and
7 * formatting do not count. It builds each package with the same
8 * `vite build --minify` that the Compressed size CI check uses. Then, as an
9 * app's production build would, it bundles each package's exported entries
10 * with `process.env.NODE_ENV` set to `production` and its dependencies
11 * external, minifies, and compresses the bundle. Development-only code, such
12 * as full error messages, drops out. `--dev` instead compares every minified
13 * `dist/esm` file as the CI check does, development code included.
14 *
15 * Usage:
16 * pnpm size:compare [--base origin/main] [--exact-base] [--dev]
17 * [--packages db,react-db,...] [--files] [--rebuild]
18 *
19 * The baseline is the merge-base with `--base` (as CI compares), built once in
20 * a cached worktree under the OS temp directory. The working tree is rebuilt
21 * in parallel, and a package whose sources did not change since its last
22 * build is not rebuilt. With `--files`, production mode lists each source
23 * module's minified bytes in the bundle, before compression.
24 *
25 * A package bundle keeps every export, so nothing is tree-shaken. Production
26 * mode therefore also measures scenarios: apps in `scripts/size-scenarios/`.
27 * `app` is the typical app: a query collection, a live query, and the React
28 * adapter. Each other scenario adds one feature to it (a join, a groupBy,
29 * includes, an optimistic action, LocalStorage, an Effect), so its delta is
30 * that feature's cost. Each is tree-shaken as an app ships it, with React and
31 * TanStack Query left external because an app ships them anyway. With `--files`, the changed modules of each
32 * scenario are listed too. `--no-scenarios` skips them.
33 */
34import { execFile, execSync } from 'node:child_process'
35import { createHash } from 'node:crypto'
36import {
37 existsSync,
38 readFileSync,
39 readdirSync,
40 statSync,
41 writeFileSync,
42} from 'node:fs'
43import { availableParallelism, tmpdir } from 'node:os'
44import { basename, join, relative, resolve } from 'node:path'
45import { promisify } from 'node:util'
46import { brotliCompressSync, constants, gzipSync } from 'node:zlib'
47import { build as esbuild } from 'esbuild'
48
49const run = promisify(execFile)
50const args = process.argv.slice(2)
51const option = (name, fallback) => {
52 const index = args.indexOf(`--${name}`)
53 return index === -1 ? fallback : args[index + 1]
54}
55const flag = (name) => args.includes(`--${name}`)
56
57const DEFAULT_PACKAGES = [
58 `db`,
59 `convex-db-collection`,
60 `react-db`,
61 `query-db-collection`,
62 `electric-db-collection`,
63 `powersync-db-collection`,
64 `trailbase-db-collection`,
65 `rxdb-db-collection`,
66 `db-sqlite-persistence-core`,
67]
68// Built first, in order: the other packages resolve their types while their
69// declarations build.
70const PREREQUISITES = [`db-ivm`, `db`]
71// Packages that the scenarios import; production mode always builds them.
72const SCENARIO_PACKAGES = [`react-db`, `query-db-collection`]
73// An app ships these itself, so a scenario leaves them out.
74const APP_DEPENDENCIES = [`react`, `react-dom`, `@tanstack/query-core`]
75
76const root = execSync(`git rev-parse --show-toplevel`, {
77 encoding: `utf8`,
78}).trim()
79const runScenarios = !flag(`dev`) && !flag(`no-scenarios`)
80const scenarioPackages = runScenarios ? SCENARIO_PACKAGES : []
81const baseRef = option(`base`, `origin/main`)
82const packages = option(`packages`, DEFAULT_PACKAGES.join(`,`)).split(`,`)
83const git = (command) =>
84 execSync(`git ${command}`, { cwd: root, encoding: `utf8` }).trim()
85const baseSha = flag(`exact-base`)
86 ? git(`rev-parse ${baseRef}`)
87 : git(`merge-base HEAD ${baseRef}`)
88const baseDir = join(
89 tmpdir(),
90 `tanstack-db-size-baseline-${baseSha.slice(0, 9)}`,
91)
92
93function walk(dir, keep, out = []) {
94 if (!existsSync(dir)) return out
95 for (const name of readdirSync(dir)) {
96 const path = join(dir, name)
97 if (statSync(path).isDirectory()) walk(path, keep, out)
98 else if (keep(name)) out.push(path)
99 }
100 return out
101}
102
103// A package's dist depends on its own sources and build config only: its
104// dependencies are external to the bundle.
105function sourceHash(dir, pkg) {
106 const pkgDir = join(dir, `packages`, pkg)
107 const hash = createHash(`sha256`)
108 const files = [
109 ...walk(join(pkgDir, `src`), () => true),
110 ...[`vite.config.ts`, `package.json`, `tsconfig.json`]
111 .map((name) => join(pkgDir, name))
112 .filter(existsSync),
113 ].sort()
114 for (const file of files) {
115 hash.update(relative(pkgDir, file))
116 hash.update(readFileSync(file))
117 }
118 return hash.digest(`hex`)
119}
120
121async function buildPackage(dir, pkg, force) {
122 const pkgDir = join(dir, `packages`, pkg)
123 if (!existsSync(pkgDir)) return `missing`
124 const stamp = join(pkgDir, `dist`, `.size-compare-hash`)
125 const hash = sourceHash(dir, pkg)
126 if (!force && existsSync(stamp) && readFileSync(stamp, `utf8`) === hash)
127 return `cached`
128 try {
129 await run(`npx`, [`vite`, `build`, `--minify`], {
130 cwd: pkgDir,
131 maxBuffer: 1 << 28,
132 })
133 } catch (error) {
134 const output = `${error.stderr ?? ``}${error.stdout ?? ``}`
135 throw new Error(
136 `vite build failed in packages/${pkg}:\n${output.split(`\n`).slice(0, 20).join(`\n`)}`,
137 )
138 }
139 writeFileSync(stamp, hash)
140 return `built`
141}
142
143async function build(dir, label, force) {
144 const started = Date.now()
145 const prerequisiteResults = {}
146 for (const pkg of PREREQUISITES)
147 prerequisiteResults[pkg] = await buildPackage(dir, pkg, force)
148 // Packages build independently, so run them in parallel.
149 const limit = Math.max(1, Math.floor(availableParallelism() / 2))
150 const queue = [...new Set([...packages, ...scenarioPackages])].filter(
151 (pkg) => !PREREQUISITES.includes(pkg),
152 )
153 const results = {}
154 await Promise.all(
155 Array.from({ length: limit }, async () => {
156 for (let pkg = queue.shift(); pkg; pkg = queue.shift())
157 results[pkg] = await buildPackage(dir, pkg, force)
158 }),
159 )
160 for (const pkg of packages.filter((pkg) => PREREQUISITES.includes(pkg)))
161 results[pkg] = prerequisiteResults[pkg]
162 const built = Object.values(results).filter((r) => r === `built`).length
163 process.stderr.write(
164 `${label}: built ${built} of ${packages.length} packages in ${(
165 (Date.now() - started) /
166 1000
167 ).toFixed(1)}s\n`,
168 )
169}
170
171if (!existsSync(baseDir)) {
172 process.stderr.write(`creating baseline worktree at ${baseSha.slice(0, 9)}\n`)
173 git(`worktree add --detach ${baseDir} ${baseSha}`)
174 execSync(`pnpm install --frozen-lockfile --prefer-offline`, {
175 cwd: baseDir,
176 stdio: `ignore`,
177 })
178}
179await build(baseDir, `baseline ${baseSha.slice(0, 9)}`, false)
180await build(root, `working tree`, flag(`rebuild`))
181
182const sizes = (buffer) => ({
183 gzip: gzipSync(buffer, { level: 9 }).length,
184 brotli: brotliCompressSync(buffer, {
185 params: { [constants.BROTLI_PARAM_QUALITY]: 11 },
186 }).length,
187})
188function measureDev(dir, pkg) {
189 const esm = join(dir, `packages`, pkg, `dist`, `esm`)
190 return new Map(
191 walk(esm, (name) => /\.m?js$/.test(name)).map((file) => [
192 relative(esm, file),
193 sizes(readFileSync(file)),
194 ]),
195 )
196}
197
198// The ESM files a package exports, as an app imports them.
199function exportedEntries(pkgDir) {
200 const manifest = JSON.parse(
201 readFileSync(join(pkgDir, `package.json`), `utf8`),
202 )
203 const entries = new Set()
204 const visit = (value) => {
205 if (typeof value === `string`) {
206 if (/\.m?js$/.test(value) && !value.includes(`/cjs/`)) entries.add(value)
207 } else if (value && typeof value === `object`) {
208 for (const [condition, target] of Object.entries(value))
209 if (condition !== `require` && condition !== `types`) visit(target)
210 }
211 }
212 visit(manifest.exports ?? manifest.module ?? manifest.main)
213 return [...entries].map((entry) => join(pkgDir, entry))
214}
215
216// One bundle per package, as an app's production build sees it. The total
217// is the compressed bundle; each file's entry is its minified bytes in it.
218async function measureProduction(dir, pkg) {
219 const pkgDir = join(dir, `packages`, pkg)
220 // New or removed packages have no shipped bytes on the absent side.
221 if (!existsSync(pkgDir)) return new Map()
222 const entries = exportedEntries(pkgDir).filter(existsSync)
223 if (entries.length === 0) return new Map()
224 const result = await esbuild({
225 stdin: {
226 contents: entries
227 .map((entry) => `export * from ${JSON.stringify(entry)}`)
228 .join(`\n`),
229 resolveDir: pkgDir,
230 },
231 absWorkingDir: pkgDir,
232 bundle: true,
233 minify: true,
234 format: `esm`,
235 platform: `neutral`,
236 packages: `external`,
237 // Resolve imports as an app would: the repo's tsconfig paths would
238 // otherwise inline other workspace packages from their sources.
239 tsconfigRaw: `{}`,
240 write: false,
241 metafile: true,
242 logLevel: `error`,
243 define: { 'process.env.NODE_ENV': `"production"` },
244 })
245 const bundle = Buffer.from(result.outputFiles[0].contents)
246 const files = new Map([[`(bundle)`, sizes(bundle)]])
247 const output = Object.values(result.metafile.outputs)[0]
248 for (const [input, { bytesInOutput }] of Object.entries(output.inputs)) {
249 const name = relative(join(`dist`, `esm`), input)
250 files.set(name, { gzip: bytesInOutput, brotli: bytesInOutput, raw: true })
251 }
252 return files
253}
254
255// A scenario as an app ships it: tree-shaken, with its dependencies, built
256// against one tree's packages.
257const scenarioDir = join(root, `scripts`, `size-scenarios`)
258// The typical app first; each other scenario adds one feature to it.
259const scenarios = existsSync(scenarioDir)
260 ? walk(scenarioDir, (name) => name.endsWith(`.js`)).sort((a, b) =>
261 basename(a) === `app.js`
262 ? -1
263 : basename(b) === `app.js`
264 ? 1
265 : a.localeCompare(b),
266 )
267 : []
268async function measureScenario(dir, scenario) {
269 const result = await esbuild({
270 entryPoints: [scenario],
271 absWorkingDir: join(dir, `packages`, `db`),
272 bundle: true,
273 minify: true,
274 format: `esm`,
275 platform: `browser`,
276 tsconfigRaw: `{}`,
277 external: APP_DEPENDENCIES,
278 alias: Object.fromEntries(
279 [`db`, `db-ivm`, ...SCENARIO_PACKAGES].map((pkg) => [
280 `@tanstack/${pkg}`,
281 join(dir, `packages`, pkg, `dist`, `esm`, `index.js`),
282 ]),
283 ),
284 write: false,
285 metafile: true,
286 logLevel: `error`,
287 define: { 'process.env.NODE_ENV': `"production"` },
288 })
289 const bundle = Buffer.from(result.outputFiles[0].contents)
290 const files = new Map([[`(bundle)`, sizes(bundle)]])
291 const output = Object.values(result.metafile.outputs)[0]
292 // Name each input the same way in both trees: scenario files by their
293 // scenario path, workspace modules by their package path, and dependencies
294 // by their path inside node_modules.
295 for (const [input, { bytesInOutput }] of Object.entries(output.inputs)) {
296 const path = resolve(join(dir, `packages`, `db`), input)
297 const name = path.startsWith(scenarioDir)
298 ? `scenario/${relative(scenarioDir, path)}`
299 : path.includes(`/node_modules/`)
300 ? path.slice(path.lastIndexOf(`/node_modules/`) + 14)
301 : relative(dir, path)
302 files.set(name, { gzip: bytesInOutput, brotli: bytesInOutput, raw: true })
303 }
304 return files
305}
306
307const production = !flag(`dev`)
308const measure = (dir, pkg) =>
309 production
310 ? measureProduction(dir, pkg)
311 : Promise.resolve(measureDev(dir, pkg))
312
313const signed = (n) => (n > 0 ? `+${n}` : `${n}`)
314const percent = (delta, base) =>
315 base ? ` (${signed(Math.round((delta / base) * 1000) / 10)}%)` : ``
316// In production mode the bundle is the total; per-file entries are detail.
317const total = (map, key) =>
318 production
319 ? (map.get(`(bundle)`)?.[key] ?? 0)
320 : [...map.values()].reduce((sum, size) => sum + size[key], 0)
321
322console.log(
323 `merge-base ${baseSha.slice(0, 9)} (${baseRef}) vs working tree: ${
324 production
325 ? `production bundle per package (NODE_ENV=production, dependencies external)`
326 : `minified dist/esm files, development code included`
327 }, gzip -9 and brotli -11 bytes${
328 production && flag(`files`)
329 ? `; per-file rows are minified bytes before compression`
330 : ``
331 }\n`,
332)
333console.log(
334 [`package`, `base gzip`, `head gzip`, `Δ gzip`, `Δ brotli`].join(`\t`),
335)
336const sum = { base: 0, head: 0, baseBrotli: 0, headBrotli: 0 }
337for (const pkg of packages) {
338 const base = await measure(baseDir, pkg)
339 const head = await measure(root, pkg)
340 const baseGzip = total(base, `gzip`)
341 const headGzip = total(head, `gzip`)
342 sum.base += baseGzip
343 sum.head += headGzip
344 sum.baseBrotli += total(base, `brotli`)
345 sum.headBrotli += total(head, `brotli`)
346 console.log(
347 [
348 pkg,
349 baseGzip,
350 headGzip,
351 signed(headGzip - baseGzip) + percent(headGzip - baseGzip, baseGzip),
352 signed(total(head, `brotli`) - total(base, `brotli`)),
353 ].join(`\t`),
354 )
355 if (!flag(`files`)) continue
356 const changed = [...new Set([...base.keys(), ...head.keys()])]
357 .filter((file) => file !== `(bundle)`)
358 .map((file) => [
359 file,
360 (head.get(file)?.gzip ?? 0) - (base.get(file)?.gzip ?? 0),
361 ])
362 .filter(([, delta]) => delta !== 0)
363 .sort((a, b) => b[1] - a[1])
364 for (const [file, delta] of changed)
365 console.log(` ${file}\t\t\t${signed(delta)}`)
366}
367console.log(
368 [
369 `TOTAL`,
370 sum.base,
371 sum.head,
372 signed(sum.head - sum.base) + percent(sum.head - sum.base, sum.base),
373 signed(sum.headBrotli - sum.baseBrotli),
374 ].join(`\t`),
375)
376
377if (runScenarios) {
378 console.log(
379 `\nscenarios: apps in scripts/size-scenarios, tree-shaken, with ${APP_DEPENDENCIES.join(`, `)} external\n`,
380 )
381 console.log(
382 [
383 `scenario`,
384 `base gzip`,
385 `head gzip`,
386 `Δ gzip`,
387 `Δ brotli`,
388 `feature cost (head gzip over app)`,
389 ].join(`\t`),
390 )
391 let appGzip
392 for (const scenario of scenarios) {
393 // A scenario written for a new API cannot build against an older base:
394 // it imports a name the base does not export. Any other failure is real.
395 const base = await measureScenario(baseDir, scenario).catch((error) => {
396 if (!String(error?.message).includes(`No matching export`)) throw error
397 return undefined
398 })
399 const head = await measureScenario(root, scenario)
400 const baseGzip = base?.get(`(bundle)`).gzip
401 const headGzip = head.get(`(bundle)`).gzip
402 appGzip ??= headGzip
403 console.log(
404 [
405 relative(scenarioDir, scenario).replace(/\.js$/, ``),
406 baseGzip ?? `n/a`,
407 headGzip,
408 baseGzip === undefined
409 ? `n/a`
410 : signed(headGzip - baseGzip) +
411 percent(headGzip - baseGzip, baseGzip),
412 base
413 ? signed(head.get(`(bundle)`).brotli - base.get(`(bundle)`).brotli)
414 : `n/a`,
415 signed(headGzip - appGzip),
416 ].join(`\t`),
417 )
418 if (!flag(`files`) || !base) continue
419 const changed = [...new Set([...base.keys(), ...head.keys()])]
420 .filter((file) => file !== `(bundle)`)
421 .map((file) => [
422 file,
423 (head.get(file)?.gzip ?? 0) - (base.get(file)?.gzip ?? 0),
424 ])
425 .filter(([, delta]) => delta !== 0)
426 .sort((a, b) => b[1] - a[1])
427 for (const [file, delta] of changed)
428 console.log(` ${file}\t\t\t${signed(delta)}`)
429 }
430}