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