@bymaksym/loadline 1.0.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 (112) hide show
  1. package/README.md +211 -43
  2. package/dist/cli/cli/args.js +79 -128
  3. package/dist/cli/cli/gates.js +80 -14
  4. package/dist/cli/cli/main.js +164 -33
  5. package/dist/cli/cli/memory.js +40 -4
  6. package/dist/cli/cli/{declared.js → read/declared.js} +1 -1
  7. package/dist/cli/cli/read/locate.js +214 -0
  8. package/dist/cli/cli/{read-build.js → read/read-build.js} +149 -84
  9. package/dist/cli/cli/read/read-config.js +120 -0
  10. package/dist/cli/cli/{html-report.js → render/html-report.js} +14 -10
  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} +18 -5
  15. package/dist/cli/cli/{render-markdown.js → render/render-markdown.js} +5 -5
  16. package/dist/cli/cli/{render-pr.js → render/render-pr.js} +33 -13
  17. package/dist/cli/cli/{render-sarif.js → render/render-sarif.js} +8 -3
  18. package/dist/cli/cli/{render-text.js → render/render-text.js} +118 -111
  19. package/dist/cli/cli/render/terminal.js +55 -0
  20. package/dist/cli/cli/report.js +68 -27
  21. package/dist/cli/cli/self-check.js +19 -23
  22. package/dist/cli/cli/since-last.js +2 -2
  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 +63 -23
  27. package/dist/cli/src/app/core/analysis/{barrels.js → graph/barrels.js} +1 -1
  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 +7 -1
  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} +50 -9
  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} +1 -1
  40. package/dist/cli/src/app/core/analysis/tool.js +83 -0
  41. package/dist/cli/src/app/core/assets/assets.js +134 -15
  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 +168 -13
  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 +121 -43
  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 +104 -16
  53. package/dist/cli/src/app/core/export/summary.js +29 -5
  54. package/dist/cli/src/app/core/findings/actions.js +3 -1
  55. package/dist/cli/src/app/core/findings/{boot-single.js → bundle/boot-single.js} +3 -3
  56. package/dist/cli/src/app/core/findings/{dupes.js → bundle/dupes.js} +8 -5
  57. package/dist/cli/src/app/core/findings/{graph.js → bundle/graph.js} +30 -18
  58. package/dist/cli/src/app/core/findings/{own-in-boot.js → bundle/own-in-boot.js} +9 -5
  59. package/dist/cli/src/app/core/findings/{requests.js → bundle/requests.js} +3 -3
  60. package/dist/cli/src/app/core/findings/{shipped.js → bundle/shipped.js} +28 -14
  61. package/dist/cli/src/app/core/findings/compose.js +6 -1
  62. package/dist/cli/src/app/core/findings/effort.js +2 -0
  63. package/dist/cli/src/app/core/findings/finding.types.js +1 -0
  64. package/dist/cli/src/app/core/findings/findings.js +48 -19
  65. package/dist/cli/src/app/core/findings/{assets.js → folder/assets.js} +38 -14
  66. package/dist/cli/src/app/core/findings/{caching.js → folder/caching.js} +16 -9
  67. package/dist/cli/src/app/core/findings/{page.js → folder/page.js} +6 -2
  68. package/dist/cli/src/app/core/findings/{scan.js → folder/scan.js} +25 -11
  69. package/dist/cli/src/app/core/findings/kind-names.js +163 -0
  70. package/dist/cli/src/app/core/findings/{deps.js → supplied/deps.js} +13 -8
  71. package/dist/cli/src/app/core/findings/supplied/forbidden.js +71 -0
  72. package/dist/cli/src/app/core/findings/{situation.js → supplied/situation.js} +2 -2
  73. package/dist/cli/src/app/core/findings/text/causes.js +39 -0
  74. package/dist/cli/src/app/core/findings/{finding-html.js → text/finding-html.js} +8 -1
  75. package/dist/cli/src/app/core/findings/{finding-text.js → text/finding-text.js} +208 -77
  76. package/dist/cli/src/app/core/findings/text/tool-advice.js +97 -0
  77. package/dist/cli/src/app/core/format/format.utils.js +158 -11
  78. package/dist/cli/src/app/core/format/ownership.js +93 -0
  79. package/dist/cli/src/app/core/i18n/en.js +76 -17
  80. package/dist/cli/src/app/core/i18n/es.js +82 -22
  81. package/dist/cli/src/app/core/intake/bundle-graph.js +281 -43
  82. package/dist/cli/src/app/core/intake/dist-files.js +82 -14
  83. package/dist/cli/src/app/core/intake/embedded.js +11 -1
  84. package/dist/cli/src/app/core/intake/unreached.js +139 -0
  85. package/dist/cli/src/app/core/intake/webpack-modules.js +185 -0
  86. package/dist/cli/src/app/core/intake/webpack-stats.js +298 -0
  87. package/dist/cli/src/app/core/project/project-context.js +16 -4
  88. package/dist/cli/src/app/core/project/project-name.js +36 -0
  89. package/dist/cli/src/app/core/scan/scan.js +58 -19
  90. package/dist/cli/src/app/core/scan/secrets.js +23 -3
  91. package/dist/cli/src/app/core/situation/situation-text.js +23 -0
  92. package/dist/cli/src/app/core/situation/situation.js +6 -4
  93. package/dist/cli/src/app/core/timing/timing.js +5 -2
  94. package/dist/cli/src/app/core/whatif/defer.js +29 -4
  95. package/dist/cli/src/app/core/whatif/source-importers.js +58 -0
  96. package/dist/cli/src/app/core/whatif/why.js +102 -0
  97. package/docs/CONFIG-REFERENCE.md +230 -0
  98. package/docs/CONFIG.md +511 -0
  99. package/docs/HOW-IT-WORKS.md +286 -25
  100. package/loadline.html +24 -20
  101. package/loadline.schema.json +1209 -0
  102. package/package.json +35 -29
  103. package/dist/cli/cli/locate.js +0 -60
  104. package/dist/cli/cli/text.js +0 -215
  105. /package/dist/cli/cli/{read-build.types.js → read/read-build.types.js} +0 -0
  106. /package/dist/cli/cli/{render-json.types.js → render/render-json.types.js} +0 -0
  107. /package/dist/cli/cli/{text.types.js → text/text.types.js} +0 -0
  108. /package/dist/cli/src/app/core/analysis/{exclusive.js → graph/exclusive.js} +0 -0
  109. /package/dist/cli/src/app/core/analysis/{insights.types.js → graph/insights.types.js} +0 -0
  110. /package/dist/cli/src/app/core/analysis/{module-graph.js → graph/module-graph.js} +0 -0
  111. /package/dist/cli/src/app/core/analysis/{sourcemap.types.js → sourcemap/sourcemap.types.js} +0 -0
  112. /package/dist/cli/src/app/core/findings/{finding-plain.js → text/finding-plain.js} +0 -0
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ /**
3
+ * The route table a router keeps in the code, read where each lazy route names its chunk.
4
+ *
5
+ * Every router that splits by route writes the same shape: an object with a `path` and a key whose
6
+ * value imports the chunk — `component: () => import('./Home.js')` in vue-router and Nuxt,
7
+ * `loadComponent` and `loadChildren` in Angular, `lazy` and `getComponent` in React Router,
8
+ * `asyncComponent` under a path written as the key in svelte-spa-router. A router that uses another
9
+ * word is named in `build.routeKeys` of `loadline.json`. Minifiers keep the keys,
10
+ * because they are the router's API. What that gives the report is the one thing the files alone
11
+ * cannot: which lazy chunks are places somebody navigates to. A language file Nuxt loads with
12
+ * `load: () => import(…)`, a tab of documentation behind `{ label, component }` with no path, an
13
+ * async component inside a page — all of those are lazy and none of them is a screen, and without
14
+ * source maps the report used to list them as screens named after hashes.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.sapperRoutesIn = exports.routeLabel = exports.routeBefore = exports.routeKeyPattern = exports.isRouteKey = void 0;
18
+ /** The keys that hand a router the chunk of a route. */
19
+ const ROUTE_KEYS = new Set(['component', 'loadComponent', 'loadChildren', 'lazy', 'getComponent', 'asyncComponent']);
20
+ /** What a key of `build.routeKeys` may be: a property name a minifier keeps as it is written. */
21
+ const isRouteKey = (key) => /^[A-Z_$][\w$]*$/i.test(key);
22
+ exports.isRouteKey = isRouteKey;
23
+ /**
24
+ * The keys as one pattern, with the ones `build.routeKeys` adds. Only property names get in
25
+ * (`isRouteKey`), so the pattern is an alternation of words and stays linear.
26
+ */
27
+ const routeKeyPattern = (extra = []) => {
28
+ const keys = [...ROUTE_KEYS, ...extra.filter(key => (0, exports.isRouteKey)(key) && !ROUTE_KEYS.has(key))];
29
+ return new RegExp(String.raw `(?<![\w$])(?:${keys.map(key => key.replaceAll('$', String.raw `\$`)).join('|')})\s*:`, 'g');
30
+ };
31
+ exports.routeKeyPattern = routeKeyPattern;
32
+ const ROUTE_KEY = (0, exports.routeKeyPattern)();
33
+ /** `path: '…'` or `name: '…'` at the top level of the object, in any of the three quotes. */
34
+ const ROUTE_FIELD = /[,{]\s*(path|name)\s*:\s*(['"`])([^'"`]*)\2/g;
35
+ /**
36
+ * The path as the key of the route, the way svelte-spa-router writes its table: `"/users/:id":
37
+ * wrap({`, read off the end of what comes before the object. It has to start with a slash, or any
38
+ * `{ component }` inside any object property would be a route.
39
+ */
40
+ const KEYED_PATH = /(['"`])(\/[^'"`]*)\1\s*:\s*(?:[\w$.]+\s*)?\(\s*$/;
41
+ /** How far back a route object can start. A route with guards, meta and a validator fits in this. */
42
+ const WINDOW = 800;
43
+ /** How far the import can be from its key: `component: () => Q(() => import(` and nothing longer. */
44
+ const KEY_REACH = 80;
45
+ const OPEN = new Set(['{', '(', '[']);
46
+ const CLOSE = new Set(['}', ')', ']']);
47
+ /**
48
+ * The route whose key imports at `index`, or `null` when that import is not a route's.
49
+ *
50
+ * The object is walked back from the key, counting braces, so `meta: { … }` in between is skipped
51
+ * and a `path` of the route before this one is never taken for this one's. Bounded both ways, so a
52
+ * bundle of several megabytes costs a fixed amount per lazy import and nothing more.
53
+ */
54
+ const routeBefore = (code, index, keys = ROUTE_KEY) => {
55
+ const start = Math.max(0, index - WINDOW);
56
+ const window = code.slice(start, index);
57
+ let key = -1;
58
+ for (const match of window.matchAll(keys)) {
59
+ key = match.index;
60
+ }
61
+ if (key === -1 || window.length - key > KEY_REACH) {
62
+ return null;
63
+ }
64
+ // Back to the brace that opens this route, keeping only what sits at its own level.
65
+ let depth = 0;
66
+ let open = -1;
67
+ const level = [];
68
+ for (let position = key - 1; position >= 0; position--) {
69
+ const char = window[position] ?? '';
70
+ if (CLOSE.has(char)) {
71
+ depth++;
72
+ }
73
+ else if (OPEN.has(char)) {
74
+ if (depth === 0) {
75
+ open = position;
76
+ break;
77
+ }
78
+ depth--;
79
+ }
80
+ else if (depth === 0) {
81
+ level.push(char);
82
+ }
83
+ }
84
+ if (open === -1 || window[open] !== '{') {
85
+ return null;
86
+ }
87
+ const own = `{${level.toReversed().join('')}`;
88
+ let path = null;
89
+ let name = null;
90
+ for (const [, field, , value = ''] of own.matchAll(ROUTE_FIELD)) {
91
+ if (field === 'path') {
92
+ path = value;
93
+ }
94
+ else {
95
+ name = value;
96
+ }
97
+ }
98
+ path ??= KEYED_PATH.exec(window.slice(Math.max(0, open - 200), open))?.[2] ?? null;
99
+ return path === null ? null : { path, name: name || null };
100
+ };
101
+ exports.routeBefore = routeBefore;
102
+ /** What a screen is called by its routes: the router's name for it, or its path. */
103
+ const routeLabel = (route) => route.name ?? (route.path === '' ? '/' : route.path);
104
+ exports.routeLabel = routeLabel;
105
+ /**
106
+ * Sapper's table, which has none of the shapes above. Its manifest is two lists: the components,
107
+ * `{js:()=>import("./index.e902f999.js"),css:[…]}`, and the routes, each a regular expression and the
108
+ * components of its layouts and its page by their place in the first list:
109
+ * `{pattern:/^\/profile\/([^\/]+?)\/?$/,parts:[null,{i:5,params:t=>({user:e(t[1])})}]}`. Without it,
110
+ * a build without source maps had seven screens named `index` and told them apart by their hashes.
111
+ */
112
+ const SAPPER_COMPONENT = /\bjs\s*:\s*\(\s*\)\s*=>\s*import\(\s*(["'`])([^"'`]+)\1\s*\)/g;
113
+ /** A route of the table, up to its parts: the source of the expression, escapes kept. */
114
+ const SAPPER_ROUTE = /\bpattern\s*:\s*\/\^((?:[^\n/\\]|\\.)*)\/[a-z]*\s*,\s*parts\s*:\s*\[/g;
115
+ /** A part of a route: `i:5`, the place of its component. The last one is the page. */
116
+ const SAPPER_PART = /\bi\s*:\s*(\d+)/g;
117
+ /** A parameter of a route, `user:e(t[1])`: its name and the group of the expression it is read from. */
118
+ const SAPPER_PARAM = /([\w$]+)\s*:\s*[\w$]+\(\s*[\w$]+\[(\d+)\]\s*\)/g;
119
+ /**
120
+ * A group of the expression, `([^\/]+?)`, with the escapes and the character classes inside it read
121
+ * whole so a `)` in them does not end it. Sapper writes no group inside another.
122
+ */
123
+ const SAPPER_GROUP = /\((?:\\.|\[(?:\\.|[^\\\]])*\]|[^()[\\])*\)/g;
124
+ /** How far after its expression the parts of a route can be: a route with three parameters fits. */
125
+ const PARTS_REACH = 400;
126
+ /**
127
+ * The path a route's expression matches, with each group named by its parameter, the way Sapper's
128
+ * files are named: `^\/article\/([^\/]+?)\/?$` is `/article/[slug]`.
129
+ */
130
+ const sapperPath = (source, params) => {
131
+ let group = 0;
132
+ const path = source
133
+ .replaceAll(SAPPER_GROUP, () => {
134
+ group += 1;
135
+ return `[${params.get(group) ?? group}]`;
136
+ })
137
+ // An escape is the character it escapes; `$` is the end and `?` the optional slash before it.
138
+ .replaceAll(/\\(.)|[$?]/g, (_, escaped) => escaped ?? '');
139
+ // What is left of the ending `\/?$` is that slash, which no route is called by.
140
+ return path.length > 1 ? path.replace(/\/$/, '') : path;
141
+ };
142
+ /**
143
+ * The parts of a route, from after `parts:[` to the bracket that closes the list, so that what the
144
+ * last route is read from ends where the table does and not in the code after it.
145
+ */
146
+ const partsAfter = (code, start) => {
147
+ let depth = 1;
148
+ const end = Math.min(code.length, start + PARTS_REACH);
149
+ for (let at = start; at < end; at++) {
150
+ const char = code[at] ?? '';
151
+ if (OPEN.has(char)) {
152
+ depth++;
153
+ }
154
+ else if (CLOSE.has(char) && --depth === 0) {
155
+ return code.slice(start, at);
156
+ }
157
+ }
158
+ return '';
159
+ };
160
+ /** The routes of Sapper's manifest in a chunk, by the specifier of the page each one opens. */
161
+ const sapperRoutesIn = (code) => {
162
+ const routes = [...code.matchAll(SAPPER_ROUTE)];
163
+ if (routes.length === 0) {
164
+ return [];
165
+ }
166
+ const components = [...code.matchAll(SAPPER_COMPONENT)].map(match => match[2] ?? '');
167
+ return routes.flatMap(match => {
168
+ const parts = partsAfter(code, match.index + match[0].length);
169
+ const page = [...parts.matchAll(SAPPER_PART)].at(-1)?.[1];
170
+ const specifier = page === undefined ? undefined : components[Number(page)];
171
+ if (specifier === undefined) {
172
+ return [];
173
+ }
174
+ const params = new Map([...parts.matchAll(SAPPER_PARAM)].map(([, name = '', group]) => [Number(group), name]));
175
+ return [{ specifier, route: { path: sapperPath(match[1] ?? '', params), name: null } }];
176
+ });
177
+ };
178
+ exports.sapperRoutesIn = sapperRoutesIn;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ /**
3
+ * What a build's own files say about the tool that wrote it, read by the folder reader for the
4
+ * advice the report gives (`analysis/tool.ts`), and the one thing a tool writes that changes how a
5
+ * folder is read: Stencil's list of components.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.builtByOf = exports.toolsIn = exports.stencilComponentsIn = void 0;
9
+ /**
10
+ * Stencil's list of lazy components, which its loader carries in the entry: `["p-w91mnxr1",[[1,
11
+ * "app-home"]]]` — the id of a chunk, `<id>.entry.js`, and the first custom element it defines. It is
12
+ * read the way a router's table is: the components are what gets loaded on demand and are named by
13
+ * their tag, and what the loader fetches that is not in the list — the polyfills for browsers
14
+ * without custom elements or CSS variables — is no component. A Stencil app listed twelve screens
15
+ * named `p-qidxadfy.entry`, three of them its polyfills.
16
+ */
17
+ const STENCIL_COMPONENT = /\["([\w-]+)",\[\[\d+,"([a-z]\w*-[\w-]*)"/g;
18
+ /** The components Stencil's loader lists in a chunk: the id of each chunk and its first tag. */
19
+ const stencilComponentsIn = (code) => [...code.matchAll(STENCIL_COMPONENT)].map(([, id = '', tag = '']) => ({ id, tag }));
20
+ exports.stencilComponentsIn = stencilComponentsIn;
21
+ /**
22
+ * What a chunk says about the tool that wrote it, for the advice the report gives (`analysis/tool.ts`).
23
+ * Each is something only that tool writes: Vite's preload helper, and the attribute Angular's
24
+ * runtime sets on every root element. A folder with source maps names the packages anyway; these
25
+ * are for one without.
26
+ */
27
+ const VITE_MARK = /__vitePreload|__vite__mapDeps|vite\/modulepreload-polyfill/;
28
+ const ANGULAR_MARK = /["']ng-version["']/;
29
+ /** What one chunk says: `stencil` when it carried Stencil's list of components. */
30
+ const toolsIn = (code, stencil) => ({
31
+ ...(VITE_MARK.test(code) && { bundler: 'vite' }),
32
+ ...(stencil && { framework: 'stencil', bundler: 'rollup' }),
33
+ ...(ANGULAR_MARK.test(code) && { framework: 'angular' }),
34
+ });
35
+ exports.toolsIn = toolsIn;
36
+ /**
37
+ * What the page says about the tool, for the frameworks whose page carries their name: Sapper's and
38
+ * Nuxt's state, SvelteKit's start-up, the meta every Ember app has, and Polymer's loader.
39
+ */
40
+ const PAGE_MARKS = [
41
+ [/__SAPPER__/, { framework: 'sapper', bundler: 'rollup' }],
42
+ [/__NUXT__|\/_nuxt\//, { framework: 'nuxt', bundler: 'vite' }],
43
+ [/__sveltekit/, { framework: 'sveltekit', bundler: 'vite' }],
44
+ [/<meta name="[\w-]+\/config\/environment"/, { framework: 'ember' }],
45
+ [/webcomponents-loader\.js|@webcomponents\/webcomponentsjs/, { framework: 'polymer' }],
46
+ ];
47
+ /** The tool, from the page first and then from the chunks; the page names the framework more surely. */
48
+ const builtByOf = (html, chunks) => {
49
+ const page = PAGE_MARKS.find(([mark]) => html !== null && mark.test(html))?.[1] ?? {};
50
+ const bundler = page.bundler ?? chunks.find(tools => tools.bundler)?.bundler;
51
+ const framework = page.framework ?? chunks.find(tools => tools.framework)?.framework;
52
+ return { ...(bundler && { bundler }), ...(framework && { framework }) };
53
+ };
54
+ exports.builtByOf = builtByOf;
@@ -9,7 +9,8 @@
9
9
  * the names carry hashes, which is the third figure here and the reason it is measured too.
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.readCaching = exports.unhashableFiles = exports.unstableChunks = exports.updateCostOf = exports.unhashedName = void 0;
12
+ exports.readCaching = exports.unhashableFiles = exports.unstableChunks = exports.updateCostOf = exports.carriesHash = exports.unhashedName = void 0;
13
+ const assets_1 = require("../assets/assets");
13
14
  /**
14
15
  * A content hash in a file name: `main-A1B2C3D4.js`, `main.a1b2c3d4.js`, `chunk-0fPdmq0U.mjs`.
15
16
  *
@@ -41,11 +42,47 @@ const MIXED_CASE = /(?=.*[a-z])(?=.*[A-Z])/;
41
42
  const WRITTEN_PREFIX = /^[a-z]{3,}[.\-_]/;
42
43
  /** A version pinned in the query string: `app.js?v=3`. It defeats the cache on every deploy. */
43
44
  const VERSIONED_QUERY = /[?&]v(?:er|ersion)?=/i;
44
- /** The name with its content hash taken off, which is what makes two builds' files comparable. */
45
- const unhashedName = (name) => name.replace(/[.\-_][\w-]{8,}(\.[\da-z]+)$/, '$1');
45
+ /**
46
+ * Rollup's and Vite's hash: exactly eight characters, the last thing before the extension. Read
47
+ * first because a name can carry a hash of its own in front of it — mermaid ships
48
+ * `chunk-QN33PNHL-CkKTlLkk.js` — and the general pattern below, which starts at the first separator
49
+ * it can, took both off and left `chunk.js`: every one of those chunks under a single name.
50
+ */
51
+ const LAST_HASH = /[.\-_][\w-]{8}(\.[\da-z]+)$/;
52
+ const ANY_HASH = /[.\-_][\w-]{8,}(\.[\da-z]+)$/;
53
+ /**
54
+ * A hash with a second extension after it: `p-w91mnxr1.entry.js`, `p-o63olsly.system.entry.js`.
55
+ * Stencil writes every chunk that way, and thirty of the thirty-four files a Stencil build was told
56
+ * carried no hash did carry one. It has to hold a digit: `react.production.min.js` is the same shape
57
+ * with a word where the hash would be, and a word is what it is.
58
+ */
59
+ const INNER_HASH = /[.\-_](?=[a-z]*\d)[\da-z]{8,}(?:\.[a-z]+){2,}$/i;
60
+ /**
61
+ * The name with its content hash taken off, which is what makes two builds' files comparable.
62
+ *
63
+ * A hash before a second extension comes off too, keeping both extensions: `widget.a1b2c3d4.entry.js`
64
+ * is `widget.entry.js`. Not when what is left in front is one letter: Stencil's `p-w91mnxr1.entry.js`
65
+ * is all hash, and taking it off would give every chunk of the build the one name `p.entry.js`. Those
66
+ * keep their names, which is right for comparing: the hash is of the content, so a chunk that did not
67
+ * change is under the same name in both builds.
68
+ */
69
+ const unhashedName = (name) => {
70
+ if (LAST_HASH.test(name)) {
71
+ return name.replace(LAST_HASH, '$1');
72
+ }
73
+ const inner = INNER_HASH.exec(name);
74
+ if (inner && inner.index > 1) {
75
+ const hashed = inner[0];
76
+ return `${name.slice(0, inner.index)}${hashed.slice(hashed.indexOf('.', 1))}`;
77
+ }
78
+ return name.replace(ANY_HASH, '$1');
79
+ };
46
80
  exports.unhashedName = unhashedName;
47
81
  /** A name that is nothing but a hash: `ChDGvcpR.js`. Taking the hash off it would leave `.js`. */
48
82
  const isBareHash = (name) => BARE_HASH.test(name) && MIXED_CASE.test(name) && !WRITTEN_PREFIX.test(name);
83
+ /** Whether a file name carries a content hash, in any of the ways a bundler writes one. */
84
+ const carriesHash = (name) => HASHED.test(name) || INNER_HASH.test(name) || isBareHash(name);
85
+ exports.carriesHash = carriesHash;
49
86
  /**
50
87
  * The key a file is matched by across two builds.
51
88
  *
@@ -66,19 +103,56 @@ const isBareHash = (name) => BARE_HASH.test(name) && MIXED_CASE.test(name) && !W
66
103
  * front of it is there so it can never be mistaken for a file name.
67
104
  */
68
105
  const CONTENT_KEY = '\u{0}';
69
- const keysOf = (files) => {
70
- const perContent = new Map();
106
+ /**
107
+ * The name with the hash off. A name that is nothing but the hash comes back as itself, which no
108
+ * file of the other build carries, so it simply pairs with nothing here and goes on to content.
109
+ */
110
+ const byName = name => (0, exports.unhashedName)(name);
111
+ /** What the chunk is built around, for the names that say nothing — or that several files share. */
112
+ const byContent = (_name, file) => (file.content ? `${CONTENT_KEY}${file.content}` : null);
113
+ /** How many files of one side each key names. A pairing is only trusted when it names one on each. */
114
+ const countKeys = (files, rule) => {
115
+ const counts = new Map();
71
116
  for (const [name, file] of files) {
72
- if (file.content && isBareHash(name)) {
73
- perContent.set(file.content, (perContent.get(file.content) ?? 0) + 1);
117
+ const key = rule(name, file);
118
+ if (key !== null) {
119
+ counts.set(key, (counts.get(key) ?? 0) + 1);
74
120
  }
75
121
  }
76
- const keys = new Map();
77
- for (const [name, file] of files) {
78
- const byContent = !!file.content && isBareHash(name) && perContent.get(file.content) === 1;
79
- keys.set(name, byContent ? `${CONTENT_KEY}${file.content ?? ''}` : (0, exports.unhashedName)(name));
122
+ return counts;
123
+ };
124
+ /**
125
+ * Pairs the files of the two builds that are the same file, and takes them out of both lists.
126
+ *
127
+ * A key only pairs when it names exactly one file on each side. Angular calls every lazy chunk
128
+ * `chunk-XXXXXXXX.js`, so with the hash off twenty files share the name `chunk.js`; letting the last
129
+ * of them stand for all twenty reported an unchanged, same-named file as re-downloaded and put the
130
+ * edit in a chunk the edit never touched. Twenty chunks under one name say nothing about which is
131
+ * which, and the next rule — what each is built around — usually does.
132
+ */
133
+ const pairBy = (current, previous, rule) => {
134
+ const currentCounts = countKeys(current, rule);
135
+ const previousCounts = countKeys(previous, rule);
136
+ const previousByKey = new Map();
137
+ for (const [name, file] of previous) {
138
+ const key = rule(name, file);
139
+ if (key !== null) {
140
+ previousByKey.set(key, name);
141
+ }
142
+ }
143
+ const pairs = new Map();
144
+ for (const [name, file] of current) {
145
+ const key = rule(name, file);
146
+ const was = key === null ? undefined : previousByKey.get(key);
147
+ if (key !== null && was !== undefined && currentCounts.get(key) === 1 && previousCounts.get(key) === 1) {
148
+ pairs.set(name, was);
149
+ }
150
+ }
151
+ for (const [name, was] of pairs) {
152
+ current.delete(name);
153
+ previous.delete(was);
80
154
  }
81
- return keys;
155
+ return pairs;
82
156
  };
83
157
  /**
84
158
  * The changed files split into the edit and the cascade it set off.
@@ -121,37 +195,31 @@ const cascadeOf = (changed, importers) => {
121
195
  * always was, and the split into edit and cascade is `null` rather than guessed.
122
196
  */
123
197
  const updateCostOf = (current, previous, importers = null) => {
124
- const previousKeys = keysOf(previous);
125
- const currentKeys = keysOf(current);
126
- const before = new Map();
127
- for (const [name, file] of previous) {
128
- before.set(previousKeys.get(name) ?? (0, exports.unhashedName)(name), { name, bytes: file.bytes });
129
- }
198
+ // Same name, same content, still in the browser's cache: nothing to download. This goes first
199
+ // and is not a key like the others — a name both builds carry is the same file whatever any
200
+ // rule below would have made of it.
201
+ const reused = [...current.keys()].filter(name => previous.has(name)).length;
202
+ const leftNow = new Map([...current].filter(([name]) => !previous.has(name)));
203
+ const leftBefore = new Map([...previous].filter(([name]) => !current.has(name)));
204
+ // Content is the fallback for the names that have nothing left underneath, and for the ones
205
+ // several files share — not a replacement for a name that survived the hash coming off.
206
+ const paired = new Set([
207
+ ...pairBy(leftNow, leftBefore, byName).keys(),
208
+ ...pairBy(leftNow, leftBefore, byContent).keys(),
209
+ ]);
210
+ let fresh = 0;
130
211
  const changed = [];
131
212
  const added = [];
132
- const seen = new Set();
133
- let reused = 0;
134
- let fresh = 0;
135
213
  for (const [name, file] of current) {
136
- const bytes = file.bytes;
137
- fresh += bytes;
138
- const key = currentKeys.get(name) ?? (0, exports.unhashedName)(name);
139
- const was = before.get(key);
140
- seen.add(key);
141
- if (!was) {
142
- added.push({ name, change: 'added', bytes });
143
- }
144
- else if (was.name === name) {
145
- // Same name, same content, still in the browser's cache. Nothing to download.
146
- reused += 1;
214
+ fresh += file.bytes;
215
+ if (paired.has(name)) {
216
+ changed.push({ name, change: 'changed', bytes: file.bytes });
147
217
  }
148
- else {
149
- changed.push({ name, change: 'changed', bytes });
218
+ else if (!previous.has(name)) {
219
+ added.push({ name, change: 'added', bytes: file.bytes });
150
220
  }
151
221
  }
152
- const removed = [...before]
153
- .filter(([key]) => !seen.has(key))
154
- .map(([, was]) => ({ name: was.name, change: 'removed', bytes: was.bytes }));
222
+ const removed = [...leftBefore].map(([name, was]) => ({ name, change: 'removed', bytes: was.bytes }));
155
223
  const bytes = [...changed, ...added].reduce((sum, file) => sum + file.bytes, 0);
156
224
  const byWeight = changed.toSorted((a, b) => b.bytes - a.bytes);
157
225
  return {
@@ -180,13 +248,22 @@ exports.updateCostOf = updateCostOf;
180
248
  const unstableChunks = (chunks, minRatio) => chunks
181
249
  .map((chunk) => {
182
250
  const total = chunk.vendorBytes + chunk.ownBytes;
251
+ const compressed = (chunk.rawBytes ?? chunk.bytes) !== chunk.bytes;
183
252
  return {
184
253
  name: chunk.name,
185
254
  bytes: chunk.bytes,
186
255
  vendorRatio: total > 0 ? chunk.vendorBytes / total : 0,
187
256
  // Only when the chunk holds both. A chunk that is nothing but vendor code is the
188
257
  // right answer, not the problem: its hash does not move when the project changes.
189
- vendorBytes: chunk.ownBytes > 0 ? chunk.vendorBytes : 0,
258
+ // In the report's unit: what is re-downloaded is the chunk, and the chunk has a
259
+ // compressed size, which the split inside it — raw, always — does not. Given raw, a
260
+ // gzip report said "283 kB re-invalidated" over an 87 kB bootstrap.
261
+ vendorBytes: chunk.ownBytes === 0
262
+ ? 0
263
+ : compressed
264
+ ? Math.round((chunk.vendorBytes / total) * chunk.bytes)
265
+ : chunk.vendorBytes,
266
+ estimated: compressed,
190
267
  inBoot: chunk.inBoot,
191
268
  };
192
269
  })
@@ -216,19 +293,20 @@ const NEVER_HASHED = /(?:\.map|\.html?|\.br|\.brotli|\.gz|\.zst)$/i;
216
293
  * except that it changes it for **every** file at once.
217
294
  */
218
295
  const unhashableFiles = (files, referencedAs, inPage) => files
219
- .filter(file => !NEVER_HASHED.test(file.name))
296
+ .filter(file => !NEVER_HASHED.test(file.name) && !assets_1.SERVER_FILE.test(file.name))
220
297
  .map((file) => {
221
298
  // Every rule below reads the name, because that is what a hash is written into and what
222
299
  // the page, the metafile and the compressed copies all key a file by. Only what gets
223
300
  // printed is the path.
301
+ // Except whether the page asks for it, which goes by the path when there is one: 25
302
+ // `plugin.min.js` by name were all "asked for by the page" when it named one.
224
303
  const at = { name: file.name, path: file.path ?? file.name, bytes: file.bytes };
304
+ const asked = inPage.has(at.path);
225
305
  const reference = referencedAs.get(file.name) ?? file.name;
226
306
  if (VERSIONED_QUERY.test(reference)) {
227
- return { ...at, reason: 'query', inPage: inPage.has(file.name) };
307
+ return { ...at, reason: 'query', inPage: asked };
228
308
  }
229
- const bare = isBareHash(file.name);
230
- const hashed = HASHED.test(file.name) || bare;
231
- return hashed ? null : { ...at, reason: 'none', inPage: inPage.has(file.name) };
309
+ return (0, exports.carriesHash)(file.name) ? null : { ...at, reason: 'none', inPage: asked };
232
310
  })
233
311
  .filter(file => file !== null)
234
312
  .toSorted((a, b) => Number(b.inPage) - Number(a.inPage) || b.bytes - a.bytes);
@@ -31,7 +31,14 @@ const chunksOf = (analysis) => {
31
31
  const ownBytes = node.children
32
32
  .filter(child => child.kind === 'folder')
33
33
  .reduce((sum, child) => sum + child.bytes, 0);
34
- return { name: node.label, bytes: node.bytes, inBoot: boot.has(node.id), vendorBytes, ownBytes };
34
+ return {
35
+ name: node.label,
36
+ bytes: node.bytes,
37
+ rawBytes: node.rawBytes,
38
+ inBoot: boot.has(node.id),
39
+ vendorBytes,
40
+ ownBytes,
41
+ };
35
42
  });
36
43
  };
37
44
  /**
@@ -43,11 +50,16 @@ const chunksOf = (analysis) => {
43
50
  * @param baseline the previous build. Only the snapshots that carry `files` can answer what an
44
51
  * update costs; an older export cannot, and the report says nothing rather than
45
52
  * guessing from the byte totals.
53
+ * @param weighed what each script and stylesheet of the folder weighs in the unit of the report, by
54
+ * name. A file named here is said in it; the rest — an image, a font — travel as
55
+ * they are. Without it the list of names that carry no hash said `my-app.js (681 kB)`
56
+ * under a heading of compressed figures, for a file that travels as 173 kB.
46
57
  */
47
- const cachingOf = (analysis, baseline, assets, inPage, hrefs = []) => {
58
+ const cachingOf = (analysis, baseline, assets, inPage, hrefs = [], weighed = null) => {
48
59
  // What the page asks for, as the folder reader worked it out. Without a folder there is only
49
60
  // what `index.html` announced of the JavaScript, which is what the caller passes.
50
- const named = assets ? new Set(assets.inPage) : inPage;
61
+ // By path when the folder was read, which is also what the files below carry.
62
+ const named = assets ? new Set(assets.inPagePaths) : inPage;
51
63
  const current = new Map(analysis.allChunks.map(file => {
52
64
  const chunk = analysis.chunkOf(file);
53
65
  return [(0, format_utils_1.baseName)(file), { bytes: chunk?.bytes ?? 0, content: chunk?.mainContent }];
@@ -60,7 +72,11 @@ const cachingOf = (analysis, baseline, assets, inPage, hrefs = []) => {
60
72
  previous,
61
73
  chunks: chunksOf(analysis),
62
74
  files: assets
63
- ? assets.files.map(file => ({ name: file.name, path: file.path, bytes: file.bytes }))
75
+ ? assets.files.map(file => ({
76
+ name: file.name,
77
+ path: file.path,
78
+ bytes: weighed?.get(file.name) ?? file.bytes,
79
+ }))
64
80
  : [...current].map(([name, file]) => ({ name, bytes: file.bytes })),
65
81
  referencedAs: new Map(hrefs.map(href => [(0, format_utils_1.baseName)(/^[^?#]*/.exec(href)?.[0] ?? ''), href])),
66
82
  // Keyed by file name, because that is the only thing the two builds have in common: the
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ /**
3
+ * What is said about a `loadline.json` that got something wrong, in both languages of the report.
4
+ *
5
+ * The command prints these under a report in the language it was asked for, and a Spanish report
6
+ * with its warnings in English read as two tools. The keys in quotes stay as they are written in
7
+ * the file: they are what somebody searches the file for.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.CONFIG_TEXT = void 0;
11
+ exports.CONFIG_TEXT = {
12
+ en: {
13
+ notConfig: 'Not a loadline.json: it needs "tool": "loadline" and "version": 1.',
14
+ unknownTopKey: key => `"${key}" is not a key of loadline.json, and nothing reads it.`,
15
+ badExtends: '"extends" has to be a file or a package, or a list of them, like "@acme/loadline-config". Nothing is inherited.',
16
+ extendsMode: (own, base, baseMode, ownMode) => `${own} says "mode": "${ownMode}", but ${base}, which it extends, writes its sizes in ${baseMode}: every inherited threshold would be read in the wrong unit. Use the same "mode", or leave it out.`,
17
+ badMode: given => `"mode" has to be "raw", "gzip" or "brotli", not ${given}. It is ignored.`,
18
+ criteriaNotObject: '"criteria" has to be an object of thresholds. It is ignored.',
19
+ unknownCriterion: key => `"criteria.${key}" is not one of the criteria, so it changes nothing.`,
20
+ recommendedStays: problem => `${problem} The recommended value stays.`,
21
+ gatesNotObject: '"gates" has to be an object. No gate from the file applies.',
22
+ unknownGate: key => `"gates.${key}" is not a gate, so it guards nothing.`,
23
+ gateOff: problem => `${problem} That gate cannot run.`,
24
+ badFailOn: given => `"gates.failOn" has to be "high", "mid" or "none", not ${given}.`,
25
+ badFailOnNewPackage: '"gates.failOnNewPackage" has to be true or false.',
26
+ badFailOnSignals: '"gates.failOnSignals" has to be a list of signals, like ["forbidden", "secrets"].',
27
+ unknownFailOnSignal: kind => `"gates.failOnSignals" names ${kind}, which is not a signal.`,
28
+ badScreens: '"gates.screens" has to map a screen to a size, like { "rooms": "400kB" }.',
29
+ badPackages: '"packages" has to be a list of package names. It is ignored.',
30
+ forbiddenNotList: '"forbidden" has to be a list of rules, like [{ "package": "moment", "why": "…" }].',
31
+ forbiddenWhat: where => `The "forbidden" rule ${where} has to name a "package" or a "path" — one of the two.`,
32
+ forbiddenIn: (where, given) => `The "in" of the "forbidden" rule ${where} has to be "bootstrap" or "anywhere", not ${given}.`,
33
+ forbiddenNoWhy: where => `The "forbidden" rule ${where} has no "why". It is the first thing whoever meets it reads.`,
34
+ badBuild: '"build" has to be an object, like { "entries": ["main.*.js"] }. It is ignored.',
35
+ badBuildList: key => `"build.${key}" has to be a list of names or paths, like ["main.*.js"]. It is ignored.`,
36
+ badBuildScreens: '"build.screens" has to map a file to "screen" or "piece", like { "*.widget.ts": "piece" }. It is ignored.',
37
+ badRouteKey: key => `"${key}" in "build.routeKeys" is not a property name, like "page". It is ignored.`,
38
+ badBuildScreen: pattern => `"build.screens" says something other than "screen" or "piece" for ${pattern}. That line is ignored.`,
39
+ badBuildPage: '"build.page" has to be the name of an HTML file of the build, like "app.html". It is ignored.',
40
+ notSize: (where, given) => `${where} has to be a size like "350kB" or "1.5MB", not ${given}.`,
41
+ bareSize: (where, given) => `${where} is ${given}, which would be ${given} bytes. Write "${given}kB", or "${given}B" if bytes are meant.`,
42
+ notShare: (where, given) => `${where} has to be a share like "25%" or 0.25, not ${given}.`,
43
+ notNumber: (where, given) => `${where} has to be a number, not ${given}.`,
44
+ acceptedNotList: '"accepted" has to be a list. Nothing in it is accepted.',
45
+ unknownAccepted: kind => `Unknown signal in "accepted": ${kind}. It accepts nothing.`,
46
+ noWhy: where => `The acceptance of ${where} has no "why". An acceptance without a reason is a suppression.`,
47
+ bytesOf: where => `The "bytes" of ${where}`,
48
+ ignored: problem => `${problem} It is ignored.`,
49
+ badUntil: (where, until) => `The "until" of ${where} is not a YYYY-MM-DD date: ${until}. It is ignored.`,
50
+ },
51
+ es: {
52
+ notConfig: 'No es un loadline.json: necesita "tool": "loadline" y "version": 1.',
53
+ unknownTopKey: key => `"${key}" no es una clave de loadline.json y nada la lee.`,
54
+ badExtends: '"extends" tiene que ser un fichero o un paquete, o una lista de ellos, como "@acme/loadline-config". No se hereda nada.',
55
+ extendsMode: (own, base, baseMode, ownMode) => `${own} dice "mode": "${ownMode}", pero ${base}, del que hereda, escribe sus tamaños en ${baseMode}: todos los umbrales heredados se leerían en otra unidad. Pon el mismo "mode" o quítalo.`,
56
+ badMode: given => `"mode" tiene que ser "raw", "gzip" o "brotli", no ${given}. Se ignora.`,
57
+ criteriaNotObject: '"criteria" tiene que ser un objeto de umbrales. Se ignora.',
58
+ unknownCriterion: key => `"criteria.${key}" no es ninguno de los criterios, así que no cambia nada.`,
59
+ recommendedStays: problem => `${problem} Se queda el valor recomendado.`,
60
+ gatesNotObject: '"gates" tiene que ser un objeto. No se aplica ningún gate del fichero.',
61
+ unknownGate: key => `"gates.${key}" no es un gate, así que no vigila nada.`,
62
+ gateOff: problem => `${problem} Ese gate no puede comprobarse.`,
63
+ badFailOn: given => `"gates.failOn" tiene que ser "high", "mid" o "none", no ${given}.`,
64
+ badFailOnNewPackage: '"gates.failOnNewPackage" tiene que ser true o false.',
65
+ badFailOnSignals: '"gates.failOnSignals" tiene que ser una lista de señales, como ["forbidden", "secrets"].',
66
+ unknownFailOnSignal: kind => `"gates.failOnSignals" nombra ${kind}, que no es una señal.`,
67
+ badScreens: '"gates.screens" tiene que asignar un tamaño a cada pantalla, como { "rooms": "400kB" }.',
68
+ badPackages: '"packages" tiene que ser una lista de nombres de paquete. Se ignora.',
69
+ forbiddenNotList: '"forbidden" tiene que ser una lista de reglas, como [{ "package": "moment", "why": "…" }].',
70
+ forbiddenWhat: where => `La regla de "forbidden" ${where} tiene que nombrar un "package" o un "path": uno de los dos.`,
71
+ forbiddenIn: (where, given) => `El "in" de la regla de "forbidden" ${where} tiene que ser "bootstrap" o "anywhere", no ${given}.`,
72
+ forbiddenNoWhy: where => `La regla de "forbidden" ${where} no tiene "why". Es lo primero que lee quien se la encuentra.`,
73
+ badBuild: '"build" tiene que ser un objeto, como { "entries": ["main.*.js"] }. Se ignora.',
74
+ badBuildList: key => `"build.${key}" tiene que ser una lista de nombres o rutas, como ["main.*.js"]. Se ignora.`,
75
+ badBuildScreens: '"build.screens" tiene que asignar a cada fichero "screen" o "piece", como { "*.widget.ts": "piece" }. Se ignora.',
76
+ badRouteKey: key => `"${key}" en "build.routeKeys" no es un nombre de propiedad, como "page". Se ignora.`,
77
+ badBuildScreen: pattern => `"build.screens" dice algo que no es "screen" ni "piece" para ${pattern}. Esa línea se ignora.`,
78
+ badBuildPage: '"build.page" tiene que ser el nombre de un HTML del build, como "app.html". Se ignora.',
79
+ notSize: (where, given) => `${where} tiene que ser un tamaño como "350kB" o "1.5MB", no ${given}.`,
80
+ bareSize: (where, given) => `${where} vale ${given}, que serían ${given} bytes. Escribe "${given}kB", o "${given}B" si son bytes.`,
81
+ notShare: (where, given) => `${where} tiene que ser una proporción como "25%" o 0.25, no ${given}.`,
82
+ notNumber: (where, given) => `${where} tiene que ser un número, no ${given}.`,
83
+ acceptedNotList: '"accepted" tiene que ser una lista. No se acepta nada de lo que lleva.',
84
+ unknownAccepted: kind => `Señal desconocida en "accepted": ${kind}. No acepta nada.`,
85
+ noWhy: where => `La aceptación de ${where} no tiene "why". Una aceptación sin motivo es un silencio.`,
86
+ bytesOf: where => `El "bytes" de ${where}`,
87
+ ignored: problem => `${problem} Se ignora.`,
88
+ badUntil: (where, until) => `El "until" de ${where} no es una fecha AAAA-MM-DD: ${until}. Se ignora.`,
89
+ },
90
+ };