@bymaksym/loadline 1.2.0 → 1.3.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 (45) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/cli/main.js +7 -4
  3. package/dist/cli/cli/read/locate.js +61 -0
  4. package/dist/cli/cli/read/read-build.js +7 -4
  5. package/dist/cli/cli/read/read-config.js +21 -3
  6. package/dist/cli/cli/render/render-json.js +1 -0
  7. package/dist/cli/cli/render/render-text.js +25 -1
  8. package/dist/cli/cli/report.js +10 -3
  9. package/dist/cli/cli/text/text-errors.js +14 -0
  10. package/dist/cli/cli/text/text.js +4 -0
  11. package/dist/cli/cli/text/usage.js +4 -4
  12. package/dist/cli/src/app/core/analysis/analysis.js +18 -4
  13. package/dist/cli/src/app/core/analysis/sourcemap/index-map.js +193 -0
  14. package/dist/cli/src/app/core/analysis/sourcemap/sourcemap.js +2 -1
  15. package/dist/cli/src/app/core/analysis/sourcemap/split-drift.js +39 -1
  16. package/dist/cli/src/app/core/assets/assets.js +35 -6
  17. package/dist/cli/src/app/core/caching/caching.js +1 -0
  18. package/dist/cli/src/app/core/deps/deps.js +68 -19
  19. package/dist/cli/src/app/core/export/summary.js +2 -1
  20. package/dist/cli/src/app/core/findings/actions.js +24 -3
  21. package/dist/cli/src/app/core/findings/bundle/dupes.js +22 -7
  22. package/dist/cli/src/app/core/findings/bundle/requests.js +1 -0
  23. package/dist/cli/src/app/core/findings/bundle/shipped.js +17 -2
  24. package/dist/cli/src/app/core/findings/effort.js +5 -5
  25. package/dist/cli/src/app/core/findings/folder/assets.js +13 -2
  26. package/dist/cli/src/app/core/findings/folder/caching.js +5 -5
  27. package/dist/cli/src/app/core/findings/folder/scan.js +2 -7
  28. package/dist/cli/src/app/core/findings/supplied/forbidden.js +1 -1
  29. package/dist/cli/src/app/core/findings/text/finding-html.js +25 -2
  30. package/dist/cli/src/app/core/findings/text/finding-text.js +88 -42
  31. package/dist/cli/src/app/core/findings/text/tool-advice.js +33 -1
  32. package/dist/cli/src/app/core/format/format.utils.js +14 -1
  33. package/dist/cli/src/app/core/i18n/en.js +57 -0
  34. package/dist/cli/src/app/core/i18n/es.js +57 -0
  35. package/dist/cli/src/app/core/intake/bundle-graph.js +2 -1
  36. package/dist/cli/src/app/core/intake/native-export.js +84 -0
  37. package/dist/cli/src/app/core/project/budget-advice.js +22 -1
  38. package/dist/cli/src/app/core/project/project-name.js +32 -4
  39. package/dist/cli/src/app/core/scan/scan.js +56 -8
  40. package/dist/cli/src/app/core/situation/situation.js +3 -3
  41. package/dist/cli/src/app/core/whatif/source-importers.js +2 -1
  42. package/docs/CONFIG.md +2 -1
  43. package/docs/HOW-IT-WORKS.md +90 -7
  44. package/loadline.html +23 -21
  45. package/package.json +38 -39
package/README.md CHANGED
@@ -152,7 +152,7 @@ summary. It runs the Loadline version it was released with, so pinning the Actio
152
152
  - uses: actions/setup-node@v7
153
153
  with: { node-version: 22 }
154
154
  - run: npm ci && npm run build
155
- - uses: bymaksym/LoadLine@v1.2.0
155
+ - uses: bymaksym/LoadLine@v1.3.0
156
156
  with:
157
157
  path: dist/my-app
158
158
  args: --max-boot 350kB # anything the command takes
