#!/usr/bin/env node // Splits main.dart.js by Dart source through its source map, to find deferred // loading candidates: // // flutter build web --release --source-maps --output build/size // node tool/perf/js_size_by_source.mjs build/size [depth=3] // // Every generated character is charged to the source of the mapping segment // it falls in (characters before a line's first segment, or in an unmapped // segment, count as "(unmapped)"). App sources are grouped to [depth] path // parts under lib/ (`features/chat/ui` at 3), other sources by package. import { readFile } from 'node:fs/promises'; const [dir, depthArg = '3'] = process.argv.slice(2); if (!dir) throw new Error('usage: js_size_by_source.mjs [depth]'); const depth = Number(depthArg); const js = (await readFile(`${dir}/main.dart.js`, 'utf8')).split('\n'); const map = JSON.parse(await readFile(`${dir}/main.dart.js.map`, 'utf8')); const B64 = Object.fromEntries([...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'].map((c, i) => [c, i])); function decode(segment) { const out = []; let value = 0; let shift = 0; for (const c of segment) { const digit = B64[c]; value += (digit & 31) << shift; if (digit & 32) { shift += 5; continue; } out.push(value & 1 ? -(value >>> 1) : value >>> 1); value = 0; shift = 0; } return out; } function group(source) { const app = source.match(/(?:^|\/)lib\/((?:features|ui|shell|core|application)\/.*)$/); if (app && !source.includes('/packages/')) return `app:${app[1].split('/').slice(0, depth).join('/').replace(/\.dart$/, '')}`; const flutter = source.match(/packages\/flutter\/lib\/src\/(\w+)/); if (flutter) return `flutter/${flutter[1]}`; const pkg = source.match(/(?:pub\.dev|hosted\/[^/]+)\/([\w]+)-[\d.]+/) ?? source.match(/packages\/(\w+)\//); if (pkg) return `pkg:${pkg[1]}`; if (source.startsWith('org-dartlang-sdk')) return source.includes('_engine') ? 'sdk:web_engine' : 'sdk:dart'; return source.split('/').slice(-2).join('/'); } const sizes = new Map(); const add = (key, n) => sizes.set(key, (sizes.get(key) ?? 0) + n); let src = 0; map.mappings.split(';').forEach((line, i) => { const text = js[i] ?? ''; let col = 0; let last = { col: 0, key: '(unmapped)' }; for (const seg of line.split(',')) { if (!seg) continue; const v = decode(seg); col += v[0]; add(last.key, col - last.col); if (v.length >= 4) src += v[1]; last = { col, key: v.length >= 4 ? group(map.sources[src]) : '(unmapped)' }; } add(last.key, text.length + 1 - last.col); }); const total = js.reduce((n, l) => n + l.length + 1, 0); console.log(`main.dart.js ${(total / 1024).toFixed(0)} KiB`); for (const [k, v] of [...sizes].sort((a, b) => b[1] - a[1]).slice(0, 45)) { console.log(`${(v / 1024).toFixed(1).padStart(8)} KiB ${(100 * v / total).toFixed(1).padStart(5)}% ${k}`); }