@bymaksym/loadline 0.1.0 → 1.0.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 (54) hide show
  1. package/README.md +66 -7
  2. package/dist/cli/cli/args.js +33 -3
  3. package/dist/cli/cli/declared.js +52 -0
  4. package/dist/cli/cli/html-report.js +107 -0
  5. package/dist/cli/cli/locate.js +60 -0
  6. package/dist/cli/cli/main.js +118 -5
  7. package/dist/cli/cli/memory.js +78 -0
  8. package/dist/cli/cli/read-build.js +8 -4
  9. package/dist/cli/cli/render-json.js +8 -5
  10. package/dist/cli/cli/render-markdown.js +1 -1
  11. package/dist/cli/cli/render-pr.js +5 -3
  12. package/dist/cli/cli/render-sarif.js +3 -3
  13. package/dist/cli/cli/render-text.js +63 -28
  14. package/dist/cli/cli/report.js +9 -3
  15. package/dist/cli/cli/since-last.js +45 -0
  16. package/dist/cli/cli/text.js +54 -19
  17. package/dist/cli/src/app/core/analysis/analysis.js +8 -4
  18. package/dist/cli/src/app/core/analysis/barrels.js +9 -2
  19. package/dist/cli/src/app/core/analysis/entries.js +41 -6
  20. package/dist/cli/src/app/core/analysis/metafile.types.js +14 -6
  21. package/dist/cli/src/app/core/analysis/split-drift.js +12 -6
  22. package/dist/cli/src/app/core/assets/assets.js +4 -2
  23. package/dist/cli/src/app/core/caching/caching.js +3 -3
  24. package/dist/cli/src/app/core/deps/deps.js +37 -7
  25. package/dist/cli/src/app/core/deps/pins.js +63 -0
  26. package/dist/cli/src/app/core/export/summary.js +27 -9
  27. package/dist/cli/src/app/core/findings/actions.js +63 -6
  28. package/dist/cli/src/app/core/findings/assets.js +30 -5
  29. package/dist/cli/src/app/core/findings/boot-single.js +76 -0
  30. package/dist/cli/src/app/core/findings/caching.js +1 -1
  31. package/dist/cli/src/app/core/findings/dupes.js +65 -0
  32. package/dist/cli/src/app/core/findings/effort.js +2 -0
  33. package/dist/cli/src/app/core/findings/finding-html.js +14 -1
  34. package/dist/cli/src/app/core/findings/finding-text.js +104 -31
  35. package/dist/cli/src/app/core/findings/finding.types.js +1 -0
  36. package/dist/cli/src/app/core/findings/findings.js +22 -38
  37. package/dist/cli/src/app/core/findings/graph.js +4 -4
  38. package/dist/cli/src/app/core/findings/scan.js +13 -3
  39. package/dist/cli/src/app/core/findings/shipped.js +3 -5
  40. package/dist/cli/src/app/core/format/format.utils.js +16 -9
  41. package/dist/cli/src/app/core/i18n/en.js +108 -48
  42. package/dist/cli/src/app/core/i18n/es.js +114 -50
  43. package/dist/cli/src/app/core/intake/bundle-graph.js +6 -5
  44. package/dist/cli/src/app/core/intake/dist-files.js +5 -2
  45. package/dist/cli/src/app/core/intake/embedded.js +46 -0
  46. package/dist/cli/src/app/core/intake/index-html.js +66 -16
  47. package/dist/cli/src/app/core/project/budget-advice.js +14 -10
  48. package/dist/cli/src/app/core/project/project-context.js +74 -16
  49. package/dist/cli/src/app/core/scan/scan.js +59 -21
  50. package/dist/cli/src/app/core/scan/secrets.js +0 -0
  51. package/dist/cli/src/app/core/situation/situation.js +3 -4
  52. package/dist/cli/src/app/state/report-messages.utils.js +1 -4
  53. package/loadline.html +22 -24
  54. package/package.json +60 -30
package/README.md CHANGED
@@ -1,4 +1,6 @@
1
- # Loadline
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/bymaksym/LoadLine/main/.github/banner.png?v=2" alt="Loadline — weight per screen" width="100%">
3
+ </p>
2
4
 
3
5
  > Weight per screen: what someone opening a screen of your app actually downloads, how much of that
4
6
  > everybody else pays for too, and what is worth moving elsewhere.
@@ -24,10 +26,21 @@ inside the page.
24
26
  **In the terminal.**
25
27
 
26
28
  ```bash
29
+ npx @bymaksym/loadline dist/app # the build root: the metafile and browser/ are found
30
+ npx @bymaksym/loadline dist/app --html loadline.html --open # and the page, with the build already in it
27
31
  npx @bymaksym/loadline dist/app/browser # the build folder on its own
28
- npx @bymaksym/loadline dist/app/stats.json --dist dist/app/browser
32
+ npx @bymaksym/loadline dist/app/browser-stats.json --dist dist/app/browser
29
33
  ```
