analyzer.js 8.7 KB

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