@bymaksym/loadline 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -0
  3. package/bin/loadline.js +50 -0
  4. package/dist/cli/cli/args.js +324 -0
  5. package/dist/cli/cli/args.types.js +3 -0
  6. package/dist/cli/cli/gates.js +173 -0
  7. package/dist/cli/cli/gates.types.js +3 -0
  8. package/dist/cli/cli/main.js +156 -0
  9. package/dist/cli/cli/read-build.js +382 -0
  10. package/dist/cli/cli/read-build.types.js +3 -0
  11. package/dist/cli/cli/render-json.js +116 -0
  12. package/dist/cli/cli/render-json.types.js +10 -0
  13. package/dist/cli/cli/render-markdown.js +30 -0
  14. package/dist/cli/cli/render-pr.js +76 -0
  15. package/dist/cli/cli/render-sarif.js +83 -0
  16. package/dist/cli/cli/render-text.js +388 -0
  17. package/dist/cli/cli/report.js +196 -0
  18. package/dist/cli/cli/report.types.js +3 -0
  19. package/dist/cli/cli/self-check.js +85 -0
  20. package/dist/cli/cli/text.js +180 -0
  21. package/dist/cli/cli/text.types.js +10 -0
  22. package/dist/cli/src/app/core/analysis/analysis.js +661 -0
  23. package/dist/cli/src/app/core/analysis/analysis.types.js +6 -0
  24. package/dist/cli/src/app/core/analysis/barrels.js +128 -0
  25. package/dist/cli/src/app/core/analysis/blast.js +172 -0
  26. package/dist/cli/src/app/core/analysis/cycles.js +110 -0
  27. package/dist/cli/src/app/core/analysis/delivery.js +143 -0
  28. package/dist/cli/src/app/core/analysis/entries.js +217 -0
  29. package/dist/cli/src/app/core/analysis/exclusive.js +91 -0
  30. package/dist/cli/src/app/core/analysis/importers.js +38 -0
  31. package/dist/cli/src/app/core/analysis/insights.js +202 -0
  32. package/dist/cli/src/app/core/analysis/insights.types.js +10 -0
  33. package/dist/cli/src/app/core/analysis/invariant.js +69 -0
  34. package/dist/cli/src/app/core/analysis/metafile.types.js +44 -0
  35. package/dist/cli/src/app/core/analysis/module-graph.js +192 -0
  36. package/dist/cli/src/app/core/analysis/sourcemap.js +231 -0
  37. package/dist/cli/src/app/core/analysis/sourcemap.types.js +3 -0
  38. package/dist/cli/src/app/core/analysis/split-drift.js +47 -0
  39. package/dist/cli/src/app/core/assets/assets.js +296 -0
  40. package/dist/cli/src/app/core/assets/assets.types.js +11 -0
  41. package/dist/cli/src/app/core/baseline/baseline.js +0 -0
  42. package/dist/cli/src/app/core/baseline/baseline.types.js +3 -0
  43. package/dist/cli/src/app/core/caching/caching.js +241 -0
  44. package/dist/cli/src/app/core/caching/caching.types.js +10 -0
  45. package/dist/cli/src/app/core/caching/from-analysis.js +73 -0
  46. package/dist/cli/src/app/core/config/loadline-config.js +110 -0
  47. package/dist/cli/src/app/core/config/loadline-config.types.js +12 -0
  48. package/dist/cli/src/app/core/criteria/criteria.js +228 -0
  49. package/dist/cli/src/app/core/criteria/criteria.types.js +3 -0
  50. package/dist/cli/src/app/core/deps/deps.js +225 -0
  51. package/dist/cli/src/app/core/deps/deps.types.js +15 -0
  52. package/dist/cli/src/app/core/export/markdown-table.utils.js +40 -0
  53. package/dist/cli/src/app/core/export/summary.js +72 -0
  54. package/dist/cli/src/app/core/findings/actions.js +59 -0
  55. package/dist/cli/src/app/core/findings/assets.js +130 -0
  56. package/dist/cli/src/app/core/findings/caching.js +165 -0
  57. package/dist/cli/src/app/core/findings/compose.js +41 -0
  58. package/dist/cli/src/app/core/findings/deps.js +66 -0
  59. package/dist/cli/src/app/core/findings/effort.js +117 -0
  60. package/dist/cli/src/app/core/findings/finding-html.js +13 -0
  61. package/dist/cli/src/app/core/findings/finding-plain.js +26 -0
  62. package/dist/cli/src/app/core/findings/finding-text.js +1231 -0
  63. package/dist/cli/src/app/core/findings/finding.types.js +80 -0
  64. package/dist/cli/src/app/core/findings/findings.js +514 -0
  65. package/dist/cli/src/app/core/findings/graph.js +167 -0
  66. package/dist/cli/src/app/core/findings/own-in-boot.js +88 -0
  67. package/dist/cli/src/app/core/findings/page.js +49 -0
  68. package/dist/cli/src/app/core/findings/requests.js +185 -0
  69. package/dist/cli/src/app/core/findings/scan.js +126 -0
  70. package/dist/cli/src/app/core/findings/shipped.js +244 -0
  71. package/dist/cli/src/app/core/findings/situation.js +116 -0
  72. package/dist/cli/src/app/core/format/format.utils.js +204 -0
  73. package/dist/cli/src/app/core/i18n/en.js +819 -0
  74. package/dist/cli/src/app/core/i18n/es.js +822 -0
  75. package/dist/cli/src/app/core/i18n/ui-strings.js +11 -0
  76. package/dist/cli/src/app/core/i18n/ui.js +7 -0
  77. package/dist/cli/src/app/core/intake/bundle-graph.js +346 -0
  78. package/dist/cli/src/app/core/intake/bundle-graph.types.js +3 -0
  79. package/dist/cli/src/app/core/intake/dist-files.js +160 -0
  80. package/dist/cli/src/app/core/intake/index-html.js +292 -0
  81. package/dist/cli/src/app/core/json/json.utils.js +55 -0
  82. package/dist/cli/src/app/core/measurement/measurement.types.js +14 -0
  83. package/dist/cli/src/app/core/project/budget-advice.js +76 -0
  84. package/dist/cli/src/app/core/project/project-context.js +394 -0
  85. package/dist/cli/src/app/core/project/project-context.types.js +3 -0
  86. package/dist/cli/src/app/core/scan/catalog.js +67 -0
  87. package/dist/cli/src/app/core/scan/scan.js +280 -0
  88. package/dist/cli/src/app/core/scan/scan.types.js +10 -0
  89. package/dist/cli/src/app/core/scan/secrets.js +0 -0
  90. package/dist/cli/src/app/core/situation/situation.js +261 -0
  91. package/dist/cli/src/app/core/situation/situation.types.js +19 -0
  92. package/dist/cli/src/app/core/timing/timing.js +87 -0
  93. package/dist/cli/src/app/core/timing/timing.types.js +3 -0
  94. package/dist/cli/src/app/core/whatif/defer.js +68 -0
  95. package/dist/cli/src/app/state/report-messages.utils.js +73 -0
  96. package/docs/HOW-IT-WORKS.md +1087 -0
  97. package/loadline.html +78 -0
  98. package/package.json +154 -0