30
34
 
35
+ Pointed at the root of an Angular build, the command finds `browser-stats.json` (Angular 22.2) or
36
+ `stats.json` (up to 22.1) and the `browser/` folder next to it. `--html` writes the same page as
37
+ `loadline.html` with the files the command read inside it, so a script can produce a report somebody
38
+ opens with a double click — treemap, search and every chunk included, nothing to drag in.
39
+
40
+ Each run is remembered in `node_modules/.cache/loadline`, and the next run of the same build says
41
+ what moved — `since the last run: bootstrap 156 kB → 129 kB (−27 kB)` — without a `--baseline`. It is
42
+ a line and a column, never a gate; `--no-cache` turns it off.
43
+
31
44
  Zero runtime dependencies, no install script, Node 20.19 or newer. `npm i -g @bymaksym/loadline` installs it;
32
45
  `pnpm`, `yarn`, `bun` and `deno` all work, as do `pnpm dlx`, `yarn dlx` and `bunx`. The package also
33
46
  ships `loadline.html` next to the command, under `npm root -g`.
@@ -39,7 +52,7 @@ chunks carry their own import graph.
39
52
 
40
53
  | Build tool | Frameworks | What to pass |
41
54
  | -------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------- |
42
- | esbuild (metafile) | Angular 17+, plain esbuild | `stats.json`, ideally with `--dist` |
55
+ | esbuild (metafile) | Angular 17+, plain esbuild | The build root, or the metafile with `--dist` |
43
56
  | Vite, Rollup, Rolldown | Vue, React, Svelte, Solid, Nuxt, SvelteKit, Astro, React Router 7 | The build folder |
