analyzer.js 9.4 KB

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