@@ -60,7 +60,7 @@ const portableName = (target) => {
60
60
  */
61
61
  const codeOf = (error) => {
62
62
  if (error instanceof read_build_1.InputError) {
63
- return 'input';
63
+ return error.code;
64
64
  }
65
65
  return error instanceof Error && /^[A-Z][A-Z_]+$/.test(error.message) ? error.message : 'unexpected';
66
66
  };
@@ -122,7 +122,7 @@ const readInputs = async (options) => {
122
122
  // `--entry` adds to `build.entries`, for one run, what a file would say for every run.
123
123
  const said = configRead.config?.build;
124
124
  const build = options.entries.length > 0 ? { ...said, entries: [...(said?.entries ?? []), ...options.entries] } : said;
125
- const dist = folder ? await (0, read_build_1.readDist)(folder, derive, build) : NO_DIST;
125
+ const dist = folder ? await (0, read_build_1.readDist)(folder, { derive, hints: build }) : NO_DIST;
126
126
  const meta = dist.graph ? dist.graph.meta : await (0, read_build_1.readStats)(options.target, ui_1.UI[options.lang]);
127
127
  const deps = await (0, read_build_1.readDepsFiles)(options.lock, options.audit);
128
128
  const context = options.project ? await (0, read_build_1.readProject)(options.project) : { angular: null, pkg: null, pipelines: [] };
@@ -292,14 +292,17 @@ const run = async (argv, version) => {
292
292
  options = { ...options, target: located.target, dist: located.dist };
293
293
  // On stderr: which build was chosen is said, without getting into what a script parses.
294
294
  if (located.others) {
295
- write(process.stderr, text_1.CLI_TEXT[options.lang].alsoFound(located.others.join(', ')));
295
+ write(process.stderr, text_1.CLI_TEXT[options.lang].alsoFound(located.others.map(name => portableName(name)).join(', ')));
296
296
  }
297
297
  const input = await readInputs(options);
298
298
  // The gates the file asks for, where the command line did not ask for that one. A flag typed
299
299
  // by hand is somebody overriding the committed decision on purpose, so it wins.
300
300
  const gates = (0, gates_1.mergeGates)(options.gates, input.config ?? null);
301
301
  const report = (0, report_1.buildReport)(input, { ...options, gates });
302
- report.located = located.found;
302
+ // In the lead's terms — relative, with `/` — and without the one the lead already names: the
303
+ // same build printed twice, once as `../../Temp/…` and once as `C:\Users\…\browser`, read
304
+ // as two builds.
305
+ report.located = located.found.map(name => portableName(name)).filter(name => name !== report.statsName);
303
306
  const unchecked = (0, gates_1.uncheckedGates)(report, gates, options.gates);
304
307
  if (unchecked.refuse) {
305
308
  throw new read_build_1.InputError(unchecked.refuse);
@@ -15,7 +15,57 @@ const promises_1 = require("node:fs/promises");
15
15
  const node_path_1 = require("node:path");
16
16
  const index_html_1 = require("../../src/app/core/build-text/index-html");
17
17
  const dist_files_1 = require("../../src/app/core/intake/dist-files");
18
+ const native_export_1 = require("../../src/app/core/intake/native-export");
18
19
  const read_build_1 = require("./read-build");
20
+ /** The code `--format json` gives a native app, apart from `input`: a script can tell it from a typo. */
21
+ const NATIVE_APP = 'NATIVE_APP';
22
+ /**
23
+ * Whether a folder is a native Expo export (`native-export.ts`): its `metadata.json`, the bundles
24
+ * under `_expo/static/js/<platform>/` and any `.hbc` at its root. Three reads at most, nothing walked.
25
+ */
26
+ const nativeIn = async (folder) => {
27
+ const metadata = await (0, promises_1.readFile)((0, node_path_1.join)(folder, 'metadata.json'), 'utf8').catch(() => null);
28
+ const scripts = (0, node_path_1.join)(folder, '_expo', 'static', 'js');
29
+ const platforms = await (0, promises_1.readdir)(scripts).catch(() => []);
30
+ const paths = [];
31
+ for (const platform of platforms) {
32
+ const files = await (0, promises_1.readdir)((0, node_path_1.join)(scripts, platform)).catch(() => []);
33
+ paths.push(...files.map(file => `_expo/static/js/${platform}/${file}`));
34
+ }
35
+ const root = await (0, promises_1.readdir)(folder).catch(() => []);
36
+ paths.push(...root.filter(name => /\.hbc$/i.test(name)));
37
+ return (0, native_export_1.nativeExportOf)(paths, metadata);
38
+ };
39
+ /** The first bytes of a file, for its magic number. Empty when it cannot be read. */
40
+ const headOf = async (path) => {
41
+ const file = await (0, promises_1.open)(path, 'r').catch(() => null);
42
+ if (!file) {
43
+ return new Uint8Array();
44
+ }
45
+ try {
46
+ const head = new Uint8Array(8);
47
+ const { bytesRead } = await file.read(head, 0, head.length, 0);
48
+ return head.subarray(0, bytesRead);
49
+ }
50
+ finally {
51
+ await file.close();
52
+ }
53
+ };
54
+ /** Refuses a native Expo export, a Hermes bundle or an Expo project without a web build, by name. */
55
+ const refuseNative = async (target, dist) => {
56
+ if (await isFile(target)) {
57
+ if (/\.hbc$/i.test(target) || (0, native_export_1.isHermesBytecode)(await headOf(target))) {
58
+ throw new read_build_1.InputError(t => t.nativeApp(target, { kind: 'bundle', platforms: [], evidence: (0, node_path_1.basename)(target) }), NATIVE_APP);
59
+ }
60
+ return;
61
+ }
62
+ for (const folder of [target, dist]) {
63
+ const native = folder && (await isDirectory(folder)) ? await nativeIn(folder) : null;
64
+ if (folder && native) {
65
+ throw new read_build_1.InputError(t => t.nativeApp(folder, { kind: 'export', ...native }), NATIVE_APP);
66
+ }
67
+ }
68
+ };
19
69
  /**
20
70
  * The stats files' names that mark a folder as a build. Vue CLI's `report.json` is looked for only
21
71
  * inside the folder that was named: a name this plain is no sign of a build anywhere else.
@@ -162,6 +212,7 @@ const buildsUnder = async (project) => {
162
212
  * @param dist `--dist`, when it was given. Anything typed by hand wins: nothing is looked up then.
163
213
  */
164
214
  const locateBuild = async (target, dist) => {
215
+ await refuseNative(target, dist);
165
216
  // The page of the build named instead of its folder: what was meant is the folder it sits in,
166
217
  // and reading the HTML as a stats file answered "is not valid JSON".
167
218
  if (!dist && /\.html?$/i.test(target) && (await isFile(target))) {
@@ -205,6 +256,16 @@ const locateBuild = async (target, dist) => {
205
256
  ...(others.length > 0 && { others }),
206
257
  };
207
258
  }
259
+ // An Expo app has no web build to find unless it was exported for the web: its `dist/` is
260
+ // the native export, and the advice to "npm run build" named a script these apps do not have.
261
+ const exported = await nativeIn((0, node_path_1.join)(target, 'dist'));
262
+ if (exported) {
263
+ const shown = (0, node_path_1.join)(target, 'dist').replaceAll('\\', '/');
264
+ throw new read_build_1.InputError(t => t.nativeApp(shown, { kind: 'export', ...exported }), NATIVE_APP);
265
+ }
266
+ if ((0, native_export_1.isExpoPackage)(await (0, promises_1.readFile)((0, node_path_1.join)(target, 'package.json'), 'utf8').catch(() => null))) {
267
+ throw new read_build_1.InputError(t => t.nativeApp(target, { kind: 'project', platforms: [], evidence: 'package.json' }), NATIVE_APP);
268
+ }
208
269
  if (!(await isFile((0, node_path_1.join)(target, 'index.html'))) || (await isDirectory((0, node_path_1.join)(target, 'node_modules')))) {
209
270
  throw new read_build_1.InputError(t => t.projectNotBuilt(target));
210
271
  }
@@ -36,10 +36,13 @@ const text_errors_1 = require("../text/text-errors");
36
36
  */
37
37
  class InputError extends Error {
38
38
  say;
39
- constructor(say) {
39
+ /** The word `--format json` reports it under: `input`, unless the case has one of its own. */
40
+ code;
41
+ constructor(say, code = 'input') {
40
42
  const said = typeof say === 'string' ? () => say : say;
41
43
  super(said(text_errors_1.ERROR_TEXT.en));
42
44
  this.say = said;
45
+ this.code = code;
43
46
  }
44
47
  }
45
48
  exports.InputError = InputError;
@@ -137,10 +140,10 @@ const bundleFilesOf = (folder, paths) => Promise.all(paths.map(async (path) => {
137
140
  * The build folder. Names are cut down to their last segment, which is how the metafile names its
138
141
  * outputs and how the page keys the same figures.
139
142
  *
140
- * @param derive also read the import graph out of the chunks, for a build with no stats file. It
141
- * reads every source map on the way, so the maps are never parsed twice.
143
+ * @param options.derive also read the import graph out of the chunks, for a build with no stats
144
+ * file. It reads every source map on the way, so the maps are never parsed twice.
142
145
  */
143
- const readDist = async (folder, derive = false, hints = {}) => {
146
+ const readDist = async (folder, { derive = false, hints = {} } = {}) => {
144
147
  const paths = await filesUnder(folder);
145
148
  const gzip = new Map();
146
149
  const found = new Map();
@@ -93,12 +93,30 @@ const readFile = async (path, lang, shown) => {
93
93
  }
94
94
  return { config, problems };
95
95
  };
96
+ /**
97
+ * Where an unnamed `loadline.json` is looked for, in order: the working directory, then `.config/`
98
+ * in it. A repository that keeps its tool configurations together in `.config/` — this one does, and
99
+ * crowded-folders looks there too — had its file ignored without a word, and every gate in it was
100
+ * off. The root wins when both exist, because that is where the file has always been read from.
101
+ */
102
+ const UNNAMED = ['loadline.json', '.config/loadline.json'];
103
+ const unnamedPath = async (cwd) => {
104
+ for (const name of UNNAMED) {
105
+ const path = (0, node_path_1.resolve)(cwd, name);
106
+ if (await (0, read_build_1.exists)(path)) {
107
+ return path;
108
+ }
109
+ }
110
+ return null;
111
+ };
96
112
  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))) {
113
+ const path = given ? (0, node_path_1.resolve)(cwd, given) : await unnamedPath(cwd);
114
+ if (!path) {
99
115
  return { config: null, problems: [], name: null };
100
116
  }
101
- const shown = (file) => (0, node_path_1.relative)(cwd, file) || file;
117
+ // With `/` on every system: `.config\loadline.json` on Windows and `.config/loadline.json` on a
118
+ // runner are the same file, and the line naming it should not depend on who ran the command.
119
+ const shown = (file) => ((0, node_path_1.relative)(cwd, file) || file).replaceAll('\\', '/');
102
120
  // A file somebody pointed at by name is meant to be one; one that merely sits in the working
103
121
  // directory under that name may be somebody else's, and gets the warning.
104
122
  const { config, problems, gateProblems } = (0, loadline_config_1.readConfig)(await (0, read_build_1.readJson)(path), lang);
@@ -118,6 +118,7 @@ const renderJson = (report, violations, anyAsked) => {
118
118
  why: report.why,
119
119
  timing: (0, timing_1.timingsOf)(analysis.bootBytes + (report.pageCssBytes ?? 0), analysis.bootRawBytes, analysis.startup?.waves ?? 1, criteria.latencyMs),
120
120
  budget: advice,
121
+ budgetStanding: report.budgetStanding,
121
122
  caching: report.caching,
122
123
  scan: report.scan,
123
124
  // Without the declared ranges: they are an input the signals already read, not a finding.
@@ -255,6 +255,30 @@ const timeBlock = (report, palette) => {
255
255
  ], rows, palette),
256
256
  ];
257
257
  };
258
+ /**
259
+ * One line saying where the initial load stands against the budget `angular.json` sets, when the
260
+ * budget signals have nothing to say. Without it a project whose budgets were fine printed nothing,
261
+ * and "the budgets pass" could not be told from "the project was never read".
262
+ */
263
+ const standingLines = (report, palette) => {
264
+ const standing = report.budgetStanding;
265
+ const limit = standing ? (0, budget_advice_1.firstLimitOf)(standing) : null;
266
+ if (!standing || limit === null) {
267
+ return [];
268
+ }
269
+ const text = text_1.CLI_TEXT[report.lang];
270
+ // Apart, so 2,579 bytes against 3 kB does not read "3 kB of 3 kB".
271
+ const [current, bound] = (0, format_utils_1.formatBytesApart)(standing.current, limit);
272
+ const line = text.budgetStanding({
273
+ current,
274
+ limit: bound,
275
+ over: standing.current > limit,
276
+ warning: standing.warning !== null,
277
+ error: standing.warning === null || standing.error === null ? null : (0, format_utils_1.formatBytes)(standing.error),
278
+ config: standing.config,
279
+ });
280
+ return ['', ...(0, terminal_1.wrap)(line, terminal_1.WIDTH).map(row => (standing.current > limit ? palette.warn(row) : palette.dim(row)))];
281
+ };
258
282
  /**
259
283
  * The budget that should be in `angular.json`. Only with `--project`, because without it there is
260
284
  * nothing to say a budget is missing from, and the figure is raw bytes: that is what Angular counts.
@@ -267,7 +291,7 @@ const budgetBlock = (report, palette) => {
267
291
  const wanted = report.findings.some(finding => asking.has(finding.kind));
268
292
  const advice = wanted ? (0, budget_advice_1.budgetAdvice)(report.analysis.initialRawBytes) : null;
269
293
  if (!advice) {
270
- return [];
294
+ return standingLines(report, palette);
271
295
  }
272
296
  // The second budget, for a build that has screens: `anyScript` applies to every emitted file —
273
297
  // the bootstrap's too — which is what makes it useful when the names carry hashes and `bundle`
@@ -28,6 +28,7 @@ const forbidden_1 = require("../src/app/core/findings/supplied/forbidden");
28
28
  const situation_1 = require("../src/app/core/findings/supplied/situation");
29
29
  const format_utils_1 = require("../src/app/core/format/format.utils");
30
30
  const ui_1 = require("../src/app/core/i18n/ui");
31
+ const budget_advice_1 = require("../src/app/core/project/budget-advice");
31
32
  const project_name_1 = require("../src/app/core/project/project-name");
32
33
  const scan_2 = require("../src/app/core/scan/scan");
33
34
  const situation_2 = require("../src/app/core/situation/situation");
@@ -133,6 +134,7 @@ const buildReport = (input, options) => {
133
134
  modules: analysis.modules,
134
135
  boot: new Set(analysis.bootChunks),
135
136
  maps: input.maps ?? [],
137
+ generated: (0, scan_2.generatedOf)(analysis),
136
138
  })
137
139
  : null;
138
140
  const deps = (0, deps_1.readDeps)({
@@ -157,7 +159,11 @@ const buildReport = (input, options) => {
157
159
  ];
158
160
  const fromBuild = [
159
161
  ...(0, shipped_1.buildFolderFindings)({
160
- sourceMaps: input.splits?.size ?? 0,
162
+ // The map files in the folder, which is what the card about what they expose counts
163
+ // too: counted as chunks with a split, a stylesheet's map or one that did not parse
164
+ // dropped out, and two cards gave 43 and 44 for the same folder.
165
+ sourceMaps: (0, shipped_1.mapCount)(input.maps ?? [], input.splits?.size ?? 0),
166
+ unreadMaps: (0, shipped_1.unreadMapCount)(input.maps ?? [], chunk => !!input.splits?.has(chunk)),
161
167
  derived: !!input.graph,
162
168
  screens: analysis.screens.map(s => s.label),
163
169
  drift: analysis.splitDrift,
@@ -165,8 +171,8 @@ const buildReport = (input, options) => {
165
171
  }, lang),
166
172
  ...(input.assets ? (0, assets_2.buildAssetFindings)(input.assets, lang, criteria, input.assetSources ?? null, true) : []),
167
173
  ...(0, page_1.buildPageFindings)(input.pageOrigins ?? null, lang),
168
- ...(0, caching_1.buildCachingFindings)(caching, lang, criteria, situation, analysis.tool),
169
- ...(scan ? (0, scan_1.buildScanFindings)(scan, lang, criteria, (0, actions_1.unitScale)(analysis), analysis.tool) : []),
174
+ ...(0, caching_1.buildCachingFindings)(caching, lang, criteria, { situation, tool: analysis.tool }),
175
+ ...(scan ? (0, scan_1.buildScanFindings)(scan, lang, criteria, { scale: (0, actions_1.unitScale)(analysis), tool: analysis.tool }) : []),
170
176
  ...(0, deps_2.buildDepsFindings)(deps, lang, criteria, (0, actions_1.unitScale)(analysis)),
171
177
  ];
172
178
  const own = [...base, ...fromContext, ...fromBuild];
@@ -216,6 +222,7 @@ const buildReport = (input, options) => {
216
222
  // A folder build says which chunk holds what and not who imports whom; the sources in its
217
223
  // maps do, which is what lets `--why` answer for a Vite or Nuxt build at all.
218
224
  why: options.why.map(name => (0, why_1.explainWhy)(analysis, name, !input.graph, input.graph ? pkg => (0, source_importers_1.importersInSources)(input.maps ?? [], pkg) : null)),
225
+ budgetStanding: (0, budget_advice_1.budgetStanding)(input.context, analysis.initialRawBytes),
219
226
  projectName: (0, project_name_1.projectNameOf)({
220
227
  packageName: input.context.pkg?.name ?? input.packageName,
221
228
  angularProject: input.context.angular?.project,
@@ -42,6 +42,13 @@ const EN = {
42
42
  projectNotBuilt: folder => `${folder} is a project, not a build, and no build was found inside it: no folder holding an index.html with ` +
43
43
  'scripts, nor a stats.json. Build it the way you deploy it (npm run build) and run this again, or pass the ' +
44
44
  'output folder itself: dist/, build/, www/ or wherever your tool writes it.',
45
+ nativeApp: (path, d) => `${path} is ${d.kind === 'bundle'
46
+ ? 'Hermes bytecode: the bundle of a native app'
47
+ : d.kind === 'project'
48
+ ? 'an Expo app with no web build in it'
49
+ : `a native Expo export${d.platforms.length > 0 ? ` for ${d.platforms.join(' and ')}` : ''} (${d.evidence} says so)`}. Loadline weighs what a browser downloads for each screen, and does not analyse native apps: they ` +
50
+ 'arrive installed from the store. For what the native bundle holds, Expo Atlas breaks it down. For the web ' +
51
+ 'version of the app, export it with npx expo export --platform web and point Loadline at that folder.',
45
52
  notThresholds: path => `${path} has to be an object of thresholds.`,
46
53
  needsBrotli: by => `${by} needs the .js.br files of the build in --dist.`,
47
54
  needsDist: by => `${by} needs the build folder in --dist.`,
@@ -97,6 +104,13 @@ const ES = {
97
104
  projectNotBuilt: folder => `${folder} es un proyecto, no un build, y dentro no hay ningún build: ninguna carpeta con un index.html y ` +
98
105
  'scripts, ni un stats.json. Compílalo como lo despliegas (npm run build) y vuelve a lanzarlo, o pasa la ' +
99
106
  'carpeta de salida directamente: dist/, build/, www/ o donde la escriba tu herramienta.',
107
+ nativeApp: (path, d) => `${path} es ${d.kind === 'bundle'
108
+ ? 'bytecode de Hermes: el bundle de una app nativa'
109
+ : d.kind === 'project'
110
+ ? 'una app de Expo sin ningún build web dentro'
111
+ : `una exportación nativa de Expo${d.platforms.length > 0 ? ` para ${d.platforms.join(' y ')}` : ''} (lo dice ${d.evidence})`}. Loadline mide lo que descarga un navegador en cada pantalla y no analiza apps nativas: llegan ` +
112
+ 'instaladas desde la tienda. Para ver qué lleva el bundle nativo, Expo Atlas lo desglosa. Para la versión ' +
113
+ 'web de la app, expórtala con npx expo export --platform web y pasa a Loadline esa carpeta.',
100
114
  notThresholds: path => `${path} tiene que ser un objeto de umbrales.`,
101
115
  needsBrotli: by => `${by} necesita los ficheros .js.br del build en --dist.`,
102
116
  needsDist: by => `${by} necesita la carpeta del build en --dist.`,
@@ -30,6 +30,8 @@ const EN = {
30
30
  exportWritten: file => `This build's snapshot, to be the --baseline of a later run: ${file}`,
31
31
  htmlInsideBuild: folder => `It is inside ${folder}, which the next build empties: write it somewhere else to keep it.`,
32
32
  located: files => `found ${files}`,
33
+ budgetStanding: d => `Budgets: ${d.current} of ${d.limit}${d.over ? ', over it' : ''} — the initial ${d.warning ? 'warning' : 'error'} ` +
34
+ `of ${d.config} in angular.json${d.error ? `, with the error at ${d.error}` : ''}.`,
33
35
  alsoFound: folders => `the newest build was read; also found ${folders}: pass one of them to read it instead`,
34
36
  lastRunUnchanged: 'nothing moved',
35
37
  tripFonts: 'fonts',
@@ -188,6 +190,8 @@ const ES = {
188
190
  exportWritten: file => `La foto de este build, para ser la --baseline de otra ejecución: ${file}`,
189
191
  htmlInsideBuild: folder => `Está dentro de ${folder}, que el siguiente build vacía: guárdala en otro sitio para conservarla.`,
190
192
  located: files => `encontrado ${files}`,
193
+ budgetStanding: d => `Presupuestos: ${d.current} de ${d.limit}${d.over ? ', por encima' : ''} — el ${d.warning ? 'aviso' : 'error'} ` +
194
+ `inicial de ${d.config} en angular.json${d.error ? `, con el error en ${d.error}` : ''}.`,
191
195
  alsoFound: folders => `se ha leído el build más reciente; también hay ${folders}: pasa uno de ellos para leerlo`,
192
196
  lastRunUnchanged: 'no se ha movido nada',
193
197
  tripFonts: 'de tipografías',
@@ -45,8 +45,8 @@ Reading the build
45
45
  writes this file with its "Download criteria" button.
46
46
  --config <file.json> loadline.json: the thresholds, the gates and the signals the team has
47
47
  decided to live with, kept next to the code. Without the flag, a
48
- loadline.json in the working directory is read if there is one. Flags on
49
- the command line win over the file.
48
+ loadline.json in the working directory, or else in its .config/, is
49
+ read if there is one. Flags on the command line win over the file.
50
50
  --print-config Print that loadline.json with everything it "extends" joined in, and
51
51
  stop: which threshold won, without reading three files. Needs no build.
52
52
  The page cannot follow "extends"; drop what this prints on it instead.
@@ -160,8 +160,8 @@ Leer el build
160
160
  página escribe este fichero con su botón "Descargar criterios".
161
161
  --config <fichero.json> loadline.json: los umbrales, los gates y las señales que el equipo ha
162
162
  decidido aceptar, junto al código. Sin la opción, se lee el
163
- loadline.json del directorio de trabajo si lo hay. Las opciones de la
164
- línea de comandos ganan al fichero.
163
+ loadline.json del directorio de trabajo, o si no el de su .config/, si
164
+ lo hay. Las opciones de la línea de comandos ganan al fichero.
165
165
  --print-config Muestra ese loadline.json con todo lo que hereda con "extends" ya
166
166
  unido, y para: qué umbral ha ganado, sin leer tres ficheros. No necesita
167
167
  build. La página no puede seguir "extends"; suéltale lo que esto escribe.
@@ -105,6 +105,9 @@ const analyze = (meta, gzip, exact = null, announced = null, marks = null, limit
105
105
  const isOwn = (input) => (0, ownership_1.isOwnFile)(input);
106
106
  /** Source-graph edges that keep files in the same chunk: anything but a lazy boundary or an external. */
107
107
  const travelsTogether = (imp) => !imp.external && imp.kind !== 'dynamic-import';
108
+ // A chunk whose parts do not add up to it has them scaled to it: see `chunkScalesOf`.
109
+ const scales = (0, split_drift_1.chunkScalesOf)(outputs, exact);
110
+ const scaled = (chunk, bytes) => Math.round(bytes * (scales.get(chunk) ?? 1));
108
111
  /**
109
112
  * How many bytes of a file are inside a chunk. The metafile's figure is already the minified
110
113
  * one; the source map of that chunk, when the folder brought it, is preferred simply because
@@ -112,7 +115,9 @@ const analyze = (meta, gzip, exact = null, announced = null, marks = null, limit
112
115
  */
113
116
  const bytesIn = (chunk, input) => {
114
117
  const measured = exact?.get((0, format_utils_1.baseName)(chunk))?.get(input);
115
- return typeof measured === 'number' ? measured : (outputs[chunk]?.inputs?.[input]?.bytesInOutput ?? 0);
118
+ return typeof measured === 'number'
119
+ ? measured
120
+ : scaled(chunk, outputs[chunk]?.inputs?.[input]?.bytesInOutput ?? 0);
116
121
  };
117
122
  /**
118
123
  * The same figure, with "nobody measured this chunk" told apart from "it weighs nothing". A
@@ -125,7 +130,7 @@ const analyze = (meta, gzip, exact = null, announced = null, marks = null, limit
125
130
  return measured.get(input) ?? 0;
126
131
  }
127
132
  const inside = outputs[chunk]?.inputs;
128
- return inside ? (inside[input]?.bytesInOutput ?? 0) : null;
133
+ return inside ? scaled(chunk, inside[input]?.bytesInOutput ?? 0) : null;
129
134
  };
130
135
  /** Files of a chunk with their bytes, skipping the empty ones. */
131
136
  const inputsOf = (chunk) => Object.keys(outputs[chunk]?.inputs ?? {})
@@ -413,20 +418,28 @@ const analyze = (meta, gzip, exact = null, announced = null, marks = null, limit
413
418
  * question asked of a file that is only inside one screen.
414
419
  */
415
420
  const cameFrom = new Map();
421
+ // The files that walk reached through an `import()` rather than a static import. A chain that
422
+ // crosses one is not "in the bootstrap" past that step: `teams.service.ts` loading
423
+ // `@microsoft/teams-js` with `await import` read as `main.ts › … › teams.service.ts ›
424
+ // @microsoft/teams-js`, exactly like a package everybody downloads first.
425
+ const reachedLazily = new Set();
416
426
  if (mainSource && inputs[mainSource]) {
417
427
  cameFrom.set(mainSource, null);
418
428
  const pending = [mainSource];
419
- const visit = (from, path) => {
429
+ const visit = (from, path, lazy) => {
420
430
  if (cameFrom.has(path)) {
421
431
  return;
422
432
  }
423
433
  cameFrom.set(path, from);
434
+ if (lazy) {
435
+ reachedLazily.add(path);
436
+ }
424
437
  pending.push(path);
425
438
  };
426
439
  for (const file of pending) {
427
440
  const imports = (inputs[file]?.imports ?? []).filter(imp => !imp.external);
428
441
  for (const imp of imports) {
429
- visit(file, imp.path);
442
+ visit(file, imp.path, !travelsTogether(imp));
430
443
  }
431
444
  }
432
445
  }
@@ -686,6 +699,7 @@ const analyze = (meta, gzip, exact = null, announced = null, marks = null, limit
686
699
  ownFilesInBoot,
687
700
  modules,
688
701
  chainTo,
702
+ lazyStep: path => reachedLazily.has(path),
689
703
  // From the maps only when a map covers something the application reaches. Polymer ships maps
690
704
  // for its polyfill bundles alone, and the report opened with "weight per file read from the
691
705
  // source maps" right above "no source maps in this folder".
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ /**
3
+ * The index map of the source map specification — `{ "version": 3, "sections": [...] }` — joined into
4
+ * the regular map every reader here understands.
5
+ *
6
+ * Metro writes it: an Expo app exported as JavaScript came with a 4.3 MB bundle and a 16 MB map in
7
+ * 2,290 sections, one per module, with no `sources` or `mappings` at its root. Every reader asked for
8
+ * those two fields, found neither, dropped the map without a word and reported "this folder carries
9
+ * no source maps". It is in the specification, so any tool may write it, not only Metro.
10
+ *
11
+ * Joining is done once, where the JSON is parsed, so the readers downstream — the split per file,
12
+ * the attribution of a `console.log`, the exposure of the sources, the graph of a folder — need no
13
+ * second path. Each section's mappings are decoded to absolute positions, moved by the section's
14
+ * offset (its first line by the column too, the rest by the line alone, as the specification says)
15
+ * and encoded again against one list of sources. Names are left out: nothing here reads them.
16
+ *
17
+ * A section that points at another file (`url`) instead of carrying its map is not followed — there
18
+ * is no fetching here — and a map made only of those is not readable; `isReadableMap` says so, which
19
+ * is what lets the report say "there is a map in a format this does not read" instead of "none".
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.isReadableMap = exports.parseSourceMap = exports.asPlainMap = exports.isIndexMap = void 0;
23
+ const VLQ_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
24
+ const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
25
+ /** An offset's line or column: a number, or `0` where the section left it out. */
26
+ const offsetOf = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : 0);
27
+ /** Base64 VLQ, the same reading `sourcemap.ts` does, for every field of every segment of a line. */
28
+ const decodeFields = (segment) => {
29
+ const values = [];
30
+ let value = 0;
31
+ let shift = 0;
32
+ for (const char of segment) {
33
+ const digit = VLQ_CHARS.indexOf(char);
34
+ if (digit === -1) {
35
+ return values;
36
+ }
37
+ value += (digit % 32) * 2 ** shift;
38
+ if (digit >= 32) {
39
+ shift += 5;
40
+ continue;
41
+ }
42
+ values.push(value % 2 === 1 ? -Math.floor(value / 2) : Math.floor(value / 2));
43
+ value = 0;
44
+ shift = 0;
45
+ }
46
+ return values;
47
+ };
48
+ const encode = (value) => {
49
+ let rest = value < 0 ? -value * 2 + 1 : value * 2;
50
+ let out = '';
51
+ do {
52
+ const digit = rest % 32;
53
+ rest = Math.floor(rest / 32);
54
+ out += VLQ_CHARS[digit + (rest > 0 ? 32 : 0)] ?? '';
55
+ } while (rest > 0);
56
+ return out;
57
+ };
58
+ /** A section's mappings as absolute segments per line: the relative fields carried along. */
59
+ const decodeAbsolute = (mappings) => {
60
+ const lines = [];
61
+ let source = 0;
62
+ let sourceLine = 0;
63
+ let sourceColumn = 0;
64
+ for (const line of mappings.split(';')) {
65
+ const segments = [];
66
+ let column = 0;
67
+ const written = line ? line.split(',') : [];
68
+ for (const segment of written) {
69
+ const fields = decodeFields(segment);
70
+ column += fields[0] ?? 0;
71
+ if (fields.length >= 4) {
72
+ source += fields[1] ?? 0;
73
+ sourceLine += fields[2] ?? 0;
74
+ sourceColumn += fields[3] ?? 0;
75
+ segments.push([column, source, sourceLine, sourceColumn]);
76
+ }
77
+ else {
78
+ segments.push([column]);
79
+ }
80
+ }
81
+ lines.push(segments);
82
+ }
83
+ return lines;
84
+ };
85
+ /** The regular map an index map stands for, or `null` when no section carries a map of its own. */
86
+ const joinSections = (sections) => {
87
+ const sources = [];
88
+ const contents = [];
89
+ const indexOf = new Map();
90
+ const output = [];
91
+ let joined = 0;
92
+ const ordered = sections
93
+ .map(section => record(section))
94
+ .filter((section) => section !== null)
95
+ .map(section => ({
96
+ line: offsetOf(record(section['offset'])?.['line']),
97
+ column: offsetOf(record(section['offset'])?.['column']),
98
+ map: record(section['map']),
99
+ }))
100
+ .toSorted((a, b) => a.line - b.line || a.column - b.column);
101
+ for (const { line, column, map } of ordered) {
102
+ const own = map ? map['sources'] : null;
103
+ const mappings = map ? map['mappings'] : null;
104
+ // A nested index map is forbidden by the specification, and a `url` section is not fetched.
105
+ if (!map || !Array.isArray(own) || typeof mappings !== 'string') {
106
+ continue;
107
+ }
108
+ joined += 1;
109
+ const ownContents = Array.isArray(map['sourcesContent']) ? map['sourcesContent'] : [];
110
+ const global = own.map((source, index) => {
111
+ const name = typeof source === 'string' ? source : '';
112
+ const known = indexOf.get(name);
113
+ if (known !== undefined) {
114
+ return known;
115
+ }
116
+ indexOf.set(name, sources.length);
117
+ sources.push(name);
118
+ const content = ownContents[index];
119
+ contents.push(typeof content === 'string' ? content : null);
120
+ return sources.length - 1;
121
+ });
122
+ for (const [offset, segments] of decodeAbsolute(mappings).entries()) {
123
+ const at = line + offset;
124
+ const shift = offset === 0 ? column : 0;
125
+ while (output.length <= at) {
126
+ output.push([]);
127
+ }
128
+ const row = output[at] ?? [];
129
+ for (const segment of segments) {
130
+ row.push(segment.length === 4
131
+ ? [segment[0] + shift, global[segment[1]] ?? 0, segment[2], segment[3]]
132
+ : [segment[0] + shift]);
133
+ }
134
+ }
135
+ }
136
+ if (joined === 0) {
137
+ return null;
138
+ }
139
+ // Encoded again, relative as the format wants: the column within its line, the rest across the map.
140
+ let source = 0;
141
+ let sourceLine = 0;
142
+ let sourceColumn = 0;
143
+ const encoded = output.map(row => {
144
+ let column = 0;
145
+ return row
146
+ .map(segment => {
147
+ const head = encode(segment[0] - column);
148
+ column = segment[0];
149
+ if (segment.length === 1) {
150
+ return head;
151
+ }
152
+ const tail = encode(segment[1] - source) + encode(segment[2] - sourceLine) + encode(segment[3] - sourceColumn);
153
+ [, source, sourceLine, sourceColumn] = segment;
154
+ return head + tail;
155
+ })
156
+ .join(',');
157
+ });
158
+ return { version: 3, sources, sourcesContent: contents, names: [], mappings: encoded.join(';') };
159
+ };
160
+ /** Whether a parsed map is an index map: `sections` and no `mappings` of its own. */
161
+ const isIndexMap = (value) => {
162
+ const map = record(value);
163
+ return !!map && Array.isArray(map['sections']) && typeof map['mappings'] !== 'string';
164
+ };
165
+ exports.isIndexMap = isIndexMap;
166
+ /**
167
+ * A parsed source map as every reader here expects one: an index map joined into a regular map,
168
+ * anything else as it came. What cannot be joined comes back as it came, and reads as no map.
169
+ */
170
+ const asPlainMap = (value) => {
171
+ const map = record(value);
172
+ const sections = map?.['sections'];
173
+ return (0, exports.isIndexMap)(value) && Array.isArray(sections) ? (joinSections(sections) ?? value) : value;
174
+ };
175
+ exports.asPlainMap = asPlainMap;
176
+ /** `JSON.parse` of a map's text, index maps joined. Throws as `JSON.parse` does on what is not JSON. */
177
+ const parseSourceMap = (text) => (0, exports.asPlainMap)(JSON.parse(text));
178
+ exports.parseSourceMap = parseSourceMap;
179
+ /**
180
+ * Whether a map's text is one this tool reads: JSON with `sources` and `mappings`, once an index map
181
+ * is joined. `false` for an index map made only of `url` sections, a map of another shape, or text
182
+ * that is not JSON — the cases the report has to name as "a map it does not read".
183
+ */
184
+ const isReadableMap = (text) => {
185
+ try {
186
+ const map = record((0, exports.parseSourceMap)(text));
187
+ return !!map && Array.isArray(map['sources']) && typeof map['mappings'] === 'string';
188
+ }
189
+ catch {
190
+ return false;
191
+ }
192
+ };
193
+ exports.isReadableMap = isReadableMap;
@@ -19,6 +19,7 @@
19
19
  */
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.resolveSplits = exports.readSourceMaps = exports.resolveSources = exports.sourcePathOf = exports.projectRootsOf = exports.projectRootOf = exports.bytesBySource = exports.sourceAt = exports.segmentsOf = exports.isSourceMap = exports.isScriptMapName = void 0;
22
+ const index_map_1 = require("./index-map");
22
23
  const VLQ_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
23
24
  /**
24
25
  * Whether a file name is the source map of a script. Not only `*.js.map`: ember-cli hashes each map
@@ -284,7 +285,7 @@ const readSourceMaps = async (files) => {
284
285
  continue;
285
286
  }
286
287
  try {
287
- const parsed = JSON.parse(await file.text());
288
+ const parsed = (0, index_map_1.parseSourceMap)(await file.text());
288
289
  if (!(0, exports.isSourceMap)(parsed)) {
289
290
  continue;
290
291
  }