44
57
  | webpack, Turbopack, Rspack | Angular ≤ 16, Next.js, Create React App | Not supported — see [Statoscope](https://github.com/statoscope/statoscope) |
45
58
 
@@ -56,6 +69,10 @@ To get a metafile out of Angular:
56
69
  ng build --configuration <the-one-your-pipeline-deploys> --stats-json
57
70
  ```
58
71
 
72
+ Angular 22.2 and later write it as `dist/<app>/browser-stats.json`; earlier versions as
73
+ `dist/<app>/stats.json`.
74
+ Either way, `loadline dist/<app>` finds it.
75
+
59
76
  ## What you get
60
77
 
61
78
  - **One headline number** — what is downloaded before anything appears.
@@ -67,6 +84,10 @@ ng build --configuration <the-one-your-pipeline-deploys> --stats-json
67
84
  - **Signals with a name and a fix** — shared code labelled as deferred, bootstrap pulled in for a
68
85
  lazy screen, duplicate package versions, CommonJS packages the bundler cannot tree-shake, large
69
86
  data files travelling in the bootstrap, and more.
87
+ - **A map of the bundle** — one rectangle per chunk, sized by what it weighs in the report's unit,
88
+ with what fills it drawn inside, by package and by folder of yours. Click to open a chunk, as in
89
+ `esbuild-visualizer`, with the difference that the area between chunks is what travels and the
90
+ area inside one is each part's raw share, because a compressed share of one module does not exist.
70
91
  - **Search by package or file** — which chunks it is in, what it weighs in each, which screens pay
71
92
  for it, and the chain of imports that brings it in.
72
93
  - **Provenance on every figure** — each threshold says whether it is external, derived or a
@@ -79,6 +100,7 @@ Optional inputs widen the report:
79
100
  | The build folder (`--dist`) | Gzip and brotli figures, per-file weights, first-load round trips |
80
101
  | A previous build or export (`--baseline`) | Per-screen deltas, and what a returning visitor re-downloads |
81
102
  | `angular.json`, `package.json`, the CI file | Whether your size budgets sit in the configuration the pipeline builds |
103
+ | The lock file (`--lock`) | Who brings each package in, and whether a duplicate is pinned beyond reach |
82
104
  | A browser measurement, pasted into Measured | What is actually served: compression, 304s, third parties, real round trips |
83
105
  | Several apps at once | What microfrontends ship twice, and what a shared package would save |
84
106
 
@@ -109,11 +131,19 @@ the next run edits its comment instead of adding another. `--lang en|es` — Eng
109
131
  asked for in Spanish, never read from the machine's locale, which is the same rule the page
110
132
  follows with its language button. `loadline --help` for the full list.
111
133
 
134
+ The comment is worth most when it says what the pull request **adds**, and that needs the figures
135
+ of `main` to compare against. A pipeline keeps nothing between runs — the cache in
136
+ `node_modules/.cache` is gone with the runner — so `main` leaves its snapshot as an artifact on every
137
+ push, and each pull request downloads the latest one and passes it as `--baseline`. Until `main` has
138
+ run once there is nothing to download, and the comment shows plain figures instead of differences.
139
+
112
140
  ```yaml
113
141
  # .github/workflows/loadline.yml
114
142
  name: Loadline
115
- on: pull_request
116
- permissions: { contents: read, pull-requests: write, security-events: write }
143
+ on:
144
+ push: { branches: [main] }
145
+ pull_request:
146
+ permissions: { contents: read, actions: read, pull-requests: write, security-events: write }
117
147
  jobs:
118
148
  weight:
119
149
  runs-on: ubuntu-latest
@@ -122,14 +152,37 @@ jobs:
122
152
  - uses: actions/setup-node@v4
123
153
  with: { node-version: 22 }
124
154
  - run: npm ci && npm run build
125
- - run: npx @bymaksym/loadline dist/app/browser --format pr-comment > comment.md
126
- - run: gh pr comment "$NUMBER" --body-file comment.md --edit-last --create-if-none
155
+
156
+ # The snapshot main left on its last green run: what this pull request is compared to.
157
+ - if: github.event_name == 'pull_request'
158
+ run: |
159
+ run=$(gh run list --branch main --workflow loadline.yml --status success --limit 1 --json databaseId --jq '.[0].databaseId')
160
+ if [ -n "$run" ]; then gh run download "$run" --name loadline-baseline --dir base; fi
161
+ env: { GH_TOKEN: '${{ github.token }}' }
162
+
163
+ - run: |
164
+ baseline=$([ -f base/loadline-baseline.json ] && echo "--baseline base/loadline-baseline.json")
165
+ npx @bymaksym/loadline dist/app/browser $baseline --export loadline-baseline.json --format pr-comment > comment.md
166
+
167
+ - if: github.event_name == 'pull_request'
168
+ run: gh pr comment "$NUMBER" --body-file comment.md --edit-last --create-if-none
127
169
  env: { GH_TOKEN: '${{ github.token }}', NUMBER: '${{ github.event.number }}' }
170
+
171
+ # On main, the snapshot becomes the baseline of every pull request opened after it.
172
+ - if: github.event_name == 'push'
173
+ uses: actions/upload-artifact@v4
174
+ with: { name: loadline-baseline, path: loadline-baseline.json }
175
+
128
176
  - run: npx @bymaksym/loadline dist/app/browser --format sarif > loadline.sarif
129
177
  - uses: github/codeql-action/upload-sarif@v3
130
178
  with: { sarif_file: loadline.sarif }
131
179
  ```
132
180
 
181
+ To make the pull request fail on growth rather than only report it, add one more step after the
182
+ comment, so the comment is posted whatever the verdict:
183
+ `npx @bymaksym/loadline dist/app/browser $baseline --max-growth 20kB` (or `--max-growth-pct 5`).
184
+ With a baseline it judges what this pull request added, not the size of the whole application.
185
+
133
186
  ## Configuration
134
187
 
135
188
  A `loadline.json` in the working directory is read without any flag; `--config <file>` points at
@@ -176,6 +229,12 @@ When opening an issue, the **Copy diagnostics** button at the end of the report
176
229
  lines describing the build and what Loadline decided about it. Package names are real; paths in your
177
230
  own code are replaced by stable hashes, so it can be pasted in public.
178
231
 
232
+ ## Community
233
+
234
+ [Discord — ByMaksymDev Labs](https://discord.gg/ctDJjFF9yT), where Loadline has its own
235
+ channel. Bugs and feature requests are better off as issues here, where they can be found
236
+ again; the chat is for everything that is a conversation.
237
+
179
238
  ## License
180
239
 
181
240
  [MIT](LICENSE). Offered with no commitment of support: issues and pull requests are welcome and may
@@ -43,6 +43,7 @@ const WITH_VALUE = new Set([
43
43
  '--max-growth',
44
44
  '--max-growth-pct',
45
45
  '--fail-on',
46
+ '--html',
46
47
  ]);
47
48
  const EMPTY = {
48
49
  target: '',
@@ -71,6 +72,9 @@ const EMPTY = {
71
72
  help: false,
72
73
  version: false,
73
74
  selfCheck: false,
75
+ html: null,
76
+ open: false,
77
+ cache: true,
74
78
  };
75
79
  /** A percentage as it is written on the command line (`10`) into the fraction the code compares. */
76
80
  const parsePercent = (value) => {
@@ -102,6 +106,18 @@ const apply = (options, flag, value, positional) => {
102
106
  options.selfCheck = true;
103
107
  return null;
104
108
  }
109
+ case '--html': {
110
+ options.html = value;
111
+ return null;
112
+ }
113
+ case '--open': {
114
+ options.open = true;
115
+ return null;
116
+ }
117
+ case '--no-cache': {
118
+ options.cache = false;
119
+ return null;
120
+ }
105
121
  case '--dist': {
106
122
  options.dist = value;
107
123
  return null;
@@ -234,15 +250,20 @@ const parseArgs = (argv) => {
234
250
  if (positional.length > 1) {
235
251
  return { ok: false, message: `Unexpected argument: ${positional[1]}` };
236
252
  }
237
- return { ok: true, options: { ...options, target } };
253
+ return options.open && !options.html
254
+ ? { ok: false, message: '--open opens what --html writes: add --html <file>.' }
255
+ : { ok: true, options: { ...options, target } };
238
256
  };
239
257
  exports.parseArgs = parseArgs;
240
258
  exports.USAGE = `Loadline — weight per screen, from the terminal.
241
259
 
242
260
  Usage
243
- loadline <stats.json|build folder> [options]
261
+ loadline <build root|stats.json|browser folder> [options]
262
+
263
+ The root of an Angular build — dist/<app> — is enough: browser-stats.json (Angular 22.2+) or
264
+ stats.json, and the browser/ folder next to it, are found on their own.
244
265
 
245
- A build folder works on its own: its chunks carry the import graph, so anything that emits ES
266
+ A build folder works on its own too: its chunks carry the import graph, so anything that emits ES
246
267
  modules — Vite, Rollup, Rolldown, esbuild — is read without a stats file. It has to hold the
247
268
  index.html of the build, which is what names the chunk the application starts at.
248
269
 
@@ -279,8 +300,15 @@ Output
279
300
  an HTML marker so the next run edits it instead of adding a
280
301
  sixteenth one. sarif anchors each signal to a file, which is what
281
302
  GitHub's code scanning reads.
303
+ --html <file> Also write the page — treemap, search, every chunk — with this build
304
+ already loaded into it. One self-contained file: nothing to drag in,
305
+ nothing fetched, opens offline.
306
+ --open Open what --html wrote.
282
307
  --lang en|es Default: en.
283
308
  --no-color Never emit colour. It is off already when stdout is not a terminal.
309
+ --no-cache Do not remember this run. By default each run is kept in
310
+ node_modules/.cache/loadline and the next one says what moved —
311
+ "bootstrap 156 kB → 129 kB" — without a --baseline.
284
312
 
285
313
  Failing the build
286
314
  --max-boot <size> Fail when the bootstrap is over it.
@@ -314,6 +342,8 @@ Exit codes
314
342
  2 the arguments or the files could not be used.
315
343
 
316
344
  Examples
345
+ loadline dist/app
346
+ loadline dist/app --html loadline.html --open
317
347
  loadline dist/app/browser
318
348
  loadline dist/app/stats.json --dist dist/app/browser
319
349
  loadline dist/app/stats.json --dist dist/app/browser --max-boot 350kB --fail-on high
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * What each package in the bundle declares as its dependencies, read from its own `package.json`
4
+ * in `node_modules`.
5
+ *
6
+ * pnpm's lock file records which version was resolved and not which range was asked for, and the
7
+ * difference is the whole question when a package is duplicated: `idb` resolved to `7.1.1` says
8
+ * nothing; `@firebase/app` asking for exactly `7.1.1` says the copy cannot move. The `package.json`
9
+ * of the parent is on disk next to the code that was bundled, so the command reads it — only for
10
+ * the packages the metafile names, and only when a lock file or a project folder says where the
11
+ * install lives.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.readDeclared = void 0;
15
+ const promises_1 = require("node:fs/promises");
16
+ const node_path_1 = require("node:path");
17
+ const json_utils_1 = require("../src/app/core/json/json.utils");
18
+ /** `…/node_modules/@scope/name/` or `…/node_modules/name/`: the folder a package is installed in. */
19
+ const PACKAGE_DIR = /^(.*node_modules\/(?:@[^/]+\/)?[^/]+)\//;
20
+ /**
21
+ * @param meta the metafile: its input paths are where each bundled package is installed, relative
22
+ * to the folder the build ran in.
23
+ * @param root that folder.
24
+ */
25
+ const readDeclared = async (meta, root) => {
26
+ const folders = new Set();
27
+ const inputs = Object.keys(meta.inputs);
28
+ for (const input of inputs) {
29
+ const folder = PACKAGE_DIR.exec(input.replaceAll('\\', '/'))?.[1];
30
+ if (folder) {
31
+ folders.add(folder);
32
+ }
33
+ }
34
+ const declared = new Map();
35
+ for (const folder of folders) {
36
+ try {
37
+ const manifest = (0, json_utils_1.asRecord)(JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(root, folder, 'package.json'), 'utf8')));
38
+ const name = (0, json_utils_1.asText)(manifest?.['name']);
39
+ const dependencies = (0, json_utils_1.asRecord)(manifest?.['dependencies']);
40
+ if (!name || !dependencies) {
41
+ continue;
42
+ }
43
+ const ranges = Object.fromEntries(Object.entries(dependencies).filter((pair) => typeof pair[1] === 'string'));
44
+ declared.set(name, { ...declared.get(name), ...ranges });
45
+ }
46
+ catch {
47
+ // Not installed here, or not readable: that package simply has no declared ranges.
48
+ }
49
+ }
50
+ return declared;
51
+ };
52
+ exports.readDeclared = readDeclared;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ /**
3
+ * `--html <file>`: the page, with this build already in it.
4
+ *
5
+ * The page has always been the better place to *explore* a build — the treemap, the search, every
6
+ * chunk opened — and the worse one to *get to*: it asked for the folder to be dragged in by hand,
7
+ * which is exactly the step a script cannot do. So the command writes the same self-contained
8
+ * `loadline.html` it ships with and puts the files it was given inside it, as they are. The page
9
+ * reads them on start through the same door a drop goes through: the analysis runs again in the
10
+ * browser, on the same bytes, so the two front ends cannot disagree about what they show.
11
+ *
12
+ * Nothing leaves the machine. The file is written where it was asked for and opened locally; a
13
+ * report built this way can be attached to an issue and opened by anybody, offline.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.openFile = exports.writeHtmlReport = exports.embedText = exports.embedFolder = void 0;
17
+ const node_child_process_1 = require("node:child_process");
18
+ const promises_1 = require("node:fs/promises");
19
+ const node_path_1 = require("node:path");
20
+ const read_build_1 = require("./read-build");
21
+ /** Files read as text inside the page. Everything else is carried as bytes. */
22
+ const TEXT_FILE = /\.(?:m?js|css|html?|json|webmanifest|map|xml|txt|svg)$/i;
23
+ /** Carried for their size only: the page never reads what is inside a pre-compressed copy. */
24
+ const SIZE_ONLY = /\.(?:br|brotli|gz|zst)$/i;
25
+ /** Above this a binary travels as a filler of the same size: a report is not a backup of the build. */
26
+ const MAX_BINARY = 2 * 1024 * 1024;
27
+ /** Where `loadline.html` is: next to the package when installed, at the root of a clone otherwise. */
28
+ const pagePath = async () => {
29
+ const candidates = [(0, node_path_1.join)(__dirname, '..', '..', '..', 'loadline.html'), (0, node_path_1.join)(__dirname, '..', 'loadline.html')];
30
+ for (const candidate of candidates) {
31
+ try {
32
+ const info = await (0, promises_1.stat)(candidate);
33
+ if (info.isFile()) {
34
+ return candidate;
35
+ }
36
+ }
37
+ catch {
38
+ // The next one.
39
+ }
40
+ }
41
+ throw new read_build_1.InputError('loadline.html is missing from this install, so --html has nothing to write. Run: pnpm build');
42
+ };
43
+ const walk = async (folder) => {
44
+ const entries = await (0, promises_1.readdir)(folder, { withFileTypes: true, recursive: true });
45
+ return entries.filter(entry => entry.isFile()).map(entry => (0, node_path_1.join)(entry.parentPath, entry.name));
46
+ };
47
+ /** The build folder, file by file, the way the page's folder picker would have handed it over. */
48
+ const embedFolder = async (folder) => {
49
+ const files = [];
50
+ const paths = await walk(folder);
51
+ for (const path of paths) {
52
+ const inside = (0, node_path_1.relative)(folder, path).replaceAll('\\', '/');
53
+ const { size } = await (0, promises_1.stat)(path);
54
+ if (SIZE_ONLY.test(path)) {
55
+ files.push({ path: inside, size });
56
+ }
57
+ else if (TEXT_FILE.test(path)) {
58
+ files.push({ path: inside, text: await (0, promises_1.readFile)(path, 'utf8') });
59
+ }
60
+ else if (size > MAX_BINARY) {
61
+ files.push({ path: inside, size });
62
+ }
63
+ else {
64
+ const bytes = await (0, promises_1.readFile)(path);
65
+ files.push({ path: inside, b64: bytes.toString('base64') });
66
+ }
67
+ }
68
+ return { name: (0, node_path_1.basename)(folder), files };
69
+ };
70
+ exports.embedFolder = embedFolder;
71
+ const embedText = async (path) => path ? { name: (0, node_path_1.basename)(path), text: await (0, promises_1.readFile)(path, 'utf8') } : null;
72
+ exports.embedText = embedText;
73
+ /**
74
+ * The page with the build inside. `</` is escaped so no file of the build can close the script tag
75
+ * it travels in — a chunk that contains the string `</script>` is ordinary minified JavaScript.
76
+ */
77
+ const writeHtmlReport = async (file, build) => {
78
+ const page = await (0, promises_1.readFile)(await pagePath(), 'utf8');
79
+ const json = JSON.stringify(build).replaceAll('</', String.raw `<\/`);
80
+ const tag = `<script type="application/json" id="loadline-build">${json}</script>`;
81
+ // The last `</body>`, not the first: the page's own inlined code mentions the tag in its strings,
82
+ // and putting the build in front of the first one cut a script in half.
83
+ const end = page.lastIndexOf('</body>');
84
+ const html = end === -1 ? `${page}\n${tag}` : `${page.slice(0, end)}${tag}\n${page.slice(end)}`;
85
+ await (0, promises_1.writeFile)(file, html, 'utf8');
86
+ };
87
+ exports.writeHtmlReport = writeHtmlReport;
88
+ /** Opens a file with whatever the system opens HTML with. Never waits for it, never fails the run. */
89
+ const openFile = (file) => {
90
+ const [command, args] = process.platform === 'win32'
91
+ ? ['cmd', ['/c', 'start', '""', file]]
92
+ : process.platform === 'darwin'
93
+ ? ['open', [file]]
94
+ : ['xdg-open', [file]];
95
+ try {
96
+ const child = (0, node_child_process_1.spawn)(command, args, { detached: true, stdio: 'ignore', windowsHide: true });
97
+ child.on('error', () => {
98
+ // An opener that is not installed fails here, after the spawn: the file is still
99
+ // written, and opening it was a courtesy. Listening is what keeps it from crashing.
100
+ });
101
+ child.unref();
102
+ }
103
+ catch {
104
+ // No opener on this machine: the file is written and its path was printed.
105
+ }
106
+ };
107
+ exports.openFile = openFile;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ /**
3
+ * What to read when the command is pointed at the root of a build rather than at one of its files.
4
+ *
5
+ * `ng build` writes `dist/<app>/browser/` and, with `--stats-json`, the metafile next to it — called
6
+ * `stats.json` up to Angular 22.1 and `browser-stats.json` from 22.2, when the server half got a file
7
+ * of its own (`server-stats.json`). Read in @angular/build itself: 22.1.8 writes `stats.json` with or
8
+ * without a server, 22.2.0 writes `browser-stats.json` even when there is none. Asking for both paths by hand was the first thing anybody had to get right, and the
9
+ * README naming only the old file sent people looking for something that was not there. Pointed at
10
+ * `dist/<app>`, the command now finds both on its own and says which it found.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.locateBuild = void 0;
14
+ const promises_1 = require("node:fs/promises");
15
+ const node_path_1 = require("node:path");
16
+ /** The metafile's names, newest first: the first one present wins. */
17
+ const STATS_NAMES = ['browser-stats.json', 'stats.json'];
18
+ const isFile = async (path) => {
19
+ try {
20
+ const info = await (0, promises_1.stat)(path);
21
+ return info.isFile();
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ };
27
+ const isDirectory = async (path) => {
28
+ try {
29
+ const info = await (0, promises_1.stat)(path);
30
+ return info.isDirectory();
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ };
36
+ /**
37
+ * @param target what was typed: a metafile, a browser folder or the root of a build.
38
+ * @param dist `--dist`, when it was given. Anything typed by hand wins: nothing is looked up then.
39
+ */
40
+ const locateBuild = async (target, dist) => {
41
+ if (dist || !(await isDirectory(target))) {
42
+ return { target, dist, found: [] };
43
+ }
44
+ const browser = (0, node_path_1.join)(target, 'browser');
45
+ const hasBrowser = await isDirectory(browser);
46
+ let stats = null;
47
+ for (const name of STATS_NAMES) {
48
+ const candidate = (0, node_path_1.join)(target, name);
49
+ if (await isFile(candidate)) {
50
+ stats = candidate;
51
+ break;
52
+ }
53
+ }
54
+ if (stats) {
55
+ return { target: stats, dist: hasBrowser ? browser : null, found: hasBrowser ? [stats, browser] : [stats] };
56
+ }
57
+ // No metafile: the browser folder is read as a graph, the way a folder always has been.
58
+ return hasBrowser ? { target: browser, dist: null, found: [browser] } : { target, dist, found: [] };
59
+ };
60
+ exports.locateBuild = locateBuild;
@@ -7,11 +7,18 @@
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.run = exports.UNUSABLE = exports.FAILED = exports.OK = void 0;
9
9
  const promises_1 = require("node:fs/promises");
10
+ const node_path_1 = require("node:path");
11
+ const pins_1 = require("../src/app/core/deps/pins");
10
12
  const summary_1 = require("../src/app/core/export/summary");
11
13
  const ui_1 = require("../src/app/core/i18n/ui");
14
+ const project_context_1 = require("../src/app/core/project/project-context");
12
15
  const report_messages_utils_1 = require("../src/app/state/report-messages.utils");
13
16
  const args_1 = require("./args");
17
+ const declared_1 = require("./declared");
14
18
  const gates_1 = require("./gates");
19
+ const html_report_1 = require("./html-report");
20
+ const locate_1 = require("./locate");
21
+ const memory_1 = require("./memory");
15
22
  const read_build_1 = require("./read-build");
16
23
  const render_json_1 = require("./render-json");
17
24
  const render_markdown_1 = require("./render-markdown");
@@ -20,7 +27,10 @@ const render_sarif_1 = require("./render-sarif");
20
27
  const render_text_1 = require("./render-text");
21
28
  const report_1 = require("./report");
22
29
  const self_check_1 = require("./self-check");
30
+ const since_last_1 = require("./since-last");
23
31
  const text_1 = require("./text");
32
+ /** The formats that print the `--what-if` answers. */
33
+ const WHAT_IF_FORMATS = new Set(['text', 'summary', 'json']);
24
34
  /** 0 ran clean · 1 a gate broke · 2 the arguments or the files could not be used. */
25
35
  exports.OK = 0;
26
36
  exports.FAILED = 1;
@@ -40,6 +50,34 @@ const NO_DIST = {
40
50
  texts: new Map(),
41
51
  maps: [],
42
52
  };
53
+ const fileExists = async (path) => {
54
+ try {
55
+ const info = await (0, promises_1.stat)(path);
56
+ return info.isFile();
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ };
62
+ /**
63
+ * Where each file nothing names lives in the repository, when `angular.json` copies it from an
64
+ * assets folder **and it is really there**. The page can only say "comes from"; the command looks.
65
+ */
66
+ const assetSourcesOf = async (assets, context, project) => {
67
+ const folders = context.angular?.assetFolders ?? [];
68
+ if (!assets || !project || folders.length === 0) {
69
+ return null;
70
+ }
71
+ const found = new Map();
72
+ const mapped = (0, project_context_1.repoPathsOf)(assets.unreferenced, folders);
73
+ const pairs = [...(mapped ?? [])];
74
+ for (const [path, repo] of pairs) {
75
+ if (await fileExists((0, node_path_1.join)(project, repo))) {
76
+ found.set(path, repo);
77
+ }
78
+ }
79
+ return found;
80
+ };
43
81
  /** Everything off the disk, in one place, so the analysis starts with nothing left to fetch. */
44
82
  const readInputs = async (options) => {
45
83
  // A folder is the build itself, so it is both what is analysed and where the figures come from.
@@ -49,8 +87,22 @@ const readInputs = async (options) => {
49
87
  }
50
88
  const folder = derive ? options.target : options.dist;
51
89
  const dist = folder ? await (0, read_build_1.readDist)(folder, derive) : NO_DIST;
90
+ const meta = dist.graph ? dist.graph.meta : await (0, read_build_1.readStats)(options.target, ui_1.UI[options.lang]);
91
+ const deps = await (0, read_build_1.readDepsFiles)(options.lock, options.audit);
92
+ const context = options.project ? await (0, read_build_1.readProject)(options.project) : { angular: null, pkg: null, pipelines: [] };
93
+ // The ranges each package declares. A lock file of npm or yarn records them; pnpm's does not,
94
+ // and then the `package.json` files in `node_modules` are read — only when a lock file or a
95
+ // project folder says where the install is, since that is where the metafile's paths start.
96
+ const installRoot = options.project ?? (options.lock ? (0, node_path_1.dirname)(options.lock) : null);
97
+ const declared = new Map((0, pins_1.declaredFromLock)(deps.lock));
98
+ if (installRoot && (options.lock || options.project)) {
99
+ const fromDisk = await (0, declared_1.readDeclared)(meta, installRoot);
100
+ for (const [name, ranges] of fromDisk) {
101
+ declared.set(name, { ...ranges, ...declared.get(name) });
102
+ }
103
+ }
52
104
  return {
53
- meta: dist.graph ? dist.graph.meta : await (0, read_build_1.readStats)(options.target, ui_1.UI[options.lang]),
105
+ meta,
54
106
  parallel: dist.graph?.parallel ?? null,
55
107
  statsName: options.target,
56
108
  ...dist,
@@ -59,12 +111,53 @@ const readInputs = async (options) => {
59
111
  configProblems: read.problems,
60
112
  configName: read.name,
61
113
  }))),
62
- ...(await (0, read_build_1.readDepsFiles)(options.lock, options.audit)),
114
+ ...deps,
115
+ declared: declared.size > 0 ? declared : null,
116
+ assetSources: await assetSourcesOf(dist.assets, context, options.project),
63
117
  baseline: options.baseline ? await (0, read_build_1.readBaseline)(options.baseline) : null,
64
- context: options.project ? await (0, read_build_1.readProject)(options.project) : { angular: null, pkg: null, pipelines: [] },
118
+ // Remembered only when nothing was asked for explicitly: a `--baseline` is a decision, the
119
+ // memory is a convenience, and the two are never mixed in one report.
120
+ lastRun: options.cache && !options.baseline ? await (0, memory_1.readLastRun)(process.cwd(), options.target) : null,
121
+ context,
65
122
  criteria: options.criteria ? await (0, read_build_1.readCriteria)(options.criteria) : null,
66
123
  };
67
124
  };
