@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,11 @@
1
+ "use strict";
2
+ /**
3
+ UI strings. Signals live apart, in `findings.ts`.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.pct = exports.LANGS = void 0;
7
+ /** The languages there are. One list, so adding a third does not have to be found in the command. */
8
+ exports.LANGS = ['en', 'es'];
9
+ /** A ratio as a percentage, the way both languages write it inside a sentence. */
10
+ const pct = (ratio) => `${Math.round(ratio * 100)} %`;
11
+ exports.pct = pct;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UI = void 0;
4
+ const en_1 = require("./en");
5
+ const es_1 = require("./es");
6
+ /** The strings of both languages, picked by `I18nService`. */
7
+ exports.UI = { es: es_1.ES, en: en_1.EN };
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ /**
3
+ * The import graph read out of the compiled folder itself, for the builds that write no stats file.
4
+ *
5
+ * An ES module bundle carries its own graph in plain sight: `import{a}from"./chunk-X.js"` keeps two
6
+ * files together, `import("./chunk-Y.js")` is the lazy boundary, and both are written in the code
7
+ * that ships. Nothing else is needed to answer what the report answers — what the first load pulls
8
+ * in, what a screen adds on top, and what several screens pay for twice. That is why this reads the
9
+ * folder rather than a format: `stats.json` belongs to esbuild, and everything built on Vite,
10
+ * Rollup or Rolldown never writes one.
11
+ *
12
+ * Two things are deliberately not attempted:
13
+ *
14
+ * - **A JavaScript parser.** Specifiers are found with regular expressions, which will also match
15
+ * the odd string inside a comment or a template. What makes that harmless is the last step: a
16
+ * match is only kept when the file it points at **exists in the folder**. The list of files is
17
+ * already there, so a false positive points at nothing and drops out on its own.
18
+ * - **The imports between source files.** The bundler erased them: inside one chunk there is no
19
+ * `import` statement left to read. What the source maps do give is which source each stretch of
20
+ * generated code came from, and that answers the two questions that matter — what each chunk
21
+ * carries, and which file wrote each dynamic import. The chain from the entry to a package, which
22
+ * needs file-to-file edges, is the one thing a folder cannot answer and the report leaves empty.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.readBundleGraph = exports.entrySourceOf = exports.resolveFrom = void 0;
26
+ const sourcemap_1 = require("../analysis/sourcemap");
27
+ const format_utils_1 = require("../format/format.utils");
28
+ const JS_FILE = /\.m?js$/i;
29
+ /**
30
+ * `import … from "x"`, `export … from "x"` and the bare `import "x"`. All three make the browser
31
+ * fetch the other file as soon as it has parsed this one, which is the only thing that matters
32
+ * here. The character class stops at `;` so a match cannot run past the end of its statement.
33
+ */
34
+ const STATIC_IMPORT = /\b(?:import|export)\b(?:[^'"`;()]*\bfrom\s*)?['"]([^'"]+)['"]/g;
35
+ /** `import("x")` in the three quotes a minifier may leave behind — Rolldown writes backticks. */
36
+ const DYNAMIC_IMPORT = /\bimport\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g;
37
+ /** Vite's table of preloadable files, written once at the top of any chunk that needs one. */
38
+ const MAP_DEPS_TABLE = /__vite__mapDeps\s*=[^[]*\[([^\]]*)\]/;
39
+ /** Each use of that table: the indices of the files that one dynamic import asks for. */
40
+ const MAP_DEPS_CALL = /__vite__mapDeps\(\s*\[([^\]]*)\]\s*\)/g;
41
+ /** The same list written out instead of indexed, which is what an unminified build carries. */
42
+ const PATH_LIST = /\[\s*(?:['"`][^'"`\]]+['"`]\s*,\s*)+['"`][^'"`\]]+['"`]\s*\]/g;
43
+ /** The quoted strings of a list, whatever quote it was written with. */
44
+ const QUOTED = /['"`]([^'"`]+)['"`]/g;
45
+ /**
46
+ * What a bundler that resolves imports at run time leaves behind in its entry chunk: webpack's
47
+ * module table, Turbopack's, and the marker Next writes next to them. None of these builds has a
48
+ * graph in the file — the imports are numbers the loader looks up — so reading one as if it did
49
+ * produces a report of one chunk and no screens, which is the worst possible answer: confident,
50
+ * detailed and wrong.
51
+ *
52
+ * ⚠️ Each of these matches the **shape** of the registry being written, not the mere mention of a
53
+ * name. The first version looked for `webpackChunk` anywhere and Loadline refused its own build,
54
+ * because this very file talks about webpack and ends up in the bundle. Anything that writes about
55
+ * bundlers — a tool, a blog, a documentation site — would have been refused the same way.
56
+ *
57
+ * ⚠️ The registry is assigned with `=` or with `||=`, and both have to be here. webpack used to
58
+ * write `self.webpackChunkX=self.webpackChunkX||[]`; when the output targets browsers that have
59
+ * logical assignment it writes `globalThis.webpackChunkX||=[]` instead, and only the second form
60
+ * survives in a Create React App build. Matching just `=` let one through: Loadline read a
61
+ * `react-scripts build` as a good build — one bootstrap, zero screens, "nothing stands out" — which
62
+ * is the same failure Next.js produced before it was checked, from the same rule missing a shape.
63
+ * `__webpack_require__` is no help as a fallback here: the minifier mangles it to one letter.
64
+ */
65
+ const LOADER_RUNTIME = /webpackChunk\w*\s*(?:\|\|)?=|__webpack_require__\s*\(|globalThis\.TURBOPACK|__next_f\.push/;
66
+ /** Where a chunk says its map is. Absent from a build that ships none, which is most of them. */
67
+ const MAP_URL = /\/\/#\s*sourceMappingURL=(\S+)/;
68
+ /** The hash a bundler appends to a chunk name, which is not part of the module it came from. */
69
+ const HASH = /-[\w-]{8,}$/;
70
+ /**
71
+ * A specifier written inside a chunk turned into the path of another file of the folder.
72
+ *
73
+ * Two shapes turn up and they resolve differently: `./sibling.js` is relative to the chunk that
74
+ * wrote it, and `assets/other.js` — how Vite writes its preload lists — is relative to the root of
75
+ * the folder. Whatever resolves to nothing in the folder, a bare `react` included, is not a file of
76
+ * this build and the caller drops it.
77
+ */
78
+ const resolveFrom = (chunk, specifier) => {
79
+ const slash = chunk.lastIndexOf('/');
80
+ const relative = specifier.startsWith('./') || specifier.startsWith('../');
81
+ const segments = relative && slash !== -1 ? chunk.slice(0, slash).split('/') : [];
82
+ for (const part of specifier.replace(/^\//, '').split('/')) {
83
+ if (part === '' || part === '.') {
84
+ continue;
85
+ }
86
+ if (part === '..') {
87
+ segments.pop();
88
+ }
89
+ else {
90
+ segments.push(part);
91
+ }
92
+ }
93
+ return segments.join('/');
94
+ };
95
+ exports.resolveFrom = resolveFrom;
96
+ /** The offset every line starts at, so a match in the text can be looked up in the map. */
97
+ const lineStartsOf = (code) => {
98
+ const starts = [0];
99
+ for (let index = code.indexOf('\n'); index !== -1; index = code.indexOf('\n', index + 1)) {
100
+ starts.push(index + 1);
101
+ }
102
+ return starts;
103
+ };
104
+ /** An offset in the text as the line and column a source map is keyed by. */
105
+ const positionOf = (starts, offset) => {
106
+ let low = 0;
107
+ let high = starts.length - 1;
108
+ while (low < high) {
109
+ const middle = Math.ceil((low + high) / 2);
110
+ if ((starts[middle] ?? 0) <= offset) {
111
+ low = middle;
112
+ }
113
+ else {
114
+ high = middle - 1;
115
+ }
116
+ }
117
+ return { line: low, column: offset - (starts[low] ?? 0) };
118
+ };
119
+ /** Every file name of a preload list, resolved, or `null` when one of them is not a file here. */
120
+ const groupOf = (names, exists) => {
121
+ const paths = names.map(name => (0, exports.resolveFrom)('', name));
122
+ return paths.length > 1 && paths.every(path => path !== '' && exists(path)) ? paths : null;
123
+ };
124
+ /**
125
+ * The preload lists of a chunk: the sets of files Vite asks for in one go.
126
+ *
127
+ * Vite does not wait for a lazy chunk to arrive and be parsed before fetching what that chunk
128
+ * imports; it bakes the list into the call and fires the whole set off at once. Angular does not do
129
+ * this. Without reading these, every screen of a Vite application would be counted one round trip
130
+ * deeper than it is.
131
+ */
132
+ const groupsIn = (code, exists) => {
133
+ const groups = [];
134
+ const table = MAP_DEPS_TABLE.exec(code);
135
+ const files = table ? [...(table[1] ?? '').matchAll(QUOTED)].map(match => match[1] ?? '') : [];
136
+ for (const call of code.matchAll(MAP_DEPS_CALL)) {
137
+ const names = (call[1] ?? '').split(',').map(index => files[Number(index.trim())] ?? '');
138
+ const group = groupOf(names, exists);
139
+ if (group) {
140
+ groups.push(group);
141
+ }
142
+ }
143
+ for (const list of code.matchAll(PATH_LIST)) {
144
+ // The table itself is a list of file names, and would otherwise read as one huge group.
145
+ const inTable = !!table && list.index >= table.index && list.index < table.index + table[0].length;
146
+ const group = inTable
147
+ ? null
148
+ : groupOf([...(list[0].matchAll(QUOTED) ?? [])].map(m => m[1] ?? ''), exists);
149
+ if (group) {
150
+ groups.push(group);
151
+ }
152
+ }
153
+ return groups;
154
+ };
155
+ /** Reads one chunk: its edges and its preload lists, plus who wrote each dynamic import. */
156
+ const readChunk = (chunk, code, segments, exists) => {
157
+ const statics = new Set();
158
+ const dynamics = [];
159
+ const mapped = segments.length > 0;
160
+ const starts = mapped ? lineStartsOf(code) : [];
161
+ for (const match of code.matchAll(STATIC_IMPORT)) {
162
+ const target = (0, exports.resolveFrom)(chunk, match[1] ?? '');
163
+ if (target !== chunk && exists(target)) {
164
+ statics.add(target);
165
+ }
166
+ }
167
+ for (const match of code.matchAll(DYNAMIC_IMPORT)) {
168
+ const target = (0, exports.resolveFrom)(chunk, match[2] ?? '');
169
+ if (target === chunk || !exists(target)) {
170
+ continue;
171
+ }
172
+ // Which of the files inside this chunk wrote the import. The map answers it exactly, so
173
+ // "who lazy-loads this screen" is read rather than guessed even in a chunk holding thirty
174
+ // files. Without a map it stays open and the entry of the chunk answers for it later.
175
+ const position = mapped ? positionOf(starts, match.index) : null;
176
+ const from = position ? (0, sourcemap_1.sourceAt)(segments, position.line, position.column) : null;
177
+ dynamics.push({ target, from: from ? (0, sourcemap_1.sourcePathOf)(from) : null });
178
+ }
179
+ return { statics: [...statics], dynamics, groups: groupsIn(code, exists) };
180
+ };
181
+ /**
182
+ * Which source file a chunk starts at.
183
+ *
184
+ * One source is the whole answer when there is only one. Otherwise the bundler's own name for the
185
+ * chunk decides: Rollup and esbuild both name a chunk after the module it starts at, so
186
+ * `orders.page-DgHWSolo.js` came from the source called `orders.page`. When neither settles it the
187
+ * last source is taken, because a chunk is written dependencies first and the module it exists for
188
+ * goes at the end.
189
+ */
190
+ const entrySourceOf = (chunk, sources) => {
191
+ if (sources.length <= 1) {
192
+ return sources[0] ?? null;
193
+ }
194
+ const stem = (0, format_utils_1.baseName)(chunk).replace(JS_FILE, '').replace(HASH, '');
195
+ const named = sources.find(source => (0, format_utils_1.baseName)(source).replace(/\.[^.]+$/, '') === stem);
196
+ return named ?? sources.at(-1) ?? null;
197
+ };
198
+ exports.entrySourceOf = entrySourceOf;
199
+ /** The map of a chunk, when the folder ships one next to it. */
200
+ const mapOf = async (chunk, code, byPath) => {
201
+ const url = MAP_URL.exec(code)?.[1];
202
+ const named = url && !url.startsWith('data:') ? byPath.get((0, exports.resolveFrom)(chunk.path, url)) : undefined;
203
+ const file = named ?? byPath.get(`${chunk.path}.map`);
204
+ if (!file) {
205
+ return null;
206
+ }
207
+ try {
208
+ const parsed = JSON.parse(await file.text());
209
+ return (0, sourcemap_1.isSourceMap)(parsed) ? parsed : null;
210
+ }
211
+ catch {
212
+ // A truncated map costs the breakdown of one chunk, not the report.
213
+ return null;
214
+ }
215
+ };
216
+ /** Reads every chunk of the folder once: text, map, edges and weights. */
217
+ const readChunks = async (chunks, byPath) => {
218
+ const read = new Map();
219
+ const splits = new Map();
220
+ const runtimes = new Set();
221
+ const exists = (path) => byPath.has(path);
222
+ for (const chunk of chunks) {
223
+ const code = await chunk.text();
224
+ if (LOADER_RUNTIME.test(code)) {
225
+ runtimes.add(chunk.path);
226
+ }
227
+ const map = await mapOf(chunk, code, byPath);
228
+ const segments = map ? (0, sourcemap_1.segmentsOf)(map) : [];
229
+ const raw = map ? (0, sourcemap_1.bytesBySource)(map, code) : new Map();
230
+ const split = new Map();
231
+ for (const [source, bytes] of raw) {
232
+ const path = (0, sourcemap_1.sourcePathOf)(source);
233
+ split.set(path, (split.get(path) ?? 0) + bytes);
234
+ }
235
+ if (raw.size > 0) {
236
+ // Keyed and named the way `readSourceMaps` does it, so what the folder reader stores
237
+ // is the same object whichever of the two paths produced it.
238
+ splits.set((0, format_utils_1.baseName)(chunk.path), raw);
239
+ }
240
+ const sources = map ? map.sources.map(source => (0, sourcemap_1.sourcePathOf)(source)) : [];
241
+ read.set(chunk.path, { ...readChunk(chunk.path, code, segments, exists), split, sources });
242
+ }
243
+ return { read, splits, runtimes };
244
+ };
245
+ /**
246
+ * Which chunks the loader asks for in the same round trip, from the preload lists.
247
+ *
248
+ * A list only means something once it is tied to the import it belongs to, and what ties it is that
249
+ * exactly one of its files is a chunk this same chunk lazily imports. When two of them are, the
250
+ * list is left alone: counting a screen as arriving with something it does not would understate the
251
+ * round trips, and that is the direction that flatters the build.
252
+ */
253
+ const parallelOf = (read) => {
254
+ const parallel = new Map();
255
+ const targetOf = (group, lazy) => {
256
+ const inside = group.filter(path => lazy.has(path));
257
+ return inside.length === 1 ? (inside[0] ?? null) : null;
258
+ };
259
+ for (const info of read.values()) {
260
+ const lazy = new Set(info.dynamics.map(entry => entry.target));
261
+ for (const group of info.groups) {
262
+ const target = targetOf(group, lazy);
263
+ if (target) {
264
+ const rest = group.filter(path => path !== target);
265
+ parallel.set(target, [...new Set([...(parallel.get(target) ?? []), ...rest])]);
266
+ }
267
+ }
268
+ }
269
+ return parallel;
270
+ };
271
+ /**
272
+ * Builds the metafile the analysis takes out of a compiled folder.
273
+ *
274
+ * @param files every file of the folder, with its path relative to the folder itself
275
+ * @param entries the file names the page names in a `<script>` tag. They are what tells an entry
276
+ * chunk from a shared one: a bundler writes the shared code of an application into
277
+ * its entry chunk, so the entry ends up imported by its own children and cannot be
278
+ * found by looking for a chunk that nobody imports.
279
+ */
280
+ const readBundleGraph = async (files, entries) => {
281
+ const byPath = new Map(files.map(file => [file.path, file]));
282
+ const chunks = files.filter(file => JS_FILE.test(file.path));
283
+ const { read, splits, runtimes } = await readChunks(chunks, byPath);
284
+ const roots = chunks.filter(chunk => entries.has((0, format_utils_1.baseName)(chunk.path))).map(chunk => chunk.path);
285
+ if (roots.length === 0) {
286
+ throw new Error('NO_PAGE');
287
+ }
288
+ const lazyTargets = new Set([...read.values()].flatMap(info => info.dynamics.map(entry => entry.target)));
289
+ /**
290
+ * A folder whose entry carries a run-time loader and where nothing lazily imports anything is
291
+ * not an ES module bundle: it is webpack's or Turbopack's output, and its graph is a table of
292
+ * numbers this cannot read. Saying so is the whole point — pointed at a Next.js export, the
293
+ * report came out as one bootstrap of seven files, zero screens and "nothing stands out".
294
+ *
295
+ * Both halves are required on purpose. The marker alone would refuse an ES module bundle that
296
+ * happens to carry one webpack-built dependency; no lazy edges alone is a perfectly ordinary
297
+ * application with every route eager, which is a build this reads correctly today.
298
+ */
299
+ if (lazyTargets.size === 0 && roots.some(root => runtimes.has(root))) {
300
+ throw new Error('NOT_ESM_GRAPH');
301
+ }
302
+ const entryChunks = new Set([...roots, ...lazyTargets]);
303
+ /**
304
+ * The name the source graph knows a chunk by. It is a real file when the maps said so, and the
305
+ * chunk itself when they did not: without maps the smallest thing the folder knows about is a
306
+ * chunk, and naming a screen after its file is what the folder actually says.
307
+ */
308
+ const sourceKeys = new Map([...read].map(([chunk, info]) => [chunk, (0, exports.entrySourceOf)(chunk, info.sources) ?? chunk]));
309
+ const inputs = {};
310
+ const inputOf = (path) => (inputs[path] ??= { bytes: 0, imports: [] });
311
+ for (const info of read.values()) {
312
+ for (const [source, bytes] of info.split) {
313
+ inputOf(source).bytes += bytes;
314
+ }
315
+ }
316
+ for (const [chunk, info] of read) {
317
+ for (const { target, from } of info.dynamics) {
318
+ const importer = from ?? sourceKeys.get(chunk);
319
+ const imported = sourceKeys.get(target);
320
+ if (importer && imported) {
321
+ inputOf(importer).imports.push({ path: imported, kind: 'dynamic-import' });
322
+ }
323
+ }
324
+ }
325
+ const outputs = {};
326
+ for (const chunk of chunks) {
327
+ const info = read.get(chunk.path);
328
+ const dynamics = [...new Set(info?.dynamics.map(entry => entry.target))];
329
+ const output = {
330
+ bytes: chunk.bytes,
331
+ imports: [
332
+ ...(info?.statics ?? []).map((path) => ({ path, kind: 'import-statement' })),
333
+ ...dynamics.map((path) => ({ path, kind: 'dynamic-import' })),
334
+ ],
335
+ };
336
+ if (info && info.split.size > 0) {
337
+ output.inputs = Object.fromEntries([...info.split].map(([path, bytes]) => [path, { bytesInOutput: bytes }]));
338
+ }
339
+ if (entryChunks.has(chunk.path)) {
340
+ output.entryPoint = sourceKeys.get(chunk.path) ?? chunk.path;
341
+ }
342
+ outputs[chunk.path] = output;
343
+ }
344
+ return { meta: { inputs, outputs }, parallel: parallelOf(read), splits };
345
+ };
346
+ exports.readBundleGraph = readBundleGraph;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ /** What the folder reader takes and what it gives back. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pageCssOf = exports.sniff = exports.bundleFilesOf = exports.brotliSizes = exports.gzipSizes = exports.gzipSize = exports.isLockName = exports.isContextName = exports.hashOf = exports.isSearchable = exports.isAsset = void 0;
4
+ const metafile_types_1 = require("../analysis/metafile.types");
5
+ const baseline_1 = require("../baseline/baseline");
6
+ const loadline_config_1 = require("../config/loadline-config");
7
+ /** The files that make up the build output, the only ones worth compressing. */
8
+ const isAsset = (name) => /\.(?:m?js|css)$/i.test(name);
9
+ exports.isAsset = isAsset;
10
+ /**
11
+ * Files worth reading as text, to find which names anything in the folder mentions.
12
+ *
13
+ * More than the code on purpose: a web app manifest names the icons and a `robots.txt` names a
14
+ * sitemap. Reading only the chunks reported both of those as files nothing reaches — a wrong
15
+ * answer given with exactly the same confidence as a right one.
16
+ */
17
+ const isSearchable = (name) => /\.(?:m?js|css|json|webmanifest|xml|txt|svg)$/i.test(name);
18
+ exports.isSearchable = isSearchable;
19
+ /**
20
+ * The content hash of a file, for telling "two files of the same size" from "the same file twice".
21
+ *
22
+ * Only worth doing on what a duplicate would be — a font, a picture — and only below a size where
23
+ * reading the whole thing into memory is reasonable. A fifty-megabyte video is left uncompared and
24
+ * the report says so, rather than reporting "no duplicates" and meaning "nobody looked".
25
+ */
26
+ const hashOf = async (file) => {
27
+ if (file.size > 8 * 1024 * 1024 || typeof crypto?.subtle?.digest !== 'function') {
28
+ return null;
29
+ }
30
+ const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());
31
+ return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');
32
+ };
33
+ exports.hashOf = hashOf;
34
+ /**
35
+ * Files read for the project context: what the pipeline builds and which budgets apply.
36
+ *
37
+ * Any YAML is accepted, because a pipeline file can be called anything and asking somebody to
38
+ * rename theirs would be worse. What a dropped `docker-compose.yml` gets is not a place in the
39
+ * report: whether it actually is a pipeline is decided after reading it, by whether anything in it
40
+ * looks like a build.
41
+ */
42
+ const isContextName = (name) => name === 'angular.json' || name === 'package.json' || /\.ya?ml$/i.test(name) || /^jenkinsfile$/i.test(name);
43
+ exports.isContextName = isContextName;
44
+ /** A lock file, in any of the three formats a package manager writes. */
45
+ const isLockName = (name) => /^(?:package-lock|npm-shrinkwrap)\.json$/i.test(name) || /^(?:pnpm-lock\.ya?ml|yarn\.lock)$/i.test(name);
46
+ exports.isLockName = isLockName;
47
+ /**
48
+ * What a file compresses to, done in the browser. Streamed rather than read whole: a build folder
49
+ * is tens of megabytes, and nothing here needs the bytes themselves, only how many come out.
50
+ */
51
+ const gzipSize = async (file) => {
52
+ const stream = file.stream().pipeThrough(new CompressionStream('gzip'));
53
+ const reader = stream.getReader();
54
+ let size = 0;
55
+ try {
56
+ for (;;) {
57
+ const { done, value } = await reader.read();
58
+ if (done) {
59
+ break;
60
+ }
61
+ size += value.length;
62
+ }
63
+ }
64
+ finally {
65
+ reader.releaseLock();
66
+ }
67
+ return size;
68
+ };
69
+ exports.gzipSize = gzipSize;
70
+ /** Every asset of the folder, compressed. Keyed by file name, which is how the metafile names them. */
71
+ const gzipSizes = async (files, onProgress) => {
72
+ const sizes = new Map();
73
+ for (const file of files) {
74
+ sizes.set(file.name, await (0, exports.gzipSize)(file));
75
+ // Tens of megabytes go through here one file at a time, and the page used to say nothing
76
+ // about it beyond one line of grey text that never changed.
77
+ onProgress?.(sizes.size, files.length);
78
+ }
79
+ return sizes;
80
+ };
81
+ exports.gzipSizes = gzipSizes;
82
+ /**
83
+ * Sizes of the pre-compressed files of the folder. Nothing has to be decompressed: the size of a
84
+ * `.br` file *is* the brotli figure.
85
+ */
86
+ const brotliSizes = (files) => {
87
+ const sizes = new Map();
88
+ for (const file of files) {
89
+ // `.br` is what every server and every plugin writes; `.brotli` turns up often enough that
90
+ // not reading it means silently showing gzip figures on a folder that had brotli ones.
91
+ const found = /^(.*\.(?:m?js|css))\.(?:br|brotli)$/i.exec(file.name);
92
+ if (found?.[1]) {
93
+ sizes.set(found[1], file.size);
94
+ }
95
+ }
96
+ return sizes;
97
+ };
98
+ exports.brotliSizes = brotliSizes;
99
+ /**
100
+ * The picked folder as the folder reader takes it: each file with its path **inside** the folder.
101
+ *
102
+ * A directory picker reports `browser/assets/main-A1B2C3.js`, which names the folder somebody
103
+ * happened to pick; what a chunk writing `./sibling.js` means is `assets/sibling.js`, from the root
104
+ * of the build. Dropping the first segment is what makes the two line up.
105
+ */
106
+ const bundleFilesOf = (files) => files.map(file => {
107
+ const inside = (file.webkitRelativePath || '').split('/').slice(1).join('/');
108
+ return { path: inside || file.name, bytes: file.size, text: () => file.text() };
109
+ });
110
+ exports.bundleFilesOf = bundleFilesOf;
111
+ /** What a dropped file is, without loading it. Cheap: reads the name, then the JSON if needed. */
112
+ const sniff = async (file) => {
113
+ // A lock file is decided by its name, before anything is read: `pnpm-lock.yaml` would otherwise
114
+ // be taken for a pipeline by the rule above, which accepts any YAML.
115
+ if ((0, exports.isLockName)(file.name)) {
116
+ return 'lock';
117
+ }
118
+ if ((0, exports.isContextName)(file.name)) {
119
+ return 'context';
120
+ }
121
+ if (!/\.json$/i.test(file.name)) {
122
+ return 'unknown';
123
+ }
124
+ try {
125
+ const parsed = JSON.parse(await file.text());
126
+ if ((0, baseline_1.isSnapshot)(parsed)) {
127
+ return 'baseline';
128
+ }
129
+ if ((0, loadline_config_1.isLoadlineConfig)(parsed)) {
130
+ return 'config';
131
+ }
132
+ if ((0, metafile_types_1.isMetafile)(parsed)) {
133
+ return 'stats';
134
+ }
135
+ // An audit report has no name of its own — people redirect it to whatever they like — so it
136
+ // is recognised by the two shapes npm and pnpm write.
137
+ const shape = parsed;
138
+ return shape.vulnerabilities || shape.advisories ? 'audit' : 'unknown';
139
+ }
140
+ catch {
141
+ return 'unknown';
142
+ }
143
+ };
144
+ exports.sniff = sniff;
145
+ /**
146
+ * The stylesheets the page names, weighed with the same maps every other figure is weighed with.
147
+ *
148
+ * A name the folder does not hold is dropped rather than counted as zero: a page left over from
149
+ * another build would otherwise add a stylesheet of no bytes to the first load and say nothing.
150
+ */
151
+ const pageCssOf = (named, sizes) => {
152
+ const files = named.filter(name => sizes.raw.has(name));
153
+ if (files.length === 0) {
154
+ return null;
155
+ }
156
+ const total = (from) => files.reduce((sum, file) => sum + (from.get(file) ?? 0), 0);
157
+ const brotli = files.every(file => sizes.brotli.has(file)) ? total(sizes.brotli) : null;
158
+ return { files, raw: total(sizes.raw), gzip: total(sizes.gzip), brotli };
159
+ };
160
+ exports.pageCssOf = pageCssOf;