-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathstats.ts
583 lines (497 loc) · 17 KB
/
stats.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { WebpackLoggingCallback } from '@angular-devkit/build-webpack';
import { logging, tags } from '@angular-devkit/core';
import assert from 'node:assert';
import * as path from 'node:path';
import { Configuration, StatsCompilation } from 'webpack';
import { Schema as BrowserBuilderOptions } from '../../../builders/browser/schema';
import { normalizeOptimization } from '../../../utils';
import { BudgetCalculatorResult } from '../../../utils/bundle-calculator';
import { colors as ansiColors, removeColor } from '../../../utils/color';
import { markAsyncChunksNonInitial } from './async-chunks';
import { WebpackStatsOptions, getStatsOptions, normalizeExtraEntryPoints } from './helpers';
export function formatSize(size: number): string {
if (size <= 0) {
return '0 bytes';
}
const abbreviations = ['bytes', 'kB', 'MB', 'GB'];
const index = Math.floor(Math.log(size) / Math.log(1024));
const roundedSize = size / Math.pow(1024, index);
// bytes don't have a fraction
const fractionDigits = index === 0 ? 0 : 2;
return `${roundedSize.toFixed(fractionDigits)} ${abbreviations[index]}`;
}
export type BundleStatsData = [
files: string,
names: string,
rawSize: number | string,
estimatedTransferSize: number | string,
];
export interface BundleStats {
initial: boolean;
stats: BundleStatsData;
}
function getBuildDuration(webpackStats: StatsCompilation): number {
assert(webpackStats.builtAt, 'buildAt cannot be undefined');
assert(webpackStats.time, 'time cannot be undefined');
return Date.now() - webpackStats.builtAt + webpackStats.time;
}
function generateBundleStats(info: {
rawSize?: number;
estimatedTransferSize?: number;
files?: string[];
names?: string[];
initial?: boolean;
rendered?: boolean;
}): BundleStats {
const rawSize = typeof info.rawSize === 'number' ? info.rawSize : '-';
const estimatedTransferSize =
typeof info.estimatedTransferSize === 'number' ? info.estimatedTransferSize : '-';
const files =
info.files
?.filter((f) => !f.endsWith('.map'))
.map((f) => path.basename(f))
.join(', ') ?? '';
const names = info.names?.length ? info.names.join(', ') : '-';
const initial = !!info.initial;
return {
initial,
stats: [files, names, rawSize, estimatedTransferSize],
};
}
export function generateBuildStatsTable(
data: BundleStats[],
colors: boolean,
showTotalSize: boolean,
showEstimatedTransferSize: boolean,
budgetFailures?: BudgetCalculatorResult[],
): string {
const g = (x: string) => (colors ? ansiColors.greenBright(x) : x);
const c = (x: string) => (colors ? ansiColors.cyanBright(x) : x);
const r = (x: string) => (colors ? ansiColors.redBright(x) : x);
const y = (x: string) => (colors ? ansiColors.yellowBright(x) : x);
const bold = (x: string) => (colors ? ansiColors.bold(x) : x);
const getSizeColor = (name: string, file?: string, defaultColor = c) => {
const severity = budgets.get(name) || (file && budgets.get(file));
switch (severity) {
case 'warning':
return y;
case 'error':
return r;
default:
return defaultColor;
}
};
const changedEntryChunksStats: BundleStatsData[] = [];
const changedLazyChunksStats: BundleStatsData[] = [];
let initialTotalRawSize = 0;
let initialTotalEstimatedTransferSize;
const budgets = new Map<string, string>();
if (budgetFailures) {
for (const { label, severity } of budgetFailures) {
// In some cases a file can have multiple budget failures.
// Favor error.
if (label && (!budgets.has(label) || budgets.get(label) === 'warning')) {
budgets.set(label, severity);
}
}
}
// Sort descending by raw size
data.sort((a, b) => {
if (a.stats[2] > b.stats[2]) {
return -1;
}
if (a.stats[2] < b.stats[2]) {
return 1;
}
return 0;
});
for (const { initial, stats } of data) {
const [files, names, rawSize, estimatedTransferSize] = stats;
const getRawSizeColor = getSizeColor(names, files);
let data: BundleStatsData;
if (showEstimatedTransferSize) {
data = [
g(files),
names,
getRawSizeColor(typeof rawSize === 'number' ? formatSize(rawSize) : rawSize),
c(
typeof estimatedTransferSize === 'number'
? formatSize(estimatedTransferSize)
: estimatedTransferSize,
),
];
} else {
data = [
g(files),
names,
getRawSizeColor(typeof rawSize === 'number' ? formatSize(rawSize) : rawSize),
'',
];
}
if (initial) {
changedEntryChunksStats.push(data);
if (typeof rawSize === 'number') {
initialTotalRawSize += rawSize;
}
if (showEstimatedTransferSize && typeof estimatedTransferSize === 'number') {
if (initialTotalEstimatedTransferSize === undefined) {
initialTotalEstimatedTransferSize = 0;
}
initialTotalEstimatedTransferSize += estimatedTransferSize;
}
} else {
changedLazyChunksStats.push(data);
}
}
const bundleInfo: (string | number)[][] = [];
const baseTitles = ['Names', 'Raw Size'];
const tableAlign: ('l' | 'r')[] = ['l', 'l', 'r'];
if (showEstimatedTransferSize) {
baseTitles.push('Estimated Transfer Size');
tableAlign.push('r');
}
// Entry chunks
if (changedEntryChunksStats.length) {
bundleInfo.push(['Initial Chunk Files', ...baseTitles].map(bold), ...changedEntryChunksStats);
if (showTotalSize) {
bundleInfo.push([]);
const initialSizeTotalColor = getSizeColor('bundle initial', undefined, (x) => x);
const totalSizeElements = [
' ',
'Initial Total',
initialSizeTotalColor(formatSize(initialTotalRawSize)),
];
if (showEstimatedTransferSize) {
totalSizeElements.push(
typeof initialTotalEstimatedTransferSize === 'number'
? formatSize(initialTotalEstimatedTransferSize)
: '-',
);
}
bundleInfo.push(totalSizeElements.map(bold));
}
}
// Seperator
if (changedEntryChunksStats.length && changedLazyChunksStats.length) {
bundleInfo.push([]);
}
// Lazy chunks
if (changedLazyChunksStats.length) {
bundleInfo.push(['Lazy Chunk Files', ...baseTitles].map(bold), ...changedLazyChunksStats);
}
return generateTableText(bundleInfo, colors);
}
function generateTableText(bundleInfo: (string | number)[][], colors: boolean): string {
const longest: number[] = [];
for (const item of bundleInfo) {
for (let i = 0; i < item.length; i++) {
if (item[i] === undefined) {
continue;
}
const currentItem = item[i].toString();
const currentLongest = (longest[i] ??= 0);
const currentItemLength = removeColor(currentItem).length;
if (currentLongest < currentItemLength) {
longest[i] = currentItemLength;
}
}
}
const seperator = colors ? ansiColors.dim(' | ') : ' | ';
const outputTable: string[] = [];
for (const item of bundleInfo) {
for (let i = 0; i < longest.length; i++) {
if (item[i] === undefined) {
continue;
}
const currentItem = item[i].toString();
const currentItemLength = removeColor(currentItem).length;
const stringPad = ' '.repeat(longest[i] - currentItemLength);
// Last item is right aligned, thus we add the padding at the start.
item[i] = longest.length === i + 1 ? stringPad + currentItem : currentItem + stringPad;
}
outputTable.push(item.join(seperator));
}
return outputTable.join('\n');
}
function generateBuildStats(hash: string, time: number, colors: boolean): string {
const w = (x: string) => (colors ? ansiColors.bold.white(x) : x);
return `Build at: ${w(new Date().toISOString())} - Hash: ${w(hash)} - Time: ${w('' + time)}ms`;
}
// We use this cache because we can have multiple builders running in the same process,
// where each builder has different output path.
// Ideally, we should create the logging callback as a factory, but that would need a refactoring.
const runsCache = new Set<string>();
function statsToString(
json: StatsCompilation,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
statsConfig: any,
budgetFailures?: BudgetCalculatorResult[],
): string {
if (!json.chunks?.length) {
return '';
}
const colors = statsConfig.colors;
const rs = (x: string) => (colors ? ansiColors.reset(x) : x);
const changedChunksStats: BundleStats[] = [];
let unchangedChunkNumber = 0;
let hasEstimatedTransferSizes = false;
const isFirstRun = !runsCache.has(json.outputPath || '');
for (const chunk of json.chunks) {
// During first build we want to display unchanged chunks
// but unchanged cached chunks are always marked as not rendered.
if (!isFirstRun && !chunk.rendered) {
continue;
}
const assets = json.assets?.filter((asset) => chunk.files?.includes(asset.name));
let rawSize = 0;
let estimatedTransferSize;
if (assets) {
for (const asset of assets) {
if (asset.name.endsWith('.map')) {
continue;
}
rawSize += asset.size;
if (typeof asset.info.estimatedTransferSize === 'number') {
if (estimatedTransferSize === undefined) {
estimatedTransferSize = 0;
hasEstimatedTransferSizes = true;
}
estimatedTransferSize += asset.info.estimatedTransferSize;
}
}
}
changedChunksStats.push(generateBundleStats({ ...chunk, rawSize, estimatedTransferSize }));
}
unchangedChunkNumber = json.chunks.length - changedChunksStats.length;
runsCache.add(json.outputPath || '');
const statsTable = generateBuildStatsTable(
changedChunksStats,
colors,
unchangedChunkNumber === 0,
hasEstimatedTransferSizes,
budgetFailures,
);
// In some cases we do things outside of webpack context
// Such us index generation, service worker augmentation etc...
// This will correct the time and include these.
const time = getBuildDuration(json);
if (unchangedChunkNumber > 0) {
return (
'\n' +
rs(tags.stripIndents`
${statsTable}
${unchangedChunkNumber} unchanged chunks
${generateBuildStats(json.hash || '', time, colors)}
`)
);
} else {
return (
'\n' +
rs(tags.stripIndents`
${statsTable}
${generateBuildStats(json.hash || '', time, colors)}
`)
);
}
}
export function statsWarningsToString(
json: StatsCompilation,
statsConfig: WebpackStatsOptions,
): string {
const colors = statsConfig.colors;
const c = (x: string) => (colors ? ansiColors.reset.cyan(x) : x);
const y = (x: string) => (colors ? ansiColors.reset.yellow(x) : x);
const yb = (x: string) => (colors ? ansiColors.reset.yellowBright(x) : x);
const warnings = json.warnings ? [...json.warnings] : [];
if (json.children) {
warnings.push(...json.children.map((c) => c.warnings ?? []).reduce((a, b) => [...a, ...b], []));
}
let output = '';
for (const warning of warnings) {
if (typeof warning === 'string') {
output += yb(`Warning: ${warning}\n\n`);
} else {
let file = warning.file || warning.moduleName;
// Clean up warning paths
// Ex: ./src/app/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js....
// to ./src/app/styles.scss.webpack
if (file && !statsConfig.errorDetails) {
const webpackPathIndex = file.indexOf('.webpack[');
if (webpackPathIndex !== -1) {
file = file.substring(0, webpackPathIndex);
}
}
if (file) {
output += c(file);
if (warning.loc) {
output += ':' + yb(warning.loc);
}
output += ' - ';
}
if (!/^warning/i.test(warning.message)) {
output += y('Warning: ');
}
output += `${warning.message}\n\n`;
}
}
return output ? '\n' + output : output;
}
export function statsErrorsToString(
json: StatsCompilation,
statsConfig: WebpackStatsOptions,
): string {
const colors = statsConfig.colors;
const c = (x: string) => (colors ? ansiColors.reset.cyan(x) : x);
const yb = (x: string) => (colors ? ansiColors.reset.yellowBright(x) : x);
const r = (x: string) => (colors ? ansiColors.reset.redBright(x) : x);
const errors = json.errors ? [...json.errors] : [];
if (json.children) {
errors.push(...json.children.map((c) => c?.errors || []).reduce((a, b) => [...a, ...b], []));
}
let output = '';
for (const error of errors) {
if (typeof error === 'string') {
output += r(`Error: ${error}\n\n`);
} else {
let file = error.file || error.moduleName;
// Clean up error paths
// Ex: ./src/app/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js....
// to ./src/app/styles.scss.webpack
if (file && !statsConfig.errorDetails) {
const webpackPathIndex = file.indexOf('.webpack[');
if (webpackPathIndex !== -1) {
file = file.substring(0, webpackPathIndex);
}
}
if (file) {
output += c(file);
if (error.loc) {
output += ':' + yb(error.loc);
}
output += ' - ';
}
// In most cases webpack will add stack traces to error messages.
// This below cleans up the error from stacks.
// See: https://github.com/webpack/webpack/issues/15980
const index = error.message.search(/[\n\s]+at /);
const message =
statsConfig.errorStack || index === -1 ? error.message : error.message.substring(0, index);
if (!/^error/i.test(message)) {
output += r('Error: ');
}
output += `${message}\n\n`;
}
}
return output ? '\n' + output : output;
}
export function statsHasErrors(json: StatsCompilation): boolean {
return !!(json.errors?.length || json.children?.some((c) => c.errors?.length));
}
export function statsHasWarnings(json: StatsCompilation): boolean {
return !!(json.warnings?.length || json.children?.some((c) => c.warnings?.length));
}
export function createWebpackLoggingCallback(
options: BrowserBuilderOptions,
logger: logging.LoggerApi,
): WebpackLoggingCallback {
const { verbose = false, scripts = [], styles = [] } = options;
const extraEntryPoints = [
...normalizeExtraEntryPoints(styles, 'styles'),
...normalizeExtraEntryPoints(scripts, 'scripts'),
];
return (stats, config) => {
if (verbose) {
logger.info(stats.toString(config.stats));
}
const rawStats = stats.toJson(getStatsOptions(false));
const webpackStats = {
...rawStats,
chunks: markAsyncChunksNonInitial(rawStats, extraEntryPoints),
};
webpackStatsLogger(logger, webpackStats, config);
};
}
export interface BuildEventStats {
aot: boolean;
optimization: boolean;
allChunksCount: number;
lazyChunksCount: number;
initialChunksCount: number;
changedChunksCount?: number;
durationInMs: number;
cssSizeInBytes: number;
jsSizeInBytes: number;
ngComponentCount: number;
}
export function generateBuildEventStats(
webpackStats: StatsCompilation,
browserBuilderOptions: BrowserBuilderOptions,
): BuildEventStats {
const { chunks = [], assets = [] } = webpackStats;
let jsSizeInBytes = 0;
let cssSizeInBytes = 0;
let initialChunksCount = 0;
let ngComponentCount = 0;
let changedChunksCount = 0;
const allChunksCount = chunks.length;
const isFirstRun = !runsCache.has(webpackStats.outputPath || '');
const chunkFiles = new Set<string>();
for (const chunk of chunks) {
if (!isFirstRun && chunk.rendered) {
changedChunksCount++;
}
if (chunk.initial) {
initialChunksCount++;
}
for (const file of chunk.files ?? []) {
chunkFiles.add(file);
}
}
for (const asset of assets) {
if (asset.name.endsWith('.map') || !chunkFiles.has(asset.name)) {
continue;
}
if (asset.name.endsWith('.js')) {
jsSizeInBytes += asset.size;
ngComponentCount += asset.info.ngComponentCount ?? 0;
} else if (asset.name.endsWith('.css')) {
cssSizeInBytes += asset.size;
}
}
return {
optimization: !!normalizeOptimization(browserBuilderOptions.optimization).scripts,
aot: browserBuilderOptions.aot !== false,
allChunksCount,
lazyChunksCount: allChunksCount - initialChunksCount,
initialChunksCount,
changedChunksCount,
durationInMs: getBuildDuration(webpackStats),
cssSizeInBytes,
jsSizeInBytes,
ngComponentCount,
};
}
export function webpackStatsLogger(
logger: logging.LoggerApi,
json: StatsCompilation,
config: Configuration,
budgetFailures?: BudgetCalculatorResult[],
): void {
logger.info(statsToString(json, config.stats, budgetFailures));
if (typeof config.stats !== 'object') {
throw new Error('Invalid Webpack stats configuration.');
}
if (statsHasWarnings(json)) {
logger.warn(statsWarningsToString(json, config.stats));
}
if (statsHasErrors(json)) {
logger.error(statsErrorsToString(json, config.stats));
}
}