@@ -0,0 +1,661 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyze = void 0;
4
+ const criteria_1 = require("../criteria/criteria");
5
+ const format_utils_1 = require("../format/format.utils");
6
+ const blast_1 = require("./blast");
7
+ const delivery_1 = require("./delivery");
8
+ const entries_1 = require("./entries");
9
+ const importers_1 = require("./importers");
10
+ const insights_1 = require("./insights");
11
+ const split_drift_1 = require("./split-drift");
12
+ /** pnpm writes the version into the path, which is what puts a number on each copy. */
13
+ const PNPM_COPY = /node_modules\/\.pnpm\/((?:@[^+]+\+)?[^@]+)@([^/]+)\//;
14
+ /**
15
+ * Which installed copy of a package a file belongs to.
16
+ *
17
+ * The identity of a copy is **where it is installed**: everything before the last `node_modules/`
18
+ * of its path. That one rule covers the two layouts. pnpm gives every copy its own directory with
19
+ * the version in the name, so the version comes out as a bonus; npm and yarn hoist one copy to the
20
+ * top and nest the rest inside whoever asked for them, and the path says who that is but never the
21
+ * version.
22
+ *
23
+ * It used to read the pnpm path only. The consequence was not a worse signal but a missing one:
24
+ * the same project analysed by somebody using npm reported no duplicates at all, because the
25
+ * second copy sits at `node_modules/a/node_modules/lodash/` and nothing there matched.
26
+ *
27
+ * @returns `null` for project code, which has no copies.
28
+ */
29
+ const copyOf = (input, pkg) => {
30
+ const marker = input.lastIndexOf('node_modules/');
31
+ if (marker === -1) {
32
+ return null;
33
+ }
34
+ // '' when the package is installed at the top level, which is a copy like any other.
35
+ const at = input.slice(0, marker);
36
+ const pnpm = PNPM_COPY.exec(at);
37
+ const pnpmName = pnpm?.[1]?.replace('+', '/');
38
+ // A pnpm directory named after another package holds this one as that package's dependency:
39
+ // the version in the path is that other package's, not this one's.
40
+ const own = pnpmName === pkg;
41
+ // Where a nested copy lives. `packageOf` names it when the path goes through `node_modules/`,
42
+ // which is npm's and yarn's case; a copy installed outside it — a `file:` dependency, a package
43
+ // of a monorepo — has no package name in its path, and calling that one "the top-level copy"
44
+ // is exactly wrong. The folder is what identifies it, so the folder is what gets said.
45
+ const folder = at.replaceAll(/^[./]+|\/+$/g, '');
46
+ return {
47
+ at,
48
+ version: own ? (pnpm?.[2] ?? null) : null,
49
+ under: own || !at ? null : (pnpmName ?? (0, format_utils_1.packageOf)(at) ?? (folder || null)),
50
+ };
51
+ };
52
+ /**
53
+ * Analyses a metafile.
54
+ *
55
+ * @param meta the `stats.json`
56
+ * @param gzip compressed sizes by file name, when the build folder has been loaded. Its keys
57
+ * are also the answer to "which files does that folder hold", which is how an
58
+ * output belonging to the server side of the same build is told apart from one a
59
+ * browser downloads — see `browserSide`.
60
+ * @param exact bytes per file inside each chunk, read from the source maps of the build folder,
61
+ * keyed by chunk file name. A second measurement of what the metafile already says.
62
+ * @param announced file names `index.html` tells the browser to fetch before parsing anything: the
63
+ * entry script and the `modulepreload` links. Only that page distinguishes a
64
+ * bootstrap chunk asked for at once from one found a round trip later.
65
+ * @param marks lazy entries somebody reclassified by hand, source file to what it should be.
66
+ * A mark wins over every rule: the rules read file names for part of the job, and
67
+ * whoever is looking at the report knows their project better than a regular
68
+ * expression does.
69
+ * @param limits the only criterion the analysis itself needs: what a file that just groups
70
+ * routes may weigh. It comes in from outside so it can be edited with the rest
71
+ * instead of being a constant here, and it arrives on its own rather than as the
72
+ * whole criteria object so that editing any other threshold does not walk the
73
+ * graph again.
74
+ * @param parallel chunks the loader asks for in the same round trip as a lazy one, when the build
75
+ * writes that list into the call. Vite does; esbuild does not, and there the map
76
+ * is empty and nothing changes.
77
+ */
78
+ const analyze = (meta, gzip, exact = null, announced = null, marks = null, limits = criteria_1.RECOMMENDED.raw, parallel = null) => {
79
+ // The keys of `gzip` are every asset of the build folder: the measured answer to what a
80
+ // browser can actually download, which is what tells the two sides of an SSR build apart.
81
+ const { outputs, serverOutputs } = (0, entries_1.browserSide)(meta.outputs, gzip ? new Set(gzip.keys()) : null);
82
+ const inputs = meta.inputs ?? {};
83
+ // `.mjs` is what esbuild writes with `--out-extension:.js=.mjs`, and what several setups ship.
84
+ // Filtering on `.js` alone left those builds with no entry at all and threw `NO_ENTRIES`.
85
+ const isJs = (file) => /\.m?js$/.test(file);
86
+ const isOwn = (input) => !/node_modules/.test(input);
87
+ /** Source-graph edges that keep files in the same chunk: anything but a lazy boundary or an external. */
88
+ const travelsTogether = (imp) => !imp.external && imp.kind !== 'dynamic-import';
89
+ /**
90
+ * How many bytes of a file are inside a chunk. The metafile's figure is already the minified
91
+ * one; the source map of that chunk, when the folder brought it, is preferred simply because
92
+ * it was measured on the generated file itself.
93
+ */
94
+ const bytesIn = (chunk, input) => {
95
+ const measured = exact?.get((0, format_utils_1.baseName)(chunk))?.get(input);
96
+ return typeof measured === 'number' ? measured : (outputs[chunk]?.inputs?.[input]?.bytesInOutput ?? 0);
97
+ };
98
+ /**
99
+ * The same figure, with "nobody measured this chunk" told apart from "it weighs nothing". A
100
+ * folder read without source maps knows what a chunk weighs and not what is inside it, and the
101
+ * rules that read a file's own weight have to know the difference before they fire.
102
+ */
103
+ const ownBytesIn = (chunk, input) => {
104
+ const measured = exact?.get((0, format_utils_1.baseName)(chunk));
105
+ if (measured) {
106
+ return measured.get(input) ?? 0;
107
+ }
108
+ const inside = outputs[chunk]?.inputs;
109
+ return inside ? (inside[input]?.bytesInOutput ?? 0) : null;
110
+ };
111
+ /** Files of a chunk with their bytes, skipping the empty ones. */
112
+ const inputsOf = (chunk) => Object.keys(outputs[chunk]?.inputs ?? {})
113
+ .map((input) => [input, bytesIn(chunk, input)])
114
+ .filter(([, bytes]) => bytes > 0);
115
+ const mainContentOf = (chunk) => {
116
+ const top = inputsOf(chunk).toSorted((a, b) => b[1] - a[1])[0];
117
+ return top ? (0, format_utils_1.shortName)(top[0]) : '';
118
+ };
119
+ // An output is a lazy entry if somebody imports it dynamically.
120
+ const lazyTargets = new Set(Object.values(outputs)
121
+ .flatMap(output => output.imports ?? [])
122
+ .filter(imp => imp.kind === 'dynamic-import')
123
+ .map(imp => imp.path));
124
+ /**
125
+ * What is reachable following ONLY static imports: that is what is downloaded together.
126
+ * Following dynamic ones would mix everything and always return the whole bundle.
127
+ */
128
+ const reach = (start) => {
129
+ const seen = new Set();
130
+ const stack = [start];
131
+ while (stack.length > 0) {
132
+ const file = stack.pop();
133
+ const output = file ? outputs[file] : undefined;
134
+ if (!file || !output || seen.has(file)) {
135
+ continue;
136
+ }
137
+ seen.add(file);
138
+ const imports = output.imports ?? [];
139
+ for (const imp of imports) {
140
+ if (imp.kind === 'import-statement') {
141
+ stack.push(imp.path);
142
+ }
143
+ }
144
+ }
145
+ return seen;
146
+ };
147
+ const lazyLoaders = (0, entries_1.lazyLoadersOf)(inputs, isOwn);
148
+ const entries = Object.entries(outputs).filter(([file, out]) => out.entryPoint && isJs(file));
149
+ if (entries.length === 0) {
150
+ throw new Error('NO_ENTRIES');
151
+ }
152
+ const rootCandidates = entries.filter(([file]) => !lazyTargets.has(file));
153
+ if (rootCandidates.length === 0) {
154
+ throw new Error('NO_MAIN');
155
+ }
156
+ // There may be stray entries (a library worker): the main one is the one that reaches the most.
157
+ const main = rootCandidates.map(([file]) => [file, reach(file).size]).toSorted((a, b) => b[1] - a[1])[0];
158
+ if (!main) {
159
+ throw new Error('NO_MAIN');
160
+ }
161
+ /**
162
+ * The bootstrap is the main entry plus any other entry chunk the page starts as well.
163
+ *
164
+ * An application does not have to have one entry. Angular's polyfills are a second one, and
165
+ * SvelteKit starts two — its router and the application — from a script inside the page. Taking
166
+ * only the main one left those chunks out of the figure everybody pays and made the two
167
+ * readings of the bootstrap disagree, which is a report that is wrong without saying so.
168
+ *
169
+ * What decides is the page: a stray entry nobody announces (a worker, a library build) is not
170
+ * downloaded on the first load and stays out, which is why the union is not over every entry.
171
+ */
172
+ const alsoStarted = announced
173
+ ? rootCandidates.filter(([file]) => file !== main[0] && announced.has((0, format_utils_1.baseName)(file)))
174
+ : [];
175
+ const boot = new Set([main[0], ...alsoStarted.map(([file]) => file)].flatMap(file => [...reach(file)]));
176
+ /**
177
+ * Everything the browser can get to from where the application starts, following both kinds of
178
+ * import. What is left over is in the folder and in no figure of this report: a service worker,
179
+ * a chunk imported by a path built at run time, or the leftovers of a previous build in a
180
+ * folder nobody cleaned. The first two are facts about the build; the third makes every number
181
+ * here read low, and all three were invisible.
182
+ */
183
+ const reachAll = (seeds) => {
184
+ const seen = new Set();
185
+ const stack = [...seeds];
186
+ while (stack.length > 0) {
187
+ const file = stack.pop();
188
+ const output = file ? outputs[file] : undefined;
189
+ if (!file || !output || seen.has(file)) {
190
+ continue;
191
+ }
192
+ seen.add(file);
193
+ const imports = output.imports ?? [];
194
+ for (const imp of imports) {
195
+ stack.push(imp.path);
196
+ }
197
+ }
198
+ return seen;
199
+ };
200
+ const reachable = reachAll([main[0], ...alsoStarted.map(([file]) => file)]);
201
+ const unreachable = Object.keys(outputs)
202
+ .filter(file => isJs(file) && !reachable.has(file))
203
+ .map(file => ({ file, bytes: outputs[file]?.bytes ?? 0 }));
204
+ const lazyOwnEntries = entries
205
+ .filter(([file]) => lazyTargets.has(file))
206
+ // And reachable from where the application starts. A chunk only some other unreachable
207
+ // chunk imports is not a screen of this build: it is what a previous build left in a folder
208
+ // nobody cleaned, and it used to take a row of the table and push a real screen out of it.
209
+ .filter(([file]) => reachable.has(file))
210
+ .map(([file, out]) => ({ chunk: file, source: out.entryPoint ?? '', set: reach(file) }))
211
+ // A screen is project code: an `await import('xlsx')` also produces a lazy entry and is not one.
212
+ .filter(entry => !/node_modules/.test(entry.source));
213
+ // Which of them are screens, which are pieces of one and which only group routes. The three
214
+ // rules and their reasons are in `entries.ts`; a mark, when there is one, overrules them.
215
+ const kinds = (0, entries_1.classifyLazyEntries)(lazyOwnEntries, {
216
+ inputs,
217
+ outputs,
218
+ ownBytesOf: ownBytesIn,
219
+ loaders: lazyLoaders,
220
+ marks,
221
+ grouperMaxBytes: limits.grouperMaxBytes,
222
+ });
223
+ // How many screens each lazy chunk appears in. Every shared-chunk figure builds on this counter.
224
+ const screenCount = new Map();
225
+ const chunkScreens = new Map();
226
+ for (const entry of kinds.screens) {
227
+ const lazyChunks = [...entry.set].filter(chunk => !boot.has(chunk));
228
+ for (const chunk of lazyChunks) {
229
+ screenCount.set(chunk, (screenCount.get(chunk) ?? 0) + 1);
230
+ chunkScreens.set(chunk, [...(chunkScreens.get(chunk) ?? []), entry.source]);
231
+ }
232
+ }
233
+ const zoneOf = (chunk) => {
234
+ if (boot.has(chunk)) {
235
+ return 'boot';
236
+ }
237
+ return (screenCount.get(chunk) ?? 0) > 1 ? 'shared' : 'own';
238
+ };
239
+ const sizeOf = (chunk) => {
240
+ const compressed = gzip?.get((0, format_utils_1.baseName)(chunk));
241
+ return typeof compressed === 'number' ? compressed : (outputs[chunk]?.bytes ?? 0);
242
+ };
243
+ const sumOf = (chunks) => [...chunks].reduce((total, c) => total + sizeOf(c), 0);
244
+ const bootBytes = sumOf(boot);
245
+ const bootRawBytes = [...boot].reduce((total, chunk) => total + (outputs[chunk]?.bytes ?? 0), 0);
246
+ const screens = kinds.screens
247
+ .map(entry => {
248
+ const lazy = [...entry.set].filter(chunk => !boot.has(chunk));
249
+ const own = lazy.filter(chunk => screenCount.get(chunk) === 1);
250
+ const shared = lazy.filter(chunk => (screenCount.get(chunk) ?? 0) > 1);
251
+ // The bootstrap is already there when the router navigates, so it ends the walk: what
252
+ // is being counted is the round trips this screen adds on top of an app already running.
253
+ // What the loader asks for alongside the entry chunk starts in the same trip as it: a
254
+ // build that ships that list has already paid for those files by the time it parses.
255
+ const together = parallel?.get(entry.chunk) ?? [];
256
+ const chunkWaves = (0, delivery_1.wavesFrom)(outputs, [entry.chunk, ...together], boot);
257
+ return {
258
+ label: (0, format_utils_1.screenLabel)(entry.source),
259
+ source: entry.source,
260
+ files: boot.size + lazy.length,
261
+ boot: bootBytes,
262
+ shared: sumOf(shared),
263
+ own: sumOf(own),
264
+ total: bootBytes + sumOf(lazy),
265
+ ownChunks: own,
266
+ sharedChunks: shared,
267
+ waves: (0, delivery_1.depthOf)(chunkWaves),
268
+ // Depth says how many trips; width says whether any of them can be shortened. A
269
+ // screen three trips deep whose widest trip carries one file is a chain worth
270
+ // breaking; one whose widest carries nine is a fan-out, and the fix is different.
271
+ width: (0, delivery_1.widthOf)(chunkWaves),
272
+ chunkWaves,
273
+ };
274
+ })
275
+ .toSorted((a, b) => b.total - a.total);
276
+ // What the first load costs in round trips. Only `index.html` can say, so without it the
277
+ // figure is absent rather than assumed.
278
+ const startup = announced ? (0, delivery_1.startupOf)(outputs, boot, announced) : null;
279
+ const chunkInfo = (file) => ({
280
+ file,
281
+ name: (0, format_utils_1.baseName)(file),
282
+ bytes: sizeOf(file),
283
+ screens: screenCount.get(file) ?? 0,
284
+ mainContent: mainContentOf(file),
285
+ });
286
+ const sharedChunks = [...screenCount]
287
+ .filter(([, count]) => count > 1)
288
+ .map(([file]) => chunkInfo(file))
289
+ .toSorted((a, b) => b.screens - a.screens || b.bytes - a.bytes);
290
+ // --- Bootstrap breakdown by package and folder ---------------------------------------------
291
+ const buckets = new Map();
292
+ let bootBucketTotal = 0;
293
+ /**
294
+ * The source files behind each bucket, and what each of them weighs in the bootstrap. The
295
+ * breakdown itself only ever needed the totals; the exclusive weight needs to know which files
296
+ * to take out of the graph, and there is nothing in the name `primeng` that says which those are.
297
+ */
298
+ const bucketFiles = new Map();
299
+ const bootBytesByInput = new Map();
300
+ const bootInputs = [...boot].flatMap(chunk => inputsOf(chunk));
301
+ for (const [input, bytes] of bootInputs) {
302
+ const pkg = (0, format_utils_1.packageOf)(input);
303
+ const name = pkg ?? (0, format_utils_1.projectFolderOf)(input);
304
+ const existing = buckets.get(name);
305
+ if (existing) {
306
+ existing.bytes += bytes;
307
+ }
308
+ else {
309
+ buckets.set(name, { name, bytes, isProjectCode: !pkg });
310
+ }
311
+ // A file can sit in two bootstrap chunks; the bucket lists it once and adds both weights.
312
+ const files = bucketFiles.get(name) ?? [];
313
+ if (!bootBytesByInput.has(input)) {
314
+ files.push(input);
315
+ bucketFiles.set(name, files);
316
+ }
317
+ bootBytesByInput.set(input, (bootBytesByInput.get(input) ?? 0) + bytes);
318
+ bootBucketTotal += bytes;
319
+ }
320
+ // --- Where every file of the bundle lands: the index the search looks through ---------------
321
+ const inputChunks = new Map();
322
+ for (const [chunk, output] of Object.entries(outputs)) {
323
+ const chunkInputs = Object.keys(output.inputs ?? {});
324
+ for (const input of chunkInputs) {
325
+ inputChunks.set(input, [...(inputChunks.get(input) ?? []), chunk]);
326
+ }
327
+ }
328
+ const modules = [...inputChunks]
329
+ .map(([path, chunks]) => {
330
+ const places = chunks
331
+ .map((chunk) => ({
332
+ chunk,
333
+ chunkName: (0, format_utils_1.baseName)(chunk),
334
+ bytes: bytesIn(chunk, path),
335
+ zone: zoneOf(chunk),
336
+ screens: boot.has(chunk) ? 0 : (screenCount.get(chunk) ?? 0),
337
+ }))
338
+ .filter(place => place.bytes > 0)
339
+ .toSorted((a, b) => b.bytes - a.bytes);
340
+ return {
341
+ path,
342
+ label: (0, format_utils_1.shortName)(path),
343
+ pkg: (0, format_utils_1.packageOf)(path),
344
+ bytes: places.reduce((sum, place) => sum + place.bytes, 0),
345
+ places,
346
+ };
347
+ })
348
+ .filter(entry => entry.places.length > 0)
349
+ .toSorted((a, b) => b.bytes - a.bytes);
350
+ const moduleByPath = new Map(modules.map(entry => [entry.path, entry]));
351
+ // --- Data for the signals ------------------------------------------------------------------
352
+ const { packages: packageImporters, ownFiles: ownImporters } = (0, importers_1.importGraphOf)(inputs, isOwn);
353
+ // The import chain from the entry to each package, breadth-first over static imports of the
354
+ // source graph. Breadth-first gives the shortest one: the import someone has to look at.
355
+ const bootChains = new Map();
356
+ const mainSource = outputs[main[0]]?.entryPoint;
357
+ if (mainSource && inputs[mainSource]) {
358
+ const previous = new Map([[mainSource, null]]);
359
+ const queue = [mainSource];
360
+ const enqueue = (from, path) => {
361
+ if (previous.has(path)) {
362
+ return;
363
+ }
364
+ previous.set(path, from);
365
+ queue.push(path);
366
+ };
367
+ // The array iterator sees what gets pushed while iterating: this is the BFS queue.
368
+ for (const file of queue) {
369
+ const pkg = (0, format_utils_1.packageOf)(file);
370
+ if (pkg && !bootChains.has(pkg)) {
371
+ const chain = [];
372
+ for (let step = file; step; step = previous.get(step) ?? null) {
373
+ chain.unshift(step);
374
+ }
375
+ bootChains.set(pkg, chain);
376
+ }
377
+ const imports = (inputs[file]?.imports ?? []).filter(imp => travelsTogether(imp));
378
+ for (const imp of imports) {
379
+ enqueue(file, imp.path);
380
+ }
381
+ }
382
+ }
383
+ /**
384
+ * The same walk, this time crossing lazy boundaries too. `bootChains` answers "how does this
385
+ * get into the bootstrap"; this one answers "what brings this file in at all", which is the
386
+ * question asked of a file that is only inside one screen.
387
+ */
388
+ const cameFrom = new Map();
389
+ if (mainSource && inputs[mainSource]) {
390
+ cameFrom.set(mainSource, null);
391
+ const pending = [mainSource];
392
+ const visit = (from, path) => {
393
+ if (cameFrom.has(path)) {
394
+ return;
395
+ }
396
+ cameFrom.set(path, from);
397
+ pending.push(path);
398
+ };
399
+ for (const file of pending) {
400
+ const imports = (inputs[file]?.imports ?? []).filter(imp => !imp.external);
401
+ for (const imp of imports) {
402
+ visit(file, imp.path);
403
+ }
404
+ }
405
+ }
406
+ const chainTo = (path) => {
407
+ if (!cameFrom.has(path)) {
408
+ return null;
409
+ }
410
+ const chain = [];
411
+ for (let step = path; step; step = cameFrom.get(step) ?? null) {
412
+ chain.unshift(step);
413
+ }
414
+ return chain;
415
+ };
416
+ // Who lazy-loads each screen: the routes file. That is where a route's providers go. It is the
417
+ // same map that told screens and deferred blocks apart, further up.
418
+ const screenLoaders = lazyLoaders;
419
+ /** Who imports a given set of files: own files, and the packages that do when no own file does. */
420
+ const importersOf = (targets) => {
421
+ const own = new Set();
422
+ const via = new Set();
423
+ for (const [input, data] of Object.entries(inputs)) {
424
+ if (targets.has(input) || (data.imports ?? []).every(imp => !targets.has(imp.path))) {
425
+ continue;
426
+ }
427
+ if (isOwn(input)) {
428
+ own.add(input);
429
+ continue;
430
+ }
431
+ const pkg = (0, format_utils_1.packageOf)(input);
432
+ if (pkg) {
433
+ via.add(pkg);
434
+ }
435
+ }
436
+ return { importers: [...own], viaPackages: [...via] };
437
+ };
438
+ // CommonJS packages: esbuild says so per file (`format`). Grouped by package, with where they land.
439
+ const cjsByPackage = new Map();
440
+ for (const [input, data] of Object.entries(inputs)) {
441
+ const pkg = data.format === 'cjs' ? (0, format_utils_1.packageOf)(input) : null;
442
+ if (!pkg) {
443
+ continue;
444
+ }
445
+ const entry = cjsByPackage.get(pkg) ?? { bytes: 0, files: 0, chunks: new Set() };
446
+ const chunks = inputChunks.get(input) ?? [];
447
+ entry.files += 1;
448
+ for (const chunk of chunks) {
449
+ entry.bytes += bytesIn(chunk, input);
450
+ entry.chunks.add(chunk);
451
+ }
452
+ cjsByPackage.set(pkg, entry);
453
+ }
454
+ const packagesImporting = (target) => {
455
+ const found = new Set();
456
+ for (const [input, data] of Object.entries(inputs)) {
457
+ const from = (0, format_utils_1.packageOf)(input);
458
+ if (!from || from === target) {
459
+ continue;
460
+ }
461
+ if ((data.imports ?? []).some(imp => (0, format_utils_1.packageOf)(imp.path) === target)) {
462
+ found.add(from);
463
+ }
464
+ }
465
+ return [...found];
466
+ };
467
+ const commonJs = [...cjsByPackage]
468
+ .filter(([, entry]) => entry.chunks.size > 0)
469
+ .map(([name, entry]) => {
470
+ const chunks = [...entry.chunks];
471
+ const inBoot = chunks.some(chunk => boot.has(chunk));
472
+ const screenHits = Math.max(0, ...chunks.map(chunk => screenCount.get(chunk) ?? 0));
473
+ const importers = [...(packageImporters.get(name) ?? [])];
474
+ return {
475
+ name,
476
+ bytes: entry.bytes,
477
+ files: entry.files,
478
+ zone: inBoot ? 'boot' : screenHits > 1 ? 'shared' : 'own',
479
+ screens: inBoot ? 0 : screenHits,
480
+ importers,
481
+ viaPackages: importers.length > 0 ? [] : packagesImporting(name),
482
+ };
483
+ })
484
+ .toSorted((a, b) => Number(b.zone === 'boot') - Number(a.zone === 'boot') || b.bytes - a.bytes);
485
+ const copiesByPackage = new Map();
486
+ for (const input of Object.keys(inputs)) {
487
+ const name = (0, format_utils_1.packageOf)(input);
488
+ const copy = name ? copyOf(input, name) : null;
489
+ if (!name || !copy) {
490
+ continue;
491
+ }
492
+ const byPlace = copiesByPackage.get(name) ?? new Map();
493
+ const existing = byPlace.get(copy.at) ?? { version: copy.version, under: copy.under, paths: [] };
494
+ existing.paths.push(input);
495
+ byPlace.set(copy.at, existing);
496
+ copiesByPackage.set(name, byPlace);
497
+ }
498
+ const worstZone = (zones) => {
499
+ if (zones.includes('boot')) {
500
+ return 'boot';
501
+ }
502
+ return zones.includes('shared') ? 'shared' : 'own';
503
+ };
504
+ const duplicates = [...copiesByPackage]
505
+ .map(([name, byPlace]) => {
506
+ const copies = [...byPlace]
507
+ .map(([at, copy]) => {
508
+ const shipped = copy.paths.map(path => moduleByPath.get(path)).filter(entry => !!entry);
509
+ const places = shipped.flatMap(entry => entry.places);
510
+ const heaviest = shipped.toSorted((a, b) => b.bytes - a.bytes)[0];
511
+ const { importers, viaPackages } = importersOf(new Set(copy.paths));
512
+ return {
513
+ at,
514
+ version: copy.version,
515
+ under: copy.under,
516
+ bytes: shipped.reduce((sum, entry) => sum + entry.bytes, 0),
517
+ files: shipped.length,
518
+ zone: worstZone(places.map(place => place.zone)),
519
+ screens: Math.max(0, ...places.map(place => place.screens)),
520
+ chain: heaviest ? chainTo(heaviest.path) : null,
521
+ importers,
522
+ viaPackages: viaPackages.filter(pkg => pkg !== name),
523
+ };
524
+ })
525
+ // A copy resolved but tree-shaken away entirely is not paid twice.
526
+ .filter(copy => copy.bytes > 0)
527
+ .toSorted((a, b) => Number(b.zone === 'boot') - Number(a.zone === 'boot') || b.bytes - a.bytes);
528
+ return {
529
+ name,
530
+ copies,
531
+ bytes: copies.reduce((sum, copy) => sum + copy.bytes, 0),
532
+ inBoot: copies.some(copy => copy.zone === 'boot'),
533
+ };
534
+ })
535
+ .filter(pkg => pkg.copies.length > 1)
536
+ .toSorted((a, b) => Number(b.inBoot) - Number(a.inBoot) || b.bytes - a.bytes);
537
+ // Every own file of the bootstrap, heaviest first. Which of them is "large" is a criterion and
538
+ // is applied where the signal is written, so moving that threshold does not re-read the graph.
539
+ const ownFilesInBoot = bootInputs
540
+ .filter(([input]) => isOwn(input))
541
+ .map(([path, bytes]) => ({ path, bytes }))
542
+ .toSorted((a, b) => b.bytes - a.bytes);
543
+ // --- Tree ----------------------------------------------------------------------------------
544
+ const groupsOf = (file) => {
545
+ const groups = new Map();
546
+ const fileInputs = inputsOf(file);
547
+ for (const [input, bytes] of fileInputs) {
548
+ const pkg = (0, format_utils_1.packageOf)(input);
549
+ const key = pkg ?? (0, format_utils_1.projectFolderOf)(input);
550
+ const group = groups.get(key) ?? { bytes: 0, files: [], isPackage: pkg !== null };
551
+ group.bytes += bytes;
552
+ group.files.push({ label: pkg ? (0, format_utils_1.shortName)(input) : input, bytes });
553
+ groups.set(key, group);
554
+ }
555
+ return groups;
556
+ };
557
+ const buildTree = (files, zone) => files
558
+ .map((file) => ({
559
+ id: file,
560
+ label: (0, format_utils_1.baseName)(file),
561
+ bytes: sizeOf(file),
562
+ rawBytes: outputs[file]?.bytes ?? 0,
563
+ kind: 'chunk',
564
+ zone,
565
+ screens: screenCount.get(file) ?? 0,
566
+ children: [...groupsOf(file)]
567
+ .toSorted((a, b) => b[1].bytes - a[1].bytes)
568
+ .map(([name, group]) => ({
569
+ id: `${file}::${name}`,
570
+ label: name,
571
+ bytes: group.bytes,
572
+ kind: group.isPackage ? 'package' : 'folder',
573
+ children: group.files
574
+ .toSorted((a, b) => b.bytes - a.bytes)
575
+ .map((child) => ({
576
+ id: `${file}::${name}::${child.label}`,
577
+ label: child.label,
578
+ bytes: child.bytes,
579
+ kind: 'file',
580
+ children: [],
581
+ })),
582
+ })),
583
+ }))
584
+ .toSorted((a, b) => b.bytes - a.bytes);
585
+ const sharedFiles = sharedChunks.map(c => c.file);
586
+ const ownFiles = [...screenCount].filter(([, n]) => n === 1).map(([file]) => file);
587
+ const tree = [
588
+ ...buildTree([...boot], 'boot'),
589
+ ...buildTree(sharedFiles, 'shared'),
590
+ ...buildTree(ownFiles, 'own'),
591
+ ];
592
+ const chunkCache = new Map();
593
+ /**
594
+ * The figures that come out of the same graph and were not being computed: exclusive weight,
595
+ * barrels, cycles, mixed imports, bytes paid twice, twin screens.
596
+ *
597
+ * Worked out on first use rather than here. They cost one walk of the graph per bootstrap
598
+ * bucket, and the analysis is run twice on every report — once in the unit being shown, once in
599
+ * raw bytes so a raw baseline has something to compare against — while only one of the two is
600
+ * ever asked for these. Memoised, so the signals and the panels share the one computation.
601
+ */
602
+ let computed = null;
603
+ const insights = () => {
604
+ computed ??= (0, insights_1.graphInsightsOf)({
605
+ inputs,
606
+ roots: [mainSource, ...alsoStarted.map(([, out]) => out.entryPoint)].filter(file => typeof file === 'string'),
607
+ isOwn,
608
+ modules,
609
+ boot,
610
+ bootBytesOf: file => bootBytesByInput.get(file) ?? 0,
611
+ screens,
612
+ sizeOf,
613
+ filesByBucket: bucketFiles,
614
+ packageImporters,
615
+ });
616
+ return computed;
617
+ };
618
+ return {
619
+ insights,
620
+ bootBytes,
621
+ bootRawBytes,
622
+ bootFiles: boot.size,
623
+ bootChunks: [...boot],
624
+ startup,
625
+ allChunks: Object.keys(outputs).filter(file => isJs(file)),
626
+ bootBuckets: [...buckets.values()].toSorted((a, b) => b.bytes - a.bytes),
627
+ bootBucketTotal,
628
+ serverOutputs,
629
+ deferredBlocks: (0, entries_1.labelledByWeight)(kinds.blocks, format_utils_1.screenLabel, sizeOf),
630
+ routeGroupers: (0, entries_1.labelledByWeight)(kinds.groupers, format_utils_1.screenLabel, sizeOf),
631
+ lazyData: (0, entries_1.labelledByWeight)(kinds.data, format_utils_1.screenLabel, sizeOf),
632
+ unreachable,
633
+ marks: marks ?? new Map(),
634
+ screens,
635
+ sharedChunks,
636
+ chunkScreens,
637
+ tree,
638
+ chunkImporters: (0, blast_1.chunkImportersOf)(outputs),
639
+ packageImporters,
640
+ ownImporters,
641
+ bootChains,
642
+ screenLoaders,
643
+ commonJs,
644
+ duplicates,
645
+ ownFilesInBoot,
646
+ modules,
647
+ chainTo,
648
+ splitSource: exact && exact.size > 0 ? 'sourcemap' : 'metafile',
649
+ splitDrift: (0, split_drift_1.splitDriftOf)(outputs, exact ?? null),
650
+ chunkOf: file => {
651
+ const cached = chunkCache.get(file);
652
+ if (cached) {
653
+ return cached;
654
+ }
655
+ const info = chunkInfo(file);
656
+ chunkCache.set(file, info);
657
+ return info;
658
+ },
659
+ };
660
+ };
661
+ exports.analyze = analyze;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * The shapes the bundle analysis produces. Split from `analysis.ts` so the file that computes them
4
+ * reads as computation only.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });