-
-
Notifications
You must be signed in to change notification settings - Fork 503
Expand file tree
/
Copy pathanalyzer.js
More file actions
442 lines (387 loc) · 14.5 KB
/
analyzer.js
File metadata and controls
442 lines (387 loc) · 14.5 KB
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
const fs = require("node:fs");
const path = require("node:path");
const { parseChunked } = require("@discoveryjs/json-ext");
const Logger = require("./Logger");
const { parseBundle } = require("./parseUtils");
const { getCompressedSize } = require("./sizeUtils");
const Folder = require("./tree/Folder").default;
const { createAssetsFilter } = require("./utils");
const FILENAME_QUERY_REGEXP = /\?.*$/u;
const FILENAME_EXTENSIONS = /\.(js|mjs|cjs|bundle)$/iu;
/** @typedef {import("webpack").StatsCompilation} StatsCompilation */
/** @typedef {import("webpack").StatsModule} StatsModule */
/** @typedef {import("webpack").StatsAsset} StatsAsset */
/** @typedef {import("./BundleAnalyzerPlugin").CompressionAlgorithm} CompressionAlgorithm */
/** @typedef {import("./BundleAnalyzerPlugin").ExcludeAssets} ExcludeAssets */
/**
* @typedef {object} AnalyzerOptions
* @property {"gzip" | "brotli" | "zstd"} compressionAlgorithm compression algorithm
*/
/**
* @param {StatsModule[]} modules modules
* @param {AnalyzerOptions} options options
* @returns {Folder} a folder class
*/
function createModulesTree(modules, options) {
const root = new Folder(".", options);
for (const module of modules) {
root.addModule(module);
}
root.mergeNestedFolders();
return root;
}
/**
* arr-flatten <https://github.com/jonschlinkert/arr-flatten>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*
* Modified by Sukka <https://skk.moe>
*
* Replace recursively flatten with one-level deep flatten to match lodash.flatten
*
* TODO: replace with Array.prototype.flat once Node.js 10 support is dropped
*/
/**
* Flattens an array by one level.
* @template T
* @param {(T | T[])[]} arr the array to flatten
* @returns {T[]} a new array containing the flattened elements
*/
function flatten(arr) {
if (!arr) return [];
const len = arr.length;
if (!len) return [];
let cur;
const res = [];
for (let i = 0; i < len; i++) {
cur = arr[i];
if (Array.isArray(cur)) {
res.push(...cur);
} else {
res.push(cur);
}
}
return res;
}
/**
* @param {StatsCompilation} bundleStats bundle stats
* @param {string} assetName asset name
* @returns {boolean} child asset bundlers
*/
function getChildAssetBundles(bundleStats, assetName) {
return flatten(
(bundleStats.children || /** @type {StatsCompilation} */ ([])).find(
/**
* @param {StatsCompilation} child child stats
* @returns {string[][]} assets by chunk name
*/
(child) => Object.values(child.assetsByChunkName || []),
),
).includes(assetName);
}
/**
* @param {StatsAsset} statsAsset stats asset
* @param {StatsModule} statsModule stats modules
* @returns {boolean} true when asset has a module
*/
function assetHasModule(statsAsset, statsModule) {
// Checking if this module is the part of asset chunks
return (statsModule.chunks || []).some(
(moduleChunk) =>
statsAsset.chunks && statsAsset.chunks.includes(moduleChunk),
);
}
/**
* @param {StatsModule} statsModule stats Module
* @returns {boolean} true when runtime modules, otherwise false
*/
function isRuntimeModule(statsModule) {
return statsModule.moduleType === "runtime";
}
/**
* @param {StatsCompilation} bundleStats bundle stats
* @returns {StatsModule[]} modules
*/
function getBundleModules(bundleStats) {
/** @type {Set<string | number>} */
const seenIds = new Set();
const modules = /** @type {StatsModule[]} */ ([
...(bundleStats.chunks?.map((chunk) => chunk.modules) || []),
...(bundleStats.modules || []),
]).filter(Boolean);
return flatten(modules).filter((mod) => {
// Filtering out Webpack's runtime modules as they don't have ids and can't be parsed (introduced in Webpack 5)
if (isRuntimeModule(mod)) {
return false;
}
if (seenIds.has(mod.id)) {
return false;
}
seenIds.add(mod.id);
return true;
});
}
/** @typedef {Record<string, Record<string, boolean>>} ChunkToInitialByEntrypoint */
/**
* @param {StatsCompilation} bundleStats bundle stats
* @returns {ChunkToInitialByEntrypoint} chunk to initial by entrypoint
*/
function getChunkToInitialByEntrypoint(bundleStats) {
if (bundleStats === null || bundleStats === undefined) {
return {};
}
/** @type {ChunkToInitialByEntrypoint} */
const chunkToEntrypointInititalMap = {};
for (const entrypoint of Object.values(bundleStats.entrypoints || {})) {
for (const asset of entrypoint.assets || []) {
chunkToEntrypointInititalMap[asset.name] ??= {};
chunkToEntrypointInititalMap[asset.name][
/** @type {string} */
(entrypoint.name)
] = true;
}
}
return chunkToEntrypointInititalMap;
}
/**
* @param {StatsModule} statsModule stats modules
* @returns {boolean} true when entry module, otherwise false
*/
function isEntryModule(statsModule) {
return statsModule.depth === 0;
}
/**
* @typedef {object} ViewerDataOptions
* @property {Logger} logger logger
* @property {CompressionAlgorithm} compressionAlgorithm compression algorithm
* @property {ExcludeAssets} excludeAssets exclude assets
* @property {import("webpack").OutputFileSystem | null=} outputFs non-default filesystem for reading bundle files
*/
/** @typedef {import("./tree/Module").ModuleChartData} ModuleChartData */
/** @typedef {import("./tree/ContentModule").ContentModuleChartData} ContentModuleChartData */
/** @typedef {import("./tree/ConcatenatedModule").ConcatenatedModuleChartData} ConcatenatedModuleChartData */
/** @typedef {import("./tree/ContentFolder").ContentFolderChartData} ContentFolderChartData */
/** @typedef {import("./tree/Folder").FolderChartData} FolderChartData */
/**
* @typedef {object} ChartDataItem
* @property {string} label label
* @property {true} isAsset true when is asset, otherwise false
* @property {number} statSize stat size
* @property {number | undefined} parsedSize stat size
* @property {number | undefined} gzipSize gzip size
* @property {number | undefined} brotliSize brotli size
* @property {number | undefined} zstdSize zstd size
* @property {(ModuleChartData | ContentModuleChartData | ConcatenatedModuleChartData | ContentFolderChartData | FolderChartData)[]} groups groups
* @property {Record<string, boolean>} isInitialByEntrypoint record with initial entrypoints
*/
/**
* @typedef {ChartDataItem[]} ChartData
*/
/**
* @param {StatsCompilation} bundleStats bundle stats
* @param {string | null} bundleDir bundle dir
* @param {ViewerDataOptions=} opts options
* @returns {ChartData} chart data
*/
function getViewerData(bundleStats, bundleDir, opts) {
const {
logger = new Logger(),
compressionAlgorithm = "gzip",
excludeAssets = null,
outputFs = null,
} = opts || {};
const isAssetIncluded = createAssetsFilter(excludeAssets);
// Sometimes all the information is located in `children` array (e.g. problem in #10)
if (
(bundleStats.assets === null ||
bundleStats.assets === undefined ||
bundleStats.assets.length === 0) &&
bundleStats.children &&
bundleStats.children.length > 0
) {
const { children } = bundleStats;
[bundleStats] = bundleStats.children;
// Sometimes if there are additional child chunks produced add them as child assets,
// leave the 1st one as that is considered the 'root' asset.
for (let i = 1; i < children.length; i++) {
for (const asset of children[i].assets || []) {
asset.isChild = true;
/** @type {StatsAsset[]} */
(bundleStats.assets).push(asset);
}
}
} else if (bundleStats.children && bundleStats.children.length > 0) {
// Sometimes if there are additional child chunks produced add them as child assets
for (const child of bundleStats.children) {
for (const asset of child.assets || []) {
asset.isChild = true;
/** @type {StatsAsset[]} */
(bundleStats.assets).push(asset);
}
}
}
// Picking only `*.js, *.cjs or *.mjs` assets from bundle that has non-empty `chunks` array
bundleStats.assets = (bundleStats.assets || []).filter((asset) => {
// Filter out non 'asset' type asset if type is provided (Webpack 5 add a type to indicate asset types)
if (asset.type && asset.type !== "asset") {
return false;
}
// Removing query part from filename (yes, somebody uses it for some reason and Webpack supports it)
// See #22
asset.name = asset.name.replace(FILENAME_QUERY_REGEXP, "");
return (
FILENAME_EXTENSIONS.test(asset.name) &&
asset.chunks &&
asset.chunks.length > 0 &&
isAssetIncluded(asset.name)
);
});
// Trying to parse bundle assets and get real module sizes if `bundleDir` is provided
/** @type {Record<string, { src: string, runtimeSrc: string }> | null} */
let bundlesSources = null;
/** @type {Record<string | number, boolean> | null} */
let parsedModules = null;
if (bundleDir) {
bundlesSources = {};
parsedModules = {};
for (const statAsset of bundleStats.assets) {
const assetFile = path.join(bundleDir, statAsset.name);
let bundleInfo;
try {
bundleInfo = parseBundle(assetFile, {
sourceType: statAsset.info.javascriptModule ? "module" : "script",
...(outputFs && { fs: outputFs }),
});
} catch (err) {
const msg =
/** @type {NodeJS.ErrnoException} */ (err).code === "ENOENT"
? "no such file"
: /** @type {Error} */ (err).message;
logger.warn(`Error parsing bundle asset "${assetFile}": ${msg}`, {
cause: err,
});
continue;
}
bundlesSources[statAsset.name] = {
src: bundleInfo.src,
runtimeSrc: bundleInfo.runtimeSrc,
};
Object.assign(parsedModules, bundleInfo.modules);
}
if (Object.keys(bundlesSources).length === 0) {
bundlesSources = null;
parsedModules = null;
logger.warn(
"\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n",
);
}
}
/** @typedef {{ size: number, parsedSize?: number, gzipSize?: number, brotliSize?: number, zstdSize?: number, modules: StatsModule[], tree: Folder }} Asset */
const assets = bundleStats.assets.reduce((result, statAsset) => {
// If asset is a childAsset, then calculate appropriate bundle modules by looking through stats.children
const assetBundles = statAsset.isChild
? getChildAssetBundles(bundleStats, statAsset.name)
: bundleStats;
/** @type {StatsModule[]} */
const modules = assetBundles
? // @ts-expect-error TODO looks like we have a bug with child compilation parsing, need to add test cases
getBundleModules(assetBundles)
: [];
const asset = (result[statAsset.name] = /** @type {Asset} */ ({
size: statAsset.size,
}));
const assetSources =
bundlesSources && Object.hasOwn(bundlesSources, statAsset.name)
? bundlesSources[statAsset.name]
: null;
if (assetSources) {
asset.parsedSize = Buffer.byteLength(assetSources.src);
if (compressionAlgorithm === "gzip") {
asset.gzipSize = getCompressedSize("gzip", assetSources.src);
}
if (compressionAlgorithm === "brotli") {
asset.brotliSize = getCompressedSize("brotli", assetSources.src);
}
if (compressionAlgorithm === "zstd") {
asset.zstdSize = getCompressedSize("zstd", assetSources.src);
}
}
// Picking modules from current bundle script
/** @type {StatsModule[]} */
let assetModules = (modules || []).filter((statModule) =>
assetHasModule(statAsset, statModule),
);
// Adding parsed sources
if (parsedModules) {
/** @type {StatsModule[]} */
const unparsedEntryModules = [];
for (const statsModule of assetModules) {
if (
typeof statsModule.id !== "undefined" &&
parsedModules[statsModule.id]
) {
statsModule.parsedSrc = parsedModules[statsModule.id];
} else if (isEntryModule(statsModule)) {
unparsedEntryModules.push(statsModule);
}
}
// Webpack 5 changed bundle format and now entry modules are concatenated and located at the end of it.
// Because of this they basically become a concatenated module, for which we can't even precisely determine its
// parsed source as it's located in the same scope as all Webpack runtime helpers.
if (unparsedEntryModules.length && assetSources) {
if (unparsedEntryModules.length === 1) {
// So if there is only one entry we consider its parsed source to be all the bundle code excluding code
// from parsed modules.
unparsedEntryModules[0].parsedSrc = assetSources.runtimeSrc;
} else {
// If there are multiple entry points we move all of them under synthetic concatenated module.
assetModules = (assetModules || []).filter(
(mod) => !unparsedEntryModules.includes(mod),
);
assetModules.unshift({
identifier: "./entry modules",
name: "./entry modules",
modules: unparsedEntryModules,
size: unparsedEntryModules.reduce(
(totalSize, module) =>
totalSize + /** @type {number} */ (module.size),
0,
),
parsedSrc: assetSources.runtimeSrc,
});
}
}
}
asset.modules = assetModules;
asset.tree = createModulesTree(asset.modules, { compressionAlgorithm });
return result;
}, /** @type {Record<string, Asset>} */ ({}));
const chunkToInitialByEntrypoint = getChunkToInitialByEntrypoint(bundleStats);
return Object.entries(assets).map(([filename, asset]) => ({
label: filename,
isAsset: true,
// Not using `asset.size` here provided by Webpack because it can be very confusing when `UglifyJsPlugin` is used.
// In this case all module sizes from stats file will represent unminified module sizes, but `asset.size` will
// be the size of minified bundle.
// Using `asset.size` only if current asset doesn't contain any modules (resulting size equals 0)
statSize: asset.tree.size || asset.size,
parsedSize: asset.parsedSize,
gzipSize: asset.gzipSize,
brotliSize: asset.brotliSize,
zstdSize: asset.zstdSize,
groups: Object.values(asset.tree.children).map((i) => i.toChartData()),
isInitialByEntrypoint: chunkToInitialByEntrypoint[filename] ?? {},
}));
}
/**
* @param {string} filename filename
* @returns {Promise<StatsCompilation>} result
*/
function readStatsFromFile(filename) {
return parseChunked(fs.createReadStream(filename, { encoding: "utf8" }));
}
module.exports = {
getViewerData,
readStatsFromFile,
};