UNPKG

8.33 kBJavaScriptView Raw
1"use strict";
2
3const fs = require('fs');
4
5const path = require('path');
6
7const _ = require('lodash');
8
9const gzipSize = require('gzip-size');
10
11const Logger = require('./Logger');
12
13const Folder = require('./tree/Folder').default;
14
15const {
16 parseBundle
17} = require('./parseUtils');
18
19const {
20 createAssetsFilter
21} = require('./utils');
22
23const FILENAME_QUERY_REGEXP = /\?.*$/u;
24const FILENAME_EXTENSIONS = /\.(js|mjs)$/iu;
25module.exports = {
26 getViewerData,
27 readStatsFromFile
28};
29
30function getViewerData(bundleStats, bundleDir, opts) {
31 const {
32 logger = new Logger(),
33 excludeAssets = null
34 } = opts || {};
35 const isAssetIncluded = createAssetsFilter(excludeAssets); // Sometimes all the information is located in `children` array (e.g. problem in #10)
36
37 if (_.isEmpty(bundleStats.assets) && !_.isEmpty(bundleStats.children)) {
38 const {
39 children
40 } = bundleStats;
41 bundleStats = bundleStats.children[0]; // Sometimes if there are additional child chunks produced add them as child assets,
42 // leave the 1st one as that is considered the 'root' asset.
43
44 for (let i = 1; i < children.length; i++) {
45 children[i].assets.forEach(asset => {
46 asset.isChild = true;
47 bundleStats.assets.push(asset);
48 });
49 }
50 } else if (!_.isEmpty(bundleStats.children)) {
51 // Sometimes if there are additional child chunks produced add them as child assets
52 bundleStats.children.forEach(child => {
53 child.assets.forEach(asset => {
54 asset.isChild = true;
55 bundleStats.assets.push(asset);
56 });
57 });
58 } // Picking only `*.js or *.mjs` assets from bundle that has non-empty `chunks` array
59
60
61 bundleStats.assets = bundleStats.assets.filter(asset => {
62 // Filter out non 'asset' type asset if type is provided (Webpack 5 add a type to indicate asset types)
63 if (asset.type && asset.type !== 'asset') {
64 return false;
65 } // Removing query part from filename (yes, somebody uses it for some reason and Webpack supports it)
66 // See #22
67
68
69 asset.name = asset.name.replace(FILENAME_QUERY_REGEXP, '');
70 return FILENAME_EXTENSIONS.test(asset.name) && !_.isEmpty(asset.chunks) && isAssetIncluded(asset.name);
71 }); // Trying to parse bundle assets and get real module sizes if `bundleDir` is provided
72
73 let bundlesSources = null;
74 let parsedModules = null;
75
76 if (bundleDir) {
77 bundlesSources = {};
78 parsedModules = {};
79
80 for (const statAsset of bundleStats.assets) {
81 const assetFile = path.join(bundleDir, statAsset.name);
82 let bundleInfo;
83
84 try {
85 bundleInfo = parseBundle(assetFile);
86 } catch (err) {
87 const msg = err.code === 'ENOENT' ? 'no such file' : err.message;
88 logger.warn(`Error parsing bundle asset "${assetFile}": ${msg}`);
89 continue;
90 }
91
92 bundlesSources[statAsset.name] = _.pick(bundleInfo, 'src', 'runtimeSrc');
93 Object.assign(parsedModules, bundleInfo.modules);
94 }
95
96 if (_.isEmpty(bundlesSources)) {
97 bundlesSources = null;
98 parsedModules = null;
99 logger.warn('\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n');
100 }
101 }
102
103 const assets = bundleStats.assets.reduce((result, statAsset) => {
104 // If asset is a childAsset, then calculate appropriate bundle modules by looking through stats.children
105 const assetBundles = statAsset.isChild ? getChildAssetBundles(bundleStats, statAsset.name) : bundleStats;
106 const modules = assetBundles ? getBundleModules(assetBundles) : [];
107
108 const asset = result[statAsset.name] = _.pick(statAsset, 'size');
109
110 const assetSources = bundlesSources && _.has(bundlesSources, statAsset.name) ? bundlesSources[statAsset.name] : null;
111
112 if (assetSources) {
113 asset.parsedSize = Buffer.byteLength(assetSources.src);
114 asset.gzipSize = gzipSize.sync(assetSources.src);
115 } // Picking modules from current bundle script
116
117
118 const assetModules = modules.filter(statModule => assetHasModule(statAsset, statModule)); // Adding parsed sources
119
120 if (parsedModules) {
121 const unparsedEntryModules = [];
122
123 for (const statModule of assetModules) {
124 if (parsedModules[statModule.id]) {
125 statModule.parsedSrc = parsedModules[statModule.id];
126 } else if (isEntryModule(statModule)) {
127 unparsedEntryModules.push(statModule);
128 }
129 } // Webpack 5 changed bundle format and now entry modules are concatenated and located at the end of it.
130 // Because of this they basically become a concatenated module, for which we can't even precisely determine its
131 // parsed source as it's located in the same scope as all Webpack runtime helpers.
132
133
134 if (unparsedEntryModules.length && assetSources) {
135 if (unparsedEntryModules.length === 1) {
136 // So if there is only one entry we consider its parsed source to be all the bundle code excluding code
137 // from parsed modules.
138 unparsedEntryModules[0].parsedSrc = assetSources.runtimeSrc;
139 } else {
140 // If there are multiple entry points we move all of them under synthetic concatenated module.
141 _.pullAll(assetModules, unparsedEntryModules);
142
143 assetModules.unshift({
144 identifier: './entry modules',
145 name: './entry modules',
146 modules: unparsedEntryModules,
147 size: unparsedEntryModules.reduce((totalSize, module) => totalSize + module.size, 0),
148 parsedSrc: assetSources.runtimeSrc
149 });
150 }
151 }
152 }
153
154 asset.modules = assetModules;
155 asset.tree = createModulesTree(asset.modules);
156 return result;
157 }, {});
158 const chunkToInitialByEntrypoint = getChunkToInitialByEntrypoint(bundleStats);
159 return Object.entries(assets).map(([filename, asset]) => {
160 var _chunkToInitialByEntr;
161
162 return {
163 label: filename,
164 isAsset: true,
165 // Not using `asset.size` here provided by Webpack because it can be very confusing when `UglifyJsPlugin` is used.
166 // In this case all module sizes from stats file will represent unminified module sizes, but `asset.size` will
167 // be the size of minified bundle.
168 // Using `asset.size` only if current asset doesn't contain any modules (resulting size equals 0)
169 statSize: asset.tree.size || asset.size,
170 parsedSize: asset.parsedSize,
171 gzipSize: asset.gzipSize,
172 groups: _.invokeMap(asset.tree.children, 'toChartData'),
173 isInitialByEntrypoint: (_chunkToInitialByEntr = chunkToInitialByEntrypoint[filename]) !== null && _chunkToInitialByEntr !== void 0 ? _chunkToInitialByEntr : {}
174 };
175 });
176}
177
178function readStatsFromFile(filename) {
179 return JSON.parse(fs.readFileSync(filename, 'utf8'));
180}
181
182function getChildAssetBundles(bundleStats, assetName) {
183 return (bundleStats.children || []).find(c => _(c.assetsByChunkName).values().flatten().includes(assetName));
184}
185
186function getBundleModules(bundleStats) {
187 return _(bundleStats.chunks).map('modules').concat(bundleStats.modules).compact().flatten().uniqBy('id') // Filtering out Webpack's runtime modules as they don't have ids and can't be parsed (introduced in Webpack 5)
188 .reject(isRuntimeModule).value();
189}
190
191function assetHasModule(statAsset, statModule) {
192 // Checking if this module is the part of asset chunks
193 return (statModule.chunks || []).some(moduleChunk => statAsset.chunks.includes(moduleChunk));
194}
195
196function isEntryModule(statModule) {
197 return statModule.depth === 0;
198}
199
200function isRuntimeModule(statModule) {
201 return statModule.moduleType === 'runtime';
202}
203
204function createModulesTree(modules) {
205 const root = new Folder('.');
206 modules.forEach(module => root.addModule(module));
207 root.mergeNestedFolders();
208 return root;
209}
210
211function getChunkToInitialByEntrypoint(bundleStats) {
212 if (bundleStats == null) {
213 return {};
214 }
215
216 const chunkToEntrypointInititalMap = {};
217 Object.values(bundleStats.entrypoints || {}).forEach(entrypoint => {
218 for (const asset of entrypoint.assets) {
219 var _chunkToEntrypointIni;
220
221 chunkToEntrypointInititalMap[asset.name] = (_chunkToEntrypointIni = chunkToEntrypointInititalMap[asset.name]) !== null && _chunkToEntrypointIni !== void 0 ? _chunkToEntrypointIni : {};
222 chunkToEntrypointInititalMap[asset.name][entrypoint.name] = true;
223 }
224 });
225 return chunkToEntrypointInititalMap;
226}
227
228;
\No newline at end of file