@bymaksym/loadline 0.1.0 → 1.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 (115) hide show
  1. package/README.md +272 -45
  2. package/dist/cli/cli/args.js +97 -116
  3. package/dist/cli/cli/gates.js +80 -14
  4. package/dist/cli/cli/main.js +275 -31
  5. package/dist/cli/cli/memory.js +114 -0
  6. package/dist/cli/cli/read/declared.js +52 -0
  7. package/dist/cli/cli/read/locate.js +214 -0
  8. package/dist/cli/cli/{read-build.js → read/read-build.js} +156 -87
  9. package/dist/cli/cli/read/read-config.js +120 -0
  10. package/dist/cli/cli/render/html-report.js +111 -0
  11. package/dist/cli/cli/render/render-agent.js +114 -0
  12. package/dist/cli/cli/render/render-asked.js +104 -0
  13. package/dist/cli/cli/render/render-badge.js +140 -0
  14. package/dist/cli/cli/{render-json.js → render/render-json.js} +26 -10
  15. package/dist/cli/cli/{render-markdown.js → render/render-markdown.js} +6 -6
  16. package/dist/cli/cli/{render-pr.js → render/render-pr.js} +37 -15
  17. package/dist/cli/cli/{render-sarif.js → render/render-sarif.js} +11 -6
  18. package/dist/cli/cli/{render-text.js → render/render-text.js} +169 -127
  19. package/dist/cli/cli/render/terminal.js +55 -0
  20. package/dist/cli/cli/report.js +76 -29
  21. package/dist/cli/cli/self-check.js +19 -23
  22. package/dist/cli/cli/since-last.js +45 -0
  23. package/dist/cli/cli/text/text-errors.js +124 -0
  24. package/dist/cli/cli/text/text.js +343 -0
  25. package/dist/cli/cli/text/usage.js +240 -0
  26. package/dist/cli/src/app/core/analysis/analysis.js +68 -24
  27. package/dist/cli/src/app/core/analysis/{barrels.js → graph/barrels.js} +10 -3
  28. package/dist/cli/src/app/core/analysis/{blast.js → graph/blast.js} +56 -17
  29. package/dist/cli/src/app/core/analysis/{cycles.js → graph/cycles.js} +1 -1
  30. package/dist/cli/src/app/core/analysis/{importers.js → graph/importers.js} +1 -1
  31. package/dist/cli/src/app/core/analysis/{insights.js → graph/insights.js} +10 -4
  32. package/dist/cli/src/app/core/analysis/invariant.js +1 -1
  33. package/dist/cli/src/app/core/analysis/metafile.types.js +21 -7
  34. package/dist/cli/src/app/core/analysis/{delivery.js → screens/delivery.js} +1 -1
  35. package/dist/cli/src/app/core/analysis/{entries.js → screens/entries.js} +87 -11
  36. package/dist/cli/src/app/core/analysis/screens/marks.js +32 -0
  37. package/dist/cli/src/app/core/analysis/screens/route-files.js +116 -0
  38. package/dist/cli/src/app/core/analysis/{sourcemap.js → sourcemap/sourcemap.js} +106 -7
  39. package/dist/cli/src/app/core/analysis/{split-drift.js → sourcemap/split-drift.js} +13 -7
  40. package/dist/cli/src/app/core/analysis/tool.js +83 -0
  41. package/dist/cli/src/app/core/assets/assets.js +137 -16
  42. package/dist/cli/src/app/core/baseline/baseline.js +0 -0
  43. package/dist/cli/src/app/core/{intake → build-text}/index-html.js +234 -29
  44. package/dist/cli/src/app/core/build-text/route-table.js +178 -0
  45. package/dist/cli/src/app/core/build-text/tool-marks.js +54 -0
  46. package/dist/cli/src/app/core/caching/caching.js +123 -45
  47. package/dist/cli/src/app/core/caching/from-analysis.js +20 -4
  48. package/dist/cli/src/app/core/config/config-text.js +90 -0
  49. package/dist/cli/src/app/core/config/config-values.js +358 -0
  50. package/dist/cli/src/app/core/config/loadline-config.js +81 -16
  51. package/dist/cli/src/app/core/config/merge-config.js +98 -0
  52. package/dist/cli/src/app/core/deps/deps.js +141 -23
  53. package/dist/cli/src/app/core/deps/pins.js +63 -0
  54. package/dist/cli/src/app/core/export/summary.js +54 -12
  55. package/dist/cli/src/app/core/findings/actions.js +65 -6
  56. package/dist/cli/src/app/core/findings/bundle/boot-single.js +76 -0
  57. package/dist/cli/src/app/core/findings/bundle/dupes.js +68 -0
  58. package/dist/cli/src/app/core/findings/{graph.js → bundle/graph.js} +32 -20
  59. package/dist/cli/src/app/core/findings/{own-in-boot.js → bundle/own-in-boot.js} +9 -5
  60. package/dist/cli/src/app/core/findings/{requests.js → bundle/requests.js} +3 -3
  61. package/dist/cli/src/app/core/findings/{shipped.js → bundle/shipped.js} +30 -18
  62. package/dist/cli/src/app/core/findings/compose.js +6 -1
  63. package/dist/cli/src/app/core/findings/effort.js +4 -0
  64. package/dist/cli/src/app/core/findings/finding.types.js +2 -0
  65. package/dist/cli/src/app/core/findings/findings.js +68 -55
  66. package/dist/cli/src/app/core/findings/{assets.js → folder/assets.js} +65 -16
  67. package/dist/cli/src/app/core/findings/{caching.js → folder/caching.js} +17 -10
  68. package/dist/cli/src/app/core/findings/{page.js → folder/page.js} +6 -2
  69. package/dist/cli/src/app/core/findings/{scan.js → folder/scan.js} +37 -13
  70. package/dist/cli/src/app/core/findings/kind-names.js +163 -0
  71. package/dist/cli/src/app/core/findings/{deps.js → supplied/deps.js} +13 -8
  72. package/dist/cli/src/app/core/findings/supplied/forbidden.js +71 -0
  73. package/dist/cli/src/app/core/findings/{situation.js → supplied/situation.js} +2 -2
  74. package/dist/cli/src/app/core/findings/text/causes.js +39 -0
  75. package/dist/cli/src/app/core/findings/text/finding-html.js +33 -0
  76. package/dist/cli/src/app/core/findings/{finding-text.js → text/finding-text.js} +307 -103
  77. package/dist/cli/src/app/core/findings/text/tool-advice.js +97 -0
  78. package/dist/cli/src/app/core/format/format.utils.js +172 -18
  79. package/dist/cli/src/app/core/format/ownership.js +93 -0
  80. package/dist/cli/src/app/core/i18n/en.js +180 -61
  81. package/dist/cli/src/app/core/i18n/es.js +192 -68
  82. package/dist/cli/src/app/core/intake/bundle-graph.js +285 -46
  83. package/dist/cli/src/app/core/intake/dist-files.js +87 -16
  84. package/dist/cli/src/app/core/intake/embedded.js +56 -0
  85. package/dist/cli/src/app/core/intake/unreached.js +139 -0
  86. package/dist/cli/src/app/core/intake/webpack-modules.js +185 -0
  87. package/dist/cli/src/app/core/intake/webpack-stats.js +298 -0
  88. package/dist/cli/src/app/core/project/budget-advice.js +14 -10
  89. package/dist/cli/src/app/core/project/project-context.js +89 -19
  90. package/dist/cli/src/app/core/project/project-name.js +36 -0
  91. package/dist/cli/src/app/core/scan/scan.js +116 -39
  92. package/dist/cli/src/app/core/scan/secrets.js +0 -0
  93. package/dist/cli/src/app/core/situation/situation-text.js +23 -0
  94. package/dist/cli/src/app/core/situation/situation.js +9 -8
  95. package/dist/cli/src/app/core/timing/timing.js +5 -2
  96. package/dist/cli/src/app/core/whatif/defer.js +29 -4
  97. package/dist/cli/src/app/core/whatif/source-importers.js +58 -0
  98. package/dist/cli/src/app/core/whatif/why.js +102 -0
  99. package/dist/cli/src/app/state/report-messages.utils.js +1 -4
  100. package/docs/CONFIG-REFERENCE.md +230 -0
  101. package/docs/CONFIG.md +511 -0
  102. package/docs/HOW-IT-WORKS.md +286 -25
  103. package/loadline.html +26 -24
  104. package/loadline.schema.json +1209 -0
  105. package/package.json +71 -35
  106. package/dist/cli/cli/text.js +0 -180
  107. package/dist/cli/src/app/core/findings/finding-html.js +0 -13
  108. /package/dist/cli/cli/{read-build.types.js → read/read-build.types.js} +0 -0
  109. /package/dist/cli/cli/{render-json.types.js → render/render-json.types.js} +0 -0
  110. /package/dist/cli/cli/{text.types.js → text/text.types.js} +0 -0
  111. /package/dist/cli/src/app/core/analysis/{exclusive.js → graph/exclusive.js} +0 -0
  112. /package/dist/cli/src/app/core/analysis/{insights.types.js → graph/insights.types.js} +0 -0
  113. /package/dist/cli/src/app/core/analysis/{module-graph.js → graph/module-graph.js} +0 -0
  114. /package/dist/cli/src/app/core/analysis/{sourcemap.types.js → sourcemap/sourcemap.types.js} +0 -0
  115. /package/dist/cli/src/app/core/findings/{finding-plain.js → text/finding-plain.js} +0 -0
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * `loadline.json` off the disk, with whatever it `extends` found and joined in.
4
+ *
5
+ * Found rather than required on purpose: the file is meant to be committed next to the code, and a
6
+ * tool that only reads its configuration when told to is a tool whose configuration drifts. An
7
+ * explicit `--config` that does not exist **is** an error — somebody asked for a file — while a
8
+ * missing one in the working directory is simply the ordinary case.
9
+ *
10
+ * How the files join is `mergeConfigs`, in the analysis, because it is a rule about the file and not
11
+ * about the disk. What is here is only where each name of `extends` is:
12
+ *
13
+ * - **A path** (`./base.loadline.json`, `../shared/loadline.json`) is a file, from the folder of the
14
+ * file that writes it — not from where the command runs, which is what makes a base that extends
15
+ * another base work from any repository.
16
+ * - **Anything else is a package**: its `loadline.json`, found the way Node finds a package from
17
+ * that same folder. `@acme/loadline-config` reads `@acme/loadline-config/loadline.json`. No prefix
18
+ * is added and nothing is downloaded: it is whatever `npm install` put there, at the version the
19
+ * lock file says, so a base cannot change under a build without a commit.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.readLoadlineConfig = void 0;
23
+ const node_module_1 = require("node:module");
24
+ const node_path_1 = require("node:path");
25
+ const config_text_1 = require("../../src/app/core/config/config-text");
26
+ const loadline_config_1 = require("../../src/app/core/config/loadline-config");
27
+ const merge_config_1 = require("../../src/app/core/config/merge-config");
28
+ const text_1 = require("../text/text");
29
+ const read_build_1 = require("./read-build");
30
+ /** Where a name of `extends` is on disk, or `null` when it is nowhere. */
31
+ const locate = async (name, from) => {
32
+ if (name.startsWith('.') || (0, node_path_1.isAbsolute)(name)) {
33
+ const path = (0, node_path_1.resolve)((0, node_path_1.dirname)(from), name);
34
+ return (await (0, read_build_1.exists)(path)) ? path : null;
35
+ }
36
+ try {
37
+ return (0, node_module_1.createRequire)(from).resolve(name.endsWith('.json') ? name : `${name}/loadline.json`);
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ };
43
+ /** `own` on top of `base`, or the reason it cannot be: a mode that would misread every inherited size. */
44
+ const join2 = (base, own, lang, shown) => {
45
+ const names = { base: shown(base.files[0] ?? ''), own: shown(own.files[0] ?? '') };
46
+ const joined = (0, merge_config_1.mergeConfigs)(base.config, own.config, names, config_text_1.CONFIG_TEXT[lang]);
47
+ if (joined.gateProblems.length > 0) {
48
+ throw new read_build_1.InputError(joined.gateProblems.join(' '));
49
+ }
50
+ return {
51
+ config: joined.config,
52
+ problems: [...own.problems, ...base.problems],
53
+ files: [...own.files, ...base.files],
54
+ };
55
+ };
56
+ /**
57
+ * One file and, under it, what it extends — each base joined before the file on top of it, the
58
+ * names of one `extends` from left to right, so the last one named wins over the ones before it.
59
+ */
60
+ const load = async (path, config, problems, lang, seen, shown) => {
61
+ const own = {
62
+ config,
63
+ problems: problems.map(problem => text_1.CLI_TEXT[lang].configProblem(shown(path), problem)),
64
+ files: [path],
65
+ };
66
+ let base = null;
67
+ const names = config.extends ?? [];
68
+ for (const name of names) {
69
+ const found = await locate(name, path);
70
+ if (!found) {
71
+ throw new read_build_1.InputError(t => t.extendsNotFound(name, shown(path)));
72
+ }
73
+ if ([...seen, path].includes(found)) {
74
+ throw new read_build_1.InputError(t => t.extendsCycle([...seen, path, found].map(file => shown(file))));
75
+ }
76
+ const read = await readFile(found, lang, shown);
77
+ const next = await load(found, read.config, read.problems, lang, [...seen, path], shown);
78
+ base = base ? join2(base, next, lang, shown) : next;
79
+ }
80
+ return base ? join2(base, own, lang, shown) : own;
81
+ };
82
+ /** A file read and checked. Anything wrong in one named by `--config` or by `extends` stops the run. */
83
+ const readFile = async (path, lang, shown) => {
84
+ const { config, problems, gateProblems } = (0, loadline_config_1.readConfig)(await (0, read_build_1.readJson)(path), lang);
85
+ // The same mistake typed as a flag stops the run with exit 2; written in the file it used to
86
+ // print a line and switch the gate off, and a pipeline guarded by nothing passes. A base is held
87
+ // to the same rule: its gates are this repository's gates too.
88
+ if (gateProblems.length > 0) {
89
+ throw new read_build_1.InputError(`${shown(path)}: ${gateProblems.join(' ')}`);
90
+ }
91
+ if (!config) {
92
+ throw new read_build_1.InputError(`${shown(path)}: ${problems.join(' ')}`);
93
+ }
94
+ return { config, problems };
95
+ };
96
+ const readLoadlineConfig = async (given, cwd, lang = 'en') => {
97
+ const path = (0, node_path_1.resolve)(cwd, given ?? 'loadline.json');
98
+ if (!given && !(await (0, read_build_1.exists)(path))) {
99
+ return { config: null, problems: [], name: null };
100
+ }
101
+ const shown = (file) => (0, node_path_1.relative)(cwd, file) || file;
102
+ // A file somebody pointed at by name is meant to be one; one that merely sits in the working
103
+ // directory under that name may be somebody else's, and gets the warning.
104
+ const { config, problems, gateProblems } = (0, loadline_config_1.readConfig)(await (0, read_build_1.readJson)(path), lang);
105
+ if (!given && !config && gateProblems.length === 0) {
106
+ return {
107
+ config: null,
108
+ problems: problems.map(problem => text_1.CLI_TEXT[lang].configProblem(shown(path), problem)),
109
+ name: null,
110
+ };
111
+ }
112
+ const top = await readFile(path, lang, shown);
113
+ const loaded = await load(path, top.config, top.problems, lang, [], shown);
114
+ return {
115
+ config: loaded.config,
116
+ problems: loaded.problems,
117
+ name: loaded.files.map(file => shown(file)).join(' ← '),
118
+ };
119
+ };
120
+ exports.readLoadlineConfig = readLoadlineConfig;
@@ -0,0 +1,111 @@
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 node_crypto_1 = require("node:crypto");
19
+ const promises_1 = require("node:fs/promises");
20
+ const node_path_1 = require("node:path");
21
+ const read_build_1 = require("../read/read-build");
22
+ /** Files read as text inside the page. Everything else is carried as bytes. */
23
+ const TEXT_FILE = /\.(?:m?js|css|html?|json|webmanifest|map|xml|txt|svg)$/i;
24
+ /** Carried for their size only: the page never reads what is inside a pre-compressed copy. */
25
+ const SIZE_ONLY = /\.(?:br|brotli|gz|zst)$/i;
26
+ /** Where `loadline.html` is: next to the package when installed, at the root of a clone otherwise. */
27
+ const pagePath = async () => {
28
+ const candidates = [
29
+ (0, node_path_1.join)(__dirname, '..', '..', '..', '..', 'loadline.html'),
30
+ (0, node_path_1.join)(__dirname, '..', '..', 'loadline.html'),
31
+ ];
32
+ for (const candidate of candidates) {
33
+ try {
34
+ const info = await (0, promises_1.stat)(candidate);
35
+ if (info.isFile()) {
36
+ return candidate;
37
+ }
38
+ }
39
+ catch {
40
+ // The next one.
41
+ }
42
+ }
43
+ throw new read_build_1.InputError(t => t.htmlMissing);
44
+ };
45
+ const walk = async (folder) => {
46
+ const entries = await (0, promises_1.readdir)(folder, { withFileTypes: true, recursive: true });
47
+ return entries.filter(entry => entry.isFile()).map(entry => (0, node_path_1.join)(entry.parentPath, entry.name));
48
+ };
49
+ /** The build folder, file by file, the way the page's folder picker would have handed it over. */
50
+ const embedFolder = async (folder) => {
51
+ const files = [];
52
+ const paths = await walk(folder);
53
+ for (const path of paths) {
54
+ const inside = (0, node_path_1.relative)(folder, path).replaceAll('\\', '/');
55
+ const { size } = await (0, promises_1.stat)(path);
56
+ if (SIZE_ONLY.test(path)) {
57
+ files.push({ path: inside, size });
58
+ }
59
+ else if (TEXT_FILE.test(path)) {
60
+ files.push({ path: inside, text: await (0, promises_1.readFile)(path, 'utf8') });
61
+ }
62
+ else {
63
+ // The page reads a binary only to hash it, so its hash travels instead of its bytes:
64
+ // a report is not a backup of the build, and as base64 the fonts and pictures of one
65
+ // build came to 18 MB of a 54 MB file.
66
+ const sha256 = (0, node_crypto_1.createHash)('sha256')
67
+ .update(await (0, promises_1.readFile)(path))
68
+ .digest('hex');
69
+ files.push({ path: inside, size, sha256 });
70
+ }
71
+ }
72
+ return { name: (0, node_path_1.basename)(folder), files };
73
+ };
74
+ exports.embedFolder = embedFolder;
75
+ const embedText = async (path) => path ? { name: (0, node_path_1.basename)(path), text: await (0, promises_1.readFile)(path, 'utf8') } : null;
76
+ exports.embedText = embedText;
77
+ /**
78
+ * The page with the build inside. `</` is escaped so no file of the build can close the script tag
79
+ * it travels in — a chunk that contains the string `</script>` is ordinary minified JavaScript.
80
+ */
81
+ const writeHtmlReport = async (file, build) => {
82
+ const page = await (0, promises_1.readFile)(await pagePath(), 'utf8');
83
+ const json = JSON.stringify(build).replaceAll('</', String.raw `<\/`);
84
+ const tag = `<script type="application/json" id="loadline-build">${json}</script>`;
85
+ // The last `</body>`, not the first: the page's own inlined code mentions the tag in its strings,
86
+ // and putting the build in front of the first one cut a script in half.
87
+ const end = page.lastIndexOf('</body>');
88
+ const html = end === -1 ? `${page}\n${tag}` : `${page.slice(0, end)}${tag}\n${page.slice(end)}`;
89
+ await (0, promises_1.writeFile)(file, html, 'utf8');
90
+ };
91
+ exports.writeHtmlReport = writeHtmlReport;
92
+ /** Opens a file with whatever the system opens HTML with. Never waits for it, never fails the run. */
93
+ const openFile = (file) => {
94
+ const [command, args] = process.platform === 'win32'
95
+ ? ['cmd', ['/c', 'start', '""', file]]
96
+ : process.platform === 'darwin'
97
+ ? ['open', [file]]
98
+ : ['xdg-open', [file]];
99
+ try {
100
+ const child = (0, node_child_process_1.spawn)(command, args, { detached: true, stdio: 'ignore', windowsHide: true });
101
+ child.on('error', () => {
102
+ // An opener that is not installed fails here, after the spawn: the file is still
103
+ // written, and opening it was a courtesy. Listening is what keeps it from crashing.
104
+ });
105
+ child.unref();
106
+ }
107
+ catch {
108
+ // No opener on this machine: the file is written and its path was printed.
109
+ }
110
+ };
111
+ exports.openFile = openFile;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ /**
3
+ * `--format agent`: the report as a coding agent or a script wants it — what to do, in order, each
4
+ * step with the file or package it is about, the import chain that puts it there and what doing it
5
+ * is worth. No prose.
6
+ *
7
+ * The JSON holds all of this and more, but an agent reading it spends most of its context on the
8
+ * paragraphs written for people, and still has to join three places — the action, its signal and a
9
+ * `--why` — to know where to type. Here each action is already joined, one per few lines, in an
10
+ * order that does not change between runs of the same build.
11
+ *
12
+ * It is English and its keys never change, whatever `--lang` says: it is read by programs, and a
13
+ * program parsing `saving=` should not have to know Spanish.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.renderAgent = void 0;
17
+ const criteria_1 = require("../../src/app/core/criteria/criteria");
18
+ const actions_1 = require("../../src/app/core/findings/actions");
19
+ const finding_plain_1 = require("../../src/app/core/findings/text/finding-plain");
20
+ const format_utils_1 = require("../../src/app/core/format/format.utils");
21
+ const defer_1 = require("../../src/app/core/whatif/defer");
22
+ const why_1 = require("../../src/app/core/whatif/why");
23
+ /** How many actions: enough to plan an afternoon, few enough to read before acting. */
24
+ const ACTIONS_SHOWN = 5;
25
+ /** `name=value` with no space in the value — `28kB`, not `28 kB` — so a line splits on spaces. */
26
+ const field = (name, value) => `${name}=${String(value).replaceAll(/\s+/g, '')}`;
27
+ const renderAgent = (report, violations, anyAsked) => {
28
+ const { analysis, criteria, comparison } = report;
29
+ const scale = (0, actions_1.unitScale)(analysis);
30
+ const measurable = !(0, defer_1.blindBoot)(analysis);
31
+ const count = (severity) => report.findings.filter(finding => finding.severity === severity).length;
32
+ const head = [
33
+ 'loadline agent v1',
34
+ [
35
+ field('build', report.statsName),
36
+ field('unit', report.mode),
37
+ field('boot', (0, format_utils_1.formatBytes)(analysis.bootBytes)),
38
+ field('verdict', (0, criteria_1.rate)(analysis.bootBytes, criteria.bootOk, criteria.bootBad)),
39
+ field('screens', analysis.screens.length),
40
+ // Without it every saving below is "not known", not zero.
41
+ field('measurable', measurable ? 'yes' : 'no'),
42
+ ].join(' '),
43
+ [
44
+ field('signals', report.findings.length),
45
+ field('high', count('high')),
46
+ field('mid', count('mid')),
47
+ field('info', count('info')),
48
+ ].join(' '),
49
+ ];
50
+ const gates = anyAsked
51
+ ? violations.length === 0
52
+ ? ['gates: passed']
53
+ : ['gates: failed', ...violations.map(violation => ` - ${violation.message}`)]
54
+ : ['gates: none asked'];
55
+ const growth = comparison
56
+ ? [
57
+ `baseline: ${field('name', comparison.baselineName)} ${field('boot', (0, format_utils_1.formatDelta)(comparison.boot.diff))}`,
58
+ ...comparison.bootCauses.slice(0, ACTIONS_SHOWN).map(cause => {
59
+ const figure = `${comparison.causesEstimated ? '≈' : ''}${(0, format_utils_1.formatDelta)(Math.round(cause.diff * comparison.causesRatio))}`;
60
+ return ` - ${field('cause', cause.name)} ${field('change', cause.change)} ${field('diff', figure)}${cause.own ? ' own' : ''}`;
61
+ }),
62
+ ]
63
+ : [];
64
+ // The chain and the cut only where the signal is about one package or one file in the bootstrap.
65
+ const actions = (0, actions_1.rankActions)(report.findings)
66
+ .slice(0, ACTIONS_SHOWN)
67
+ .flatMap((action, index) => {
68
+ const { finding } = action;
69
+ const key = finding.target?.key ?? '';
70
+ const why = key ? (0, why_1.explainWhy)(analysis, key) : null;
71
+ // Not for a whole folder: its chain would be the chain to one file in it, and the cut
72
+ // would be the saving of that file, which is not what the signal is about.
73
+ const reached = why?.reach === 'boot' && why.defer.kind !== 'folder' ? why : null;
74
+ return [
75
+ `${index + 1}. ${[
76
+ field('kind', finding.kind),
77
+ ...(key ? [field('key', key)] : []),
78
+ field('severity', finding.severity),
79
+ field('saving', action.saving > 0 ? (0, actions_1.formatSaving)(action.saving, scale) : measurable ? '0' : 'unknown'),
80
+ field('effort', action.effort),
81
+ ].join(' ')}`,
82
+ ` title: ${(0, finding_plain_1.plainText)(finding.title)}`,
83
+ ...(reached ? [` chain: ${reached.steps.join(' > ')}`] : []),
84
+ ...(reached?.cut && reached.via && reached.saves > 0
85
+ ? [
86
+ ` cut: ${field('in', reached.cut)} ${field('defer', reached.via)} ${field('saves', (0, actions_1.formatSaving)(reached.saves, scale))}`,
87
+ ]
88
+ : []),
89
+ // Imported by several files of the first load: one cut is nothing, all of them are
90
+ // the saving. Every file is named, because an agent edits the ones it is given.
91
+ ...(reached?.cut && reached.via && reached.alsoIn.length > 0 && reached.savesEverywhere > 0
92
+ ? [
93
+ ` cut: ${field('in', [reached.cut, ...reached.alsoIn].join(','))} ${field('defer', reached.via)} ${field('saves', (0, actions_1.formatSaving)(reached.savesEverywhere, scale))}`,
94
+ ]
95
+ : []),
96
+ ];
97
+ });
98
+ const asked = [
99
+ ...report.whatIf.map(result => result.measurable
100
+ ? `what-if ${field('target', result.target)} ${field('saves', (0, actions_1.formatSaving)(result.saved, scale))}`
101
+ : `what-if ${field('target', result.target)} saves=unknown`),
102
+ ...report.why.map(result => `why ${field('target', result.target)} ${field('reach', result.reach)}${result.steps.length > 0 ? ` chain=${result.steps.join('>')}` : ''}${result.cut ? ` ${field('cut', result.cut)}` : ''}`),
103
+ ];
104
+ return [
105
+ ...head,
106
+ ...gates,
107
+ ...growth,
108
+ actions.length > 0 ? 'actions:' : 'actions: none',
109
+ ...actions,
110
+ ...asked,
111
+ '',
112
+ ].join('\n');
113
+ };
114
+ exports.renderAgent = renderAgent;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * The answers to what the command was asked about by name: `--what-if` and `--why`. Both print
4
+ * only when asked, both answer about a package, a folder or a file, and `--why` quotes the same
5
+ * saving `--what-if` computes, so they live together.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.whyBlock = exports.whatIfBlock = void 0;
9
+ const actions_1 = require("../../src/app/core/findings/actions");
10
+ const text_1 = require("../text/text");
11
+ const terminal_1 = require("./terminal");
12
+ /**
13
+ * "What would the first load weigh without this?", for each name asked about.
14
+ *
15
+ * The saving is exact — the graph walked without those files — and the note under it says what is
16
+ * deliberately not recomputed, because a simulated re-chunking would produce round trips that look
17
+ * exactly like the measured ones and are not.
18
+ */
19
+ const whatIfBlock = (report, palette) => {
20
+ if (report.whatIf.length === 0) {
21
+ return [];
22
+ }
23
+ const text = text_1.CLI_TEXT[report.lang];
24
+ // In the report's unit, like the headline above it: see `unitScale`.
25
+ const scale = (0, actions_1.unitScale)(report.analysis);
26
+ const rows = report.whatIf.map(result => result.measurable
27
+ ? [
28
+ result.target,
29
+ (0, actions_1.formatSaving)(result.weight, scale),
30
+ palette.bold((0, actions_1.formatSaving)(result.saved, scale)),
31
+ (0, actions_1.formatRemaining)(report.analysis, result.saved, result.after),
32
+ result.screens.length > 0 ? result.screens.join(', ') : text.whatIfNobody,
33
+ ]
34
+ : [
35
+ result.target,
36
+ // What it weighs in the bootstrap holds even where the saving cannot be worked out.
37
+ result.files.length > 0 ? (0, actions_1.formatSaving)(result.weight, scale) : '—',
38
+ // A name nothing matches is not "cannot be measured": it is not there, and a
39
+ // misspelt package read like a real one that could not be weighed.
40
+ palette.warn(result.files.length > 0 ? text.whatIfUnknown : text.whatIfAbsent),
41
+ '—',
42
+ '—',
43
+ ]);
44
+ // "The saving is exact" over a table of nothing but "cannot be measured" said the opposite of
45
+ // the table; why it cannot be is what is worth saying there instead.
46
+ const measured = report.whatIf.some(result => result.measurable);
47
+ const unknown = report.whatIf.some(result => !result.measurable && result.files.length > 0);
48
+ const note = [
49
+ ...(measured ? [scale.estimated ? `${text.whatIfNote} ${text.whatIfEstimated}` : text.whatIfNote] : []),
50
+ ...(unknown ? [text.whatIfUnknownWhy] : []),
51
+ ].join(' ');
52
+ return [
53
+ '',
54
+ palette.bold(text.headWhatIf),
55
+ ...(note ? (0, terminal_1.wrap)(note, terminal_1.WIDTH).map(line => palette.dim(line)) : []),
56
+ ...(0, terminal_1.table)([
57
+ { head: text.colWhatIf, right: false },
58
+ { head: text.colSize, right: true },
59
+ { head: text.colSaving, right: true },
60
+ { head: text.colAfter, right: true },
61
+ { head: text.colWhoPays, right: false },
62
+ ], rows, palette),
63
+ ];
64
+ };
65
+ exports.whatIfBlock = whatIfBlock;
66
+ /**
67
+ * "Why is this in the first load?", for each name asked about: the chain, then where to cut it.
68
+ * The saving is the `--what-if` figure for the same name, so the two flags cannot disagree.
69
+ */
70
+ const whyBlock = (report, palette) => {
71
+ if (report.why.length === 0) {
72
+ return [];
73
+ }
74
+ const text = text_1.CLI_TEXT[report.lang];
75
+ const scale = (0, actions_1.unitScale)(report.analysis);
76
+ const answer = (result) => {
77
+ // Wrapped like the prose around it, and the name bold where it starts: an answer that is a
78
+ // whole sentence ran a hundred and thirty columns past the edge of the report.
79
+ const [first = '', ...rest] = (0, terminal_1.wrap)(`${result.target} — ${text.whyReach[result.reach]}${result.steps.length > 0 ? ':' : ''}`, terminal_1.WIDTH);
80
+ const head = [palette.bold(result.target) + first.slice(result.target.length), ...rest];
81
+ const chain = result.steps.map((step, index) => ` ${index === 0 ? '' : '→ '}${step}`);
82
+ if (result.reach === 'sourced' && result.cut && result.via) {
83
+ const files = [result.cut, ...result.alsoIn];
84
+ const sentence = text.whyCutSourced(files, result.via, (0, actions_1.formatSaving)(result.savesEverywhere, scale));
85
+ return ['', ...head, ...(0, terminal_1.wrap)(sentence, terminal_1.WIDTH - 4).map(line => ` ${line}`)];
86
+ }
87
+ if (result.reach !== 'boot') {
88
+ return ['', ...head, ...chain];
89
+ }
90
+ const { screens } = result.defer;
91
+ const through = result.via !== result.target;
92
+ const payers = !through && screens.length > 0 ? screens.join(', ') : null;
93
+ const cut = result.cut && result.via
94
+ ? result.saves > 0
95
+ ? text.whyCut(result.cut, result.via, (0, actions_1.formatSaving)(result.saves, scale), through, payers)
96
+ : result.alsoIn.length > 0
97
+ ? text.whyCutAlso(result.cut, result.alsoIn, (0, actions_1.formatSaving)(result.savesEverywhere, scale))
98
+ : text.whyCutShared(result.cut)
99
+ : text.whyNoCut;
100
+ return ['', ...head, ...chain, ...(0, terminal_1.wrap)(cut, terminal_1.WIDTH - 4).map(line => ` ${line}`)];
101
+ };
102
+ return ['', palette.bold(text.headWhy), ...report.why.flatMap(result => answer(result))];
103
+ };
104
+ exports.whyBlock = whyBlock;
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ /**
3
+ * The first load as a badge: an SVG for a README or a pull request, the one piece of the report
4
+ * people see without running the tool.
5
+ *
6
+ * It copies the look of shields.io's "flat" style on purpose. A README already holds a row of those,
7
+ * and a badge that looks like none of its neighbours reads as an advert rather than a figure. It is
8
+ * drawn here rather than fetched from shields because the command fetches nothing, and a badge that
9
+ * depends on somebody else's server goes grey the day that server is down.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.renderBadge = exports.escapeXml = exports.textWidth = exports.BADGE_COLOR = void 0;
13
+ const criteria_1 = require("../../src/app/core/criteria/criteria");
14
+ const format_utils_1 = require("../../src/app/core/format/format.utils");
15
+ /**
16
+ * The label, in the two languages of `--lang`. Here rather than in `text.ts` with the rest of the
17
+ * command's words: the badge is the only thing that says it, and two words do not earn an entry
18
+ * in a table every other format reads.
19
+ */
20
+ const LABEL = { en: 'first load', es: 'primera carga' };
21
+ /**
22
+ * The colour of the value, by the same verdict the text report paints the bootstrap with. Each one
23
+ * holds white text at 4.5:1 or more (WCAG AA): shields' own amber does not, and a badge is read at
24
+ * eleven pixels, which is exactly where low contrast stops being legible.
25
+ */
26
+ exports.BADGE_COLOR = {
27
+ good: '#2e7d32',
28
+ ok: '#9a6700',
29
+ bad: '#c62828',
30
+ };
31
+ const LABEL_COLOR = '#555';
32
+ const HEIGHT = 20;
33
+ /** Space on each side of a text, as shields leaves it. */
34
+ const PADDING = 6;
35
+ const FONT = 'Verdana,Geneva,DejaVu Sans,sans-serif';
36
+ /**
37
+ * Widths of Verdana at 11px, by groups of characters. There is no font to measure in a terminal,
38
+ * and a lookup that is roughly right and always the same is better here than one that is exact on
39
+ * one machine: the text is also told its length (`textLength`), so a guess a pixel off squeezes or
40
+ * spreads the letters a little instead of running past the edge.
41
+ */
42
+ const NARROW = new Set("ijl.,:;|!'");
43
+ const SLIM = new Set(' frtI()[]-/');
44
+ const WIDE = new Set('mwMW%');
45
+ const DIGIT_WIDTH = 7;
46
+ const UPPER_WIDTH = 7.5;
47
+ const LOWER_WIDTH = 6.5;
48
+ const charWidth = (char) => {
49
+ if (NARROW.has(char)) {
50
+ return 3;
51
+ }
52
+ if (SLIM.has(char)) {
53
+ return 4;
54
+ }
55
+ if (WIDE.has(char)) {
56
+ return 10;
57
+ }
58
+ if (/\d/.test(char)) {
59
+ return DIGIT_WIDTH;
60
+ }
61
+ return char === char.toLowerCase() ? LOWER_WIDTH : UPPER_WIDTH;
62
+ };
63
+ /** The estimated width of a text at 11px, whole pixels. Exported for the test. */
64
+ const textWidth = (text) => {
65
+ // By code point, which is what a glyph roughly is for the labels and figures this ever draws.
66
+ let width = 0;
67
+ for (const char of text) {
68
+ width += charWidth(char);
69
+ }
70
+ return Math.ceil(width);
71
+ };
72
+ exports.textWidth = textWidth;
73
+ // The quotes by number: every XML parser knows those, and they read the same in an attribute either
74
+ // way it is quoted.
75
+ const ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&#34;', "'": '&#39;' };
76
+ /** Text and attribute values both go through this: a name with `&` in it is not XML. */
77
+ const escapeXml = (text) => text.replaceAll(/[&<>"']/g, char => ESCAPES[char] ?? char);
78
+ exports.escapeXml = escapeXml;
79
+ /**
80
+ * The change against the baseline, as the badge shows it and as it is read out. The arrow is for
81
+ * the eye; a screen reader says "down-pointing triangle" for it, so the accessible name gets the
82
+ * signed figure instead.
83
+ */
84
+ const changeOf = (report) => {
85
+ const boot = report.comparison?.boot;
86
+ // Nothing before means no ratio: "+100 %" of nothing would be a number nobody can use.
87
+ if (!boot || boot.before === 0) {
88
+ return null;
89
+ }
90
+ if (boot.diff === 0) {
91
+ return { shown: '±0 %', spoken: '±0 %' };
92
+ }
93
+ const percent = Math.round(Math.abs(boot.ratio) * 100);
94
+ // A change that rounds to nothing still happened: "▲0 %" would read as a contradiction.
95
+ const figure = percent === 0 ? '<1 %' : `${percent} %`;
96
+ return boot.diff > 0
97
+ ? { shown: `▲${figure}`, spoken: `+${figure}` }
98
+ : { shown: `▼${figure}`, spoken: `−${figure}` };
99
+ };
100
+ /** One half of the badge's text: the shadow shields draws under it, then the text itself. */
101
+ const halfText = (text, centre, width) => {
102
+ const content = (0, exports.escapeXml)(text);
103
+ return (`<text aria-hidden="true" x="${centre}" y="15" fill="#010101" fill-opacity=".3" textLength="${width}">${content}</text>` +
104
+ `<text x="${centre}" y="14" textLength="${width}">${content}</text>`);
105
+ };
106
+ /** The badge for `--format badge`, an SVG document with nothing outside it to load. */
107
+ const renderBadge = (report) => {
108
+ const { analysis, criteria } = report;
109
+ const label = LABEL[report.lang];
110
+ const change = changeOf(report);
111
+ const size = (0, format_utils_1.formatBytes)(analysis.bootBytes);
112
+ const value = change ? `${size} ${change.shown}` : size;
113
+ const spoken = `${label}: ${change ? `${size}, ${change.spoken}` : size}`;
114
+ const color = exports.BADGE_COLOR[(0, criteria_1.rate)(analysis.bootBytes, criteria.bootOk, criteria.bootBad)];
115
+ const labelText = (0, exports.textWidth)(label);
116
+ const valueText = (0, exports.textWidth)(value);
117
+ const labelWidth = labelText + PADDING * 2;
118
+ const valueWidth = valueText + PADDING * 2;
119
+ const width = labelWidth + valueWidth;
120
+ const name = (0, exports.escapeXml)(spoken);
121
+ return [
122
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${HEIGHT}" role="img" aria-label="${name}">`,
123
+ `<title>${name}</title>`,
124
+ '<linearGradient id="loadline-shine" x2="0" y2="100%">',
125
+ '<stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/>',
126
+ '</linearGradient>',
127
+ `<clipPath id="loadline-round"><rect width="${width}" height="${HEIGHT}" rx="3" fill="#fff"/></clipPath>`,
128
+ '<g clip-path="url(#loadline-round)">',
129
+ `<rect width="${labelWidth}" height="${HEIGHT}" fill="${LABEL_COLOR}"/>`,
130
+ `<rect x="${labelWidth}" width="${valueWidth}" height="${HEIGHT}" fill="${color}"/>`,
131
+ `<rect width="${width}" height="${HEIGHT}" fill="url(#loadline-shine)"/>`,
132
+ '</g>',
133
+ `<g fill="#fff" text-anchor="middle" font-family="${FONT}" font-size="11">`,
134
+ halfText(label, labelWidth / 2, labelText),
135
+ halfText(value, labelWidth + valueWidth / 2, valueText),
136
+ '</g>',
137
+ '</svg>',
138
+ ].join('\n');
139
+ };
140
+ exports.renderBadge = renderBadge;