125
+ /** The files the page needs to rebuild this report on its own, read once more as they are. */
126
+ const writePage = async (options) => {
127
+ if (!options.html) {
128
+ return;
129
+ }
130
+ const derive = await (0, read_build_1.isFolder)(options.target);
131
+ const folder = derive ? options.target : options.dist;
132
+ const extras = [
133
+ options.project ? (0, node_path_1.join)(options.project, 'angular.json') : null,
134
+ options.project ? (0, node_path_1.join)(options.project, 'package.json') : null,
135
+ options.lock,
136
+ options.audit,
137
+ options.config,
138
+ ];
139
+ const texts = [];
140
+ for (const path of extras) {
141
+ if (!(path && (await fileExists(path)))) {
142
+ continue;
143
+ }
144
+ const text = await (0, html_report_1.embedText)(path);
145
+ if (text) {
146
+ texts.push(text);
147
+ }
148
+ }
149
+ await (0, html_report_1.writeHtmlReport)(options.html, {
150
+ version: 1,
151
+ lang: options.lang,
152
+ stats: derive ? null : await (0, html_report_1.embedText)(options.target),
153
+ folder: folder ? await (0, html_report_1.embedFolder)(folder) : null,
154
+ extras: texts,
155
+ baseline: await (0, html_report_1.embedText)(options.baseline),
156
+ });
157
+ if (options.open) {
158
+ (0, html_report_1.openFile)((0, node_path_1.resolve)(options.html));
159
+ }
160
+ };
68
161
  /**
69
162
  * A growth gate with nothing to grow against would pass every build, quietly, forever. Saying so
70
163
  * beats a green pipeline that checks nothing.
@@ -81,7 +174,7 @@ const run = async (argv, version) => {
81
174
  write(process.stderr, `${parsed.message}\n\nRun loadline --help to see the options.`);
82
175
  return exports.UNUSABLE;
83
176
  }
84
- const options = parsed.options;
177
+ let options = parsed.options;
85
178
  if (options.help) {
86
179
  write(process.stdout, args_1.USAGE);
87
180
  return exports.OK;
@@ -92,11 +185,15 @@ const run = async (argv, version) => {
92
185
  }
93
186
  try {
94
187
  requireBaseline(options);
188
+ // The root of a build is enough: the metafile and the browser folder are found inside it.
189
+ const located = await (0, locate_1.locateBuild)(options.target, options.dist);
190
+ options = { ...options, target: located.target, dist: located.dist };
95
191
  const input = await readInputs(options);
96
192
  // The gates the file asks for, where the command line did not ask for that one. A flag typed
97
193
  // by hand is somebody overriding the committed decision on purpose, so it wins.
98
194
  const gates = (0, gates_1.mergeGates)(options.gates, input.config ?? null);
99
195
  const report = (0, report_1.buildReport)(input, { ...options, gates });
196
+ report.located = located.found;
100
197
  // The self-check is about Loadline, not about the build, so it replaces the report rather
101
198
  // than being one more section of it — and it owns the exit code while it is asked for.
102
199
  if (options.selfCheck) {
@@ -120,7 +217,7 @@ const run = async (argv, version) => {
120
217
  const asked = (0, gates_1.anyGate)(gates);
121
218
  const violations = (0, gates_1.checkGates)(report, gates);
122
219
  // Colour is for a person watching a terminal; a redirected stream is a file or a log.
123
- const color = options.color && process.stdout.isTTY === true && !process.env['NO_COLOR'];
220
+ const color = options.color && process.stdout.isTTY && !process.env['NO_COLOR'];
124
221
  const rendered = {
125
222
  text: () => (0, render_text_1.renderText)(report, violations, asked, color),
126
223
  json: () => (0, render_json_1.renderJson)(report, violations, asked),
@@ -135,14 +232,30 @@ const run = async (argv, version) => {
135
232
  name: report.statsName,
136
233
  firstTrip: report.assets?.firstTrip.total ?? null,
137
234
  lang: report.lang,
235
+ since: (0, since_last_1.sinceLastLine)(report),
236
+ whatIf: report.whatIf,
138
237
  }),
139
238
  };
239
+ // `--what-if` is answered in text, summary and json. The other three are a document for
240
+ // somebody else — a merge request, a code-scanning upload — and had nowhere to put it, so
241
+ // the question used to go unanswered without a word. Now it says where to look.
242
+ if (options.whatIf.length > 0 && !WHAT_IF_FORMATS.has(options.format)) {
243
+ write(process.stderr, text_1.CLI_TEXT[options.lang].whatIfNotHere(options.format));
244
+ }
140
245
  // What is wrong with `loadline.json` goes to stderr, never into the report: something is
141
246
  // parsing stdout, and a warning in the middle of a SARIF document breaks it.
142
247
  for (const problem of report.configProblems) {
143
248
  write(process.stderr, text_1.CLI_TEXT[options.lang].configProblem(problem));
144
249
  }
145
250
  write(process.stdout, rendered[options.format]());
251
+ // After the report, so a page that fails to write never costs the report somebody piped.
252
+ if (options.html) {
253
+ await writePage(options);
254
+ write(process.stderr, text_1.CLI_TEXT[options.lang].htmlWritten(options.html));
255
+ }
256
+ if (options.cache) {
257
+ await (0, memory_1.writeLastRun)(process.cwd(), options.target, report.snapshot);
258
+ }
146
259
  return violations.length > 0 ? exports.FAILED : exports.OK;
147
260
  }
148
261
  catch (error) {