You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1685 lines
44 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RequestShortener = require("./RequestShortener");
  7. const SizeFormatHelpers = require("./SizeFormatHelpers");
  8. const formatLocation = require("./formatLocation");
  9. const identifierUtils = require("./util/identifier");
  10. const compareLocations = require("./compareLocations");
  11. const { LogType } = require("./logging/Logger");
  12. const optionsOrFallback = (...args) => {
  13. let optionValues = [];
  14. optionValues.push(...args);
  15. return optionValues.find(optionValue => optionValue !== undefined);
  16. };
  17. const compareId = (a, b) => {
  18. if (typeof a !== typeof b) {
  19. return typeof a < typeof b ? -1 : 1;
  20. }
  21. if (a < b) return -1;
  22. if (a > b) return 1;
  23. return 0;
  24. };
  25. class Stats {
  26. constructor(compilation) {
  27. this.compilation = compilation;
  28. this.hash = compilation.hash;
  29. this.startTime = undefined;
  30. this.endTime = undefined;
  31. }
  32. static filterWarnings(warnings, warningsFilter) {
  33. // we dont have anything to filter so all warnings can be shown
  34. if (!warningsFilter) {
  35. return warnings;
  36. }
  37. // create a chain of filters
  38. // if they return "true" a warning should be suppressed
  39. const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => {
  40. if (typeof filter === "string") {
  41. return warning => warning.includes(filter);
  42. }
  43. if (filter instanceof RegExp) {
  44. return warning => filter.test(warning);
  45. }
  46. if (typeof filter === "function") {
  47. return filter;
  48. }
  49. throw new Error(
  50. `Can only filter warnings with Strings or RegExps. (Given: ${filter})`
  51. );
  52. });
  53. return warnings.filter(warning => {
  54. return !normalizedWarningsFilters.some(check => check(warning));
  55. });
  56. }
  57. formatFilePath(filePath) {
  58. const OPTIONS_REGEXP = /^(\s|\S)*!/;
  59. return filePath.includes("!")
  60. ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})`
  61. : `${filePath}`;
  62. }
  63. hasWarnings() {
  64. return (
  65. this.compilation.warnings.length > 0 ||
  66. this.compilation.children.some(child => child.getStats().hasWarnings())
  67. );
  68. }
  69. hasErrors() {
  70. return (
  71. this.compilation.errors.length > 0 ||
  72. this.compilation.children.some(child => child.getStats().hasErrors())
  73. );
  74. }
  75. // remove a prefixed "!" that can be specified to reverse sort order
  76. normalizeFieldKey(field) {
  77. if (field[0] === "!") {
  78. return field.substr(1);
  79. }
  80. return field;
  81. }
  82. // if a field is prefixed by a "!" reverse sort order
  83. sortOrderRegular(field) {
  84. if (field[0] === "!") {
  85. return false;
  86. }
  87. return true;
  88. }
  89. toJson(options, forToString) {
  90. if (typeof options === "boolean" || typeof options === "string") {
  91. options = Stats.presetToOptions(options);
  92. } else if (!options) {
  93. options = {};
  94. }
  95. const optionOrLocalFallback = (v, def) =>
  96. v !== undefined ? v : options.all !== undefined ? options.all : def;
  97. const testAgainstGivenOption = item => {
  98. if (typeof item === "string") {
  99. const regExp = new RegExp(
  100. `[\\\\/]${item.replace(
  101. // eslint-disable-next-line no-useless-escape
  102. /[-[\]{}()*+?.\\^$|]/g,
  103. "\\$&"
  104. )}([\\\\/]|$|!|\\?)`
  105. );
  106. return ident => regExp.test(ident);
  107. }
  108. if (item && typeof item === "object" && typeof item.test === "function") {
  109. return ident => item.test(ident);
  110. }
  111. if (typeof item === "function") {
  112. return item;
  113. }
  114. if (typeof item === "boolean") {
  115. return () => item;
  116. }
  117. };
  118. const compilation = this.compilation;
  119. const context = optionsOrFallback(
  120. options.context,
  121. compilation.compiler.context
  122. );
  123. const requestShortener =
  124. compilation.compiler.context === context
  125. ? compilation.requestShortener
  126. : new RequestShortener(context);
  127. const showPerformance = optionOrLocalFallback(options.performance, true);
  128. const showHash = optionOrLocalFallback(options.hash, true);
  129. const showEnv = optionOrLocalFallback(options.env, false);
  130. const showVersion = optionOrLocalFallback(options.version, true);
  131. const showTimings = optionOrLocalFallback(options.timings, true);
  132. const showBuiltAt = optionOrLocalFallback(options.builtAt, true);
  133. const showAssets = optionOrLocalFallback(options.assets, true);
  134. const showEntrypoints = optionOrLocalFallback(options.entrypoints, true);
  135. const showChunkGroups = optionOrLocalFallback(
  136. options.chunkGroups,
  137. !forToString
  138. );
  139. const showChunks = optionOrLocalFallback(options.chunks, !forToString);
  140. const showChunkModules = optionOrLocalFallback(options.chunkModules, true);
  141. const showChunkOrigins = optionOrLocalFallback(
  142. options.chunkOrigins,
  143. !forToString
  144. );
  145. const showModules = optionOrLocalFallback(options.modules, true);
  146. const showNestedModules = optionOrLocalFallback(
  147. options.nestedModules,
  148. true
  149. );
  150. const showModuleAssets = optionOrLocalFallback(
  151. options.moduleAssets,
  152. !forToString
  153. );
  154. const showDepth = optionOrLocalFallback(options.depth, !forToString);
  155. const showCachedModules = optionOrLocalFallback(options.cached, true);
  156. const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true);
  157. const showReasons = optionOrLocalFallback(options.reasons, !forToString);
  158. const showUsedExports = optionOrLocalFallback(
  159. options.usedExports,
  160. !forToString
  161. );
  162. const showProvidedExports = optionOrLocalFallback(
  163. options.providedExports,
  164. !forToString
  165. );
  166. const showOptimizationBailout = optionOrLocalFallback(
  167. options.optimizationBailout,
  168. !forToString
  169. );
  170. const showChildren = optionOrLocalFallback(options.children, true);
  171. const showSource = optionOrLocalFallback(options.source, !forToString);
  172. const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true);
  173. const showErrors = optionOrLocalFallback(options.errors, true);
  174. const showErrorDetails = optionOrLocalFallback(
  175. options.errorDetails,
  176. !forToString
  177. );
  178. const showWarnings = optionOrLocalFallback(options.warnings, true);
  179. const warningsFilter = optionsOrFallback(options.warningsFilter, null);
  180. const showPublicPath = optionOrLocalFallback(
  181. options.publicPath,
  182. !forToString
  183. );
  184. const showLogging = optionOrLocalFallback(
  185. options.logging,
  186. forToString ? "info" : true
  187. );
  188. const showLoggingTrace = optionOrLocalFallback(
  189. options.loggingTrace,
  190. !forToString
  191. );
  192. const loggingDebug = []
  193. .concat(optionsOrFallback(options.loggingDebug, []))
  194. .map(testAgainstGivenOption);
  195. const excludeModules = []
  196. .concat(optionsOrFallback(options.excludeModules, options.exclude, []))
  197. .map(testAgainstGivenOption);
  198. const excludeAssets = []
  199. .concat(optionsOrFallback(options.excludeAssets, []))
  200. .map(testAgainstGivenOption);
  201. const maxModules = optionsOrFallback(
  202. options.maxModules,
  203. forToString ? 15 : Infinity
  204. );
  205. const sortModules = optionsOrFallback(options.modulesSort, "id");
  206. const sortChunks = optionsOrFallback(options.chunksSort, "id");
  207. const sortAssets = optionsOrFallback(options.assetsSort, "");
  208. const showOutputPath = optionOrLocalFallback(
  209. options.outputPath,
  210. !forToString
  211. );
  212. if (!showCachedModules) {
  213. excludeModules.push((ident, module) => !module.built);
  214. }
  215. const createModuleFilter = () => {
  216. let i = 0;
  217. return module => {
  218. if (excludeModules.length > 0) {
  219. const ident = requestShortener.shorten(module.resource);
  220. const excluded = excludeModules.some(fn => fn(ident, module));
  221. if (excluded) return false;
  222. }
  223. const result = i < maxModules;
  224. i++;
  225. return result;
  226. };
  227. };
  228. const createAssetFilter = () => {
  229. return asset => {
  230. if (excludeAssets.length > 0) {
  231. const ident = asset.name;
  232. const excluded = excludeAssets.some(fn => fn(ident, asset));
  233. if (excluded) return false;
  234. }
  235. return showCachedAssets || asset.emitted;
  236. };
  237. };
  238. const sortByFieldAndOrder = (fieldKey, a, b) => {
  239. if (a[fieldKey] === null && b[fieldKey] === null) return 0;
  240. if (a[fieldKey] === null) return 1;
  241. if (b[fieldKey] === null) return -1;
  242. if (a[fieldKey] === b[fieldKey]) return 0;
  243. if (typeof a[fieldKey] !== typeof b[fieldKey])
  244. return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1;
  245. return a[fieldKey] < b[fieldKey] ? -1 : 1;
  246. };
  247. const sortByField = (field, originalArray) => {
  248. const originalMap = originalArray.reduce((map, v, i) => {
  249. map.set(v, i);
  250. return map;
  251. }, new Map());
  252. return (a, b) => {
  253. if (field) {
  254. const fieldKey = this.normalizeFieldKey(field);
  255. // if a field is prefixed with a "!" the sort is reversed!
  256. const sortIsRegular = this.sortOrderRegular(field);
  257. const cmp = sortByFieldAndOrder(
  258. fieldKey,
  259. sortIsRegular ? a : b,
  260. sortIsRegular ? b : a
  261. );
  262. if (cmp) return cmp;
  263. }
  264. return originalMap.get(a) - originalMap.get(b);
  265. };
  266. };
  267. const formatError = e => {
  268. let text = "";
  269. if (typeof e === "string") {
  270. e = { message: e };
  271. }
  272. if (e.chunk) {
  273. text += `chunk ${e.chunk.name || e.chunk.id}${
  274. e.chunk.hasRuntime()
  275. ? " [entry]"
  276. : e.chunk.canBeInitial()
  277. ? " [initial]"
  278. : ""
  279. }\n`;
  280. }
  281. if (e.file) {
  282. text += `${e.file}\n`;
  283. }
  284. if (
  285. e.module &&
  286. e.module.readableIdentifier &&
  287. typeof e.module.readableIdentifier === "function"
  288. ) {
  289. text += this.formatFilePath(
  290. e.module.readableIdentifier(requestShortener)
  291. );
  292. if (typeof e.loc === "object") {
  293. const locInfo = formatLocation(e.loc);
  294. if (locInfo) text += ` ${locInfo}`;
  295. }
  296. text += "\n";
  297. }
  298. text += e.message;
  299. if (showErrorDetails && e.details) {
  300. text += `\n${e.details}`;
  301. }
  302. if (showErrorDetails && e.missing) {
  303. text += e.missing.map(item => `\n[${item}]`).join("");
  304. }
  305. if (showModuleTrace && e.origin) {
  306. text += `\n @ ${this.formatFilePath(
  307. e.origin.readableIdentifier(requestShortener)
  308. )}`;
  309. if (typeof e.originLoc === "object") {
  310. const locInfo = formatLocation(e.originLoc);
  311. if (locInfo) text += ` ${locInfo}`;
  312. }
  313. if (e.dependencies) {
  314. for (const dep of e.dependencies) {
  315. if (!dep.loc) continue;
  316. if (typeof dep.loc === "string") continue;
  317. const locInfo = formatLocation(dep.loc);
  318. if (!locInfo) continue;
  319. text += ` ${locInfo}`;
  320. }
  321. }
  322. let current = e.origin;
  323. while (current.issuer) {
  324. current = current.issuer;
  325. text += `\n @ ${current.readableIdentifier(requestShortener)}`;
  326. }
  327. }
  328. return text;
  329. };
  330. const obj = {
  331. errors: compilation.errors.map(formatError),
  332. warnings: Stats.filterWarnings(
  333. compilation.warnings.map(formatError),
  334. warningsFilter
  335. )
  336. };
  337. //We just hint other renderers since actually omitting
  338. //errors/warnings from the JSON would be kind of weird.
  339. Object.defineProperty(obj, "_showWarnings", {
  340. value: showWarnings,
  341. enumerable: false
  342. });
  343. Object.defineProperty(obj, "_showErrors", {
  344. value: showErrors,
  345. enumerable: false
  346. });
  347. if (showVersion) {
  348. obj.version = require("../package.json").version;
  349. }
  350. if (showHash) obj.hash = this.hash;
  351. if (showTimings && this.startTime && this.endTime) {
  352. obj.time = this.endTime - this.startTime;
  353. }
  354. if (showBuiltAt && this.endTime) {
  355. obj.builtAt = this.endTime;
  356. }
  357. if (showEnv && options._env) {
  358. obj.env = options._env;
  359. }
  360. if (compilation.needAdditionalPass) {
  361. obj.needAdditionalPass = true;
  362. }
  363. if (showPublicPath) {
  364. obj.publicPath = this.compilation.mainTemplate.getPublicPath({
  365. hash: this.compilation.hash
  366. });
  367. }
  368. if (showOutputPath) {
  369. obj.outputPath = this.compilation.mainTemplate.outputOptions.path;
  370. }
  371. if (showAssets) {
  372. const assetsByFile = {};
  373. const compilationAssets = compilation
  374. .getAssets()
  375. .sort((a, b) => (a.name < b.name ? -1 : 1));
  376. obj.assetsByChunkName = {};
  377. obj.assets = compilationAssets
  378. .map(({ name, source, info }) => {
  379. const obj = {
  380. name,
  381. size: source.size(),
  382. chunks: [],
  383. chunkNames: [],
  384. info,
  385. // TODO webpack 5: remove .emitted
  386. emitted: source.emitted || compilation.emittedAssets.has(name)
  387. };
  388. if (showPerformance) {
  389. obj.isOverSizeLimit = source.isOverSizeLimit;
  390. }
  391. assetsByFile[name] = obj;
  392. return obj;
  393. })
  394. .filter(createAssetFilter());
  395. obj.filteredAssets = compilationAssets.length - obj.assets.length;
  396. for (const chunk of compilation.chunks) {
  397. for (const asset of chunk.files) {
  398. if (assetsByFile[asset]) {
  399. for (const id of chunk.ids) {
  400. assetsByFile[asset].chunks.push(id);
  401. }
  402. if (chunk.name) {
  403. assetsByFile[asset].chunkNames.push(chunk.name);
  404. if (obj.assetsByChunkName[chunk.name]) {
  405. obj.assetsByChunkName[chunk.name] = []
  406. .concat(obj.assetsByChunkName[chunk.name])
  407. .concat([asset]);
  408. } else {
  409. obj.assetsByChunkName[chunk.name] = asset;
  410. }
  411. }
  412. }
  413. }
  414. }
  415. obj.assets.sort(sortByField(sortAssets, obj.assets));
  416. }
  417. const fnChunkGroup = groupMap => {
  418. const obj = {};
  419. for (const keyValuePair of groupMap) {
  420. const name = keyValuePair[0];
  421. const cg = keyValuePair[1];
  422. const children = cg.getChildrenByOrders();
  423. obj[name] = {
  424. chunks: cg.chunks.map(c => c.id),
  425. assets: cg.chunks.reduce(
  426. (array, c) => array.concat(c.files || []),
  427. []
  428. ),
  429. children: Object.keys(children).reduce((obj, key) => {
  430. const groups = children[key];
  431. obj[key] = groups.map(group => ({
  432. name: group.name,
  433. chunks: group.chunks.map(c => c.id),
  434. assets: group.chunks.reduce(
  435. (array, c) => array.concat(c.files || []),
  436. []
  437. )
  438. }));
  439. return obj;
  440. }, Object.create(null)),
  441. childAssets: Object.keys(children).reduce((obj, key) => {
  442. const groups = children[key];
  443. obj[key] = Array.from(
  444. groups.reduce((set, group) => {
  445. for (const chunk of group.chunks) {
  446. for (const asset of chunk.files) {
  447. set.add(asset);
  448. }
  449. }
  450. return set;
  451. }, new Set())
  452. );
  453. return obj;
  454. }, Object.create(null))
  455. };
  456. if (showPerformance) {
  457. obj[name].isOverSizeLimit = cg.isOverSizeLimit;
  458. }
  459. }
  460. return obj;
  461. };
  462. if (showEntrypoints) {
  463. obj.entrypoints = fnChunkGroup(compilation.entrypoints);
  464. }
  465. if (showChunkGroups) {
  466. obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups);
  467. }
  468. const fnModule = module => {
  469. const path = [];
  470. let current = module;
  471. while (current.issuer) {
  472. path.push((current = current.issuer));
  473. }
  474. path.reverse();
  475. const obj = {
  476. id: module.id,
  477. identifier: module.identifier(),
  478. name: module.readableIdentifier(requestShortener),
  479. index: module.index,
  480. index2: module.index2,
  481. size: module.size(),
  482. cacheable: module.buildInfo.cacheable,
  483. built: !!module.built,
  484. optional: module.optional,
  485. prefetched: module.prefetched,
  486. chunks: Array.from(module.chunksIterable, chunk => chunk.id),
  487. issuer: module.issuer && module.issuer.identifier(),
  488. issuerId: module.issuer && module.issuer.id,
  489. issuerName:
  490. module.issuer && module.issuer.readableIdentifier(requestShortener),
  491. issuerPath:
  492. module.issuer &&
  493. path.map(module => ({
  494. id: module.id,
  495. identifier: module.identifier(),
  496. name: module.readableIdentifier(requestShortener),
  497. profile: module.profile
  498. })),
  499. profile: module.profile,
  500. failed: !!module.error,
  501. errors: module.errors ? module.errors.length : 0,
  502. warnings: module.warnings ? module.warnings.length : 0
  503. };
  504. if (showModuleAssets) {
  505. obj.assets = Object.keys(module.buildInfo.assets || {});
  506. }
  507. if (showReasons) {
  508. obj.reasons = module.reasons
  509. .sort((a, b) => {
  510. if (a.module && !b.module) return -1;
  511. if (!a.module && b.module) return 1;
  512. if (a.module && b.module) {
  513. const cmp = compareId(a.module.id, b.module.id);
  514. if (cmp) return cmp;
  515. }
  516. if (a.dependency && !b.dependency) return -1;
  517. if (!a.dependency && b.dependency) return 1;
  518. if (a.dependency && b.dependency) {
  519. const cmp = compareLocations(a.dependency.loc, b.dependency.loc);
  520. if (cmp) return cmp;
  521. if (a.dependency.type < b.dependency.type) return -1;
  522. if (a.dependency.type > b.dependency.type) return 1;
  523. }
  524. return 0;
  525. })
  526. .map(reason => {
  527. const obj = {
  528. moduleId: reason.module ? reason.module.id : null,
  529. moduleIdentifier: reason.module
  530. ? reason.module.identifier()
  531. : null,
  532. module: reason.module
  533. ? reason.module.readableIdentifier(requestShortener)
  534. : null,
  535. moduleName: reason.module
  536. ? reason.module.readableIdentifier(requestShortener)
  537. : null,
  538. type: reason.dependency ? reason.dependency.type : null,
  539. explanation: reason.explanation,
  540. userRequest: reason.dependency
  541. ? reason.dependency.userRequest
  542. : null
  543. };
  544. if (reason.dependency) {
  545. const locInfo = formatLocation(reason.dependency.loc);
  546. if (locInfo) {
  547. obj.loc = locInfo;
  548. }
  549. }
  550. return obj;
  551. });
  552. }
  553. if (showUsedExports) {
  554. if (module.used === true) {
  555. obj.usedExports = module.usedExports;
  556. } else if (module.used === false) {
  557. obj.usedExports = false;
  558. }
  559. }
  560. if (showProvidedExports) {
  561. obj.providedExports = Array.isArray(module.buildMeta.providedExports)
  562. ? module.buildMeta.providedExports
  563. : null;
  564. }
  565. if (showOptimizationBailout) {
  566. obj.optimizationBailout = module.optimizationBailout.map(item => {
  567. if (typeof item === "function") return item(requestShortener);
  568. return item;
  569. });
  570. }
  571. if (showDepth) {
  572. obj.depth = module.depth;
  573. }
  574. if (showNestedModules) {
  575. if (module.modules) {
  576. const modules = module.modules;
  577. obj.modules = modules
  578. .sort(sortByField("depth", modules))
  579. .filter(createModuleFilter())
  580. .map(fnModule);
  581. obj.filteredModules = modules.length - obj.modules.length;
  582. obj.modules.sort(sortByField(sortModules, obj.modules));
  583. }
  584. }
  585. if (showSource && module._source) {
  586. obj.source = module._source.source();
  587. }
  588. return obj;
  589. };
  590. if (showChunks) {
  591. obj.chunks = compilation.chunks.map(chunk => {
  592. const parents = new Set();
  593. const children = new Set();
  594. const siblings = new Set();
  595. const childIdByOrder = chunk.getChildIdsByOrders();
  596. for (const chunkGroup of chunk.groupsIterable) {
  597. for (const parentGroup of chunkGroup.parentsIterable) {
  598. for (const chunk of parentGroup.chunks) {
  599. parents.add(chunk.id);
  600. }
  601. }
  602. for (const childGroup of chunkGroup.childrenIterable) {
  603. for (const chunk of childGroup.chunks) {
  604. children.add(chunk.id);
  605. }
  606. }
  607. for (const sibling of chunkGroup.chunks) {
  608. if (sibling !== chunk) siblings.add(sibling.id);
  609. }
  610. }
  611. const obj = {
  612. id: chunk.id,
  613. rendered: chunk.rendered,
  614. initial: chunk.canBeInitial(),
  615. entry: chunk.hasRuntime(),
  616. recorded: chunk.recorded,
  617. reason: chunk.chunkReason,
  618. size: chunk.modulesSize(),
  619. names: chunk.name ? [chunk.name] : [],
  620. files: chunk.files.slice(),
  621. hash: chunk.renderedHash,
  622. siblings: Array.from(siblings).sort(compareId),
  623. parents: Array.from(parents).sort(compareId),
  624. children: Array.from(children).sort(compareId),
  625. childrenByOrder: childIdByOrder
  626. };
  627. if (showChunkModules) {
  628. const modules = chunk.getModules();
  629. obj.modules = modules
  630. .slice()
  631. .sort(sortByField("depth", modules))
  632. .filter(createModuleFilter())
  633. .map(fnModule);
  634. obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length;
  635. obj.modules.sort(sortByField(sortModules, obj.modules));
  636. }
  637. if (showChunkOrigins) {
  638. obj.origins = Array.from(chunk.groupsIterable, g => g.origins)
  639. .reduce((a, b) => a.concat(b), [])
  640. .map(origin => ({
  641. moduleId: origin.module ? origin.module.id : undefined,
  642. module: origin.module ? origin.module.identifier() : "",
  643. moduleIdentifier: origin.module ? origin.module.identifier() : "",
  644. moduleName: origin.module
  645. ? origin.module.readableIdentifier(requestShortener)
  646. : "",
  647. loc: formatLocation(origin.loc),
  648. request: origin.request,
  649. reasons: origin.reasons || []
  650. }))
  651. .sort((a, b) => {
  652. const cmp1 = compareId(a.moduleId, b.moduleId);
  653. if (cmp1) return cmp1;
  654. const cmp2 = compareId(a.loc, b.loc);
  655. if (cmp2) return cmp2;
  656. const cmp3 = compareId(a.request, b.request);
  657. if (cmp3) return cmp3;
  658. return 0;
  659. });
  660. }
  661. return obj;
  662. });
  663. obj.chunks.sort(sortByField(sortChunks, obj.chunks));
  664. }
  665. if (showModules) {
  666. obj.modules = compilation.modules
  667. .slice()
  668. .sort(sortByField("depth", compilation.modules))
  669. .filter(createModuleFilter())
  670. .map(fnModule);
  671. obj.filteredModules = compilation.modules.length - obj.modules.length;
  672. obj.modules.sort(sortByField(sortModules, obj.modules));
  673. }
  674. if (showLogging) {
  675. const util = require("util");
  676. obj.logging = {};
  677. let acceptedTypes;
  678. let collapsedGroups = false;
  679. switch (showLogging) {
  680. case "none":
  681. acceptedTypes = new Set([]);
  682. break;
  683. case "error":
  684. acceptedTypes = new Set([LogType.error]);
  685. break;
  686. case "warn":
  687. acceptedTypes = new Set([LogType.error, LogType.warn]);
  688. break;
  689. case "info":
  690. acceptedTypes = new Set([LogType.error, LogType.warn, LogType.info]);
  691. break;
  692. case true:
  693. case "log":
  694. acceptedTypes = new Set([
  695. LogType.error,
  696. LogType.warn,
  697. LogType.info,
  698. LogType.log,
  699. LogType.group,
  700. LogType.groupEnd,
  701. LogType.groupCollapsed,
  702. LogType.clear
  703. ]);
  704. break;
  705. case "verbose":
  706. acceptedTypes = new Set([
  707. LogType.error,
  708. LogType.warn,
  709. LogType.info,
  710. LogType.log,
  711. LogType.group,
  712. LogType.groupEnd,
  713. LogType.groupCollapsed,
  714. LogType.profile,
  715. LogType.profileEnd,
  716. LogType.time,
  717. LogType.status,
  718. LogType.clear
  719. ]);
  720. collapsedGroups = true;
  721. break;
  722. }
  723. for (const [origin, logEntries] of compilation.logging) {
  724. const debugMode = loggingDebug.some(fn => fn(origin));
  725. let collapseCounter = 0;
  726. let processedLogEntries = logEntries;
  727. if (!debugMode) {
  728. processedLogEntries = processedLogEntries.filter(entry => {
  729. if (!acceptedTypes.has(entry.type)) return false;
  730. if (!collapsedGroups) {
  731. switch (entry.type) {
  732. case LogType.groupCollapsed:
  733. collapseCounter++;
  734. return collapseCounter === 1;
  735. case LogType.group:
  736. if (collapseCounter > 0) collapseCounter++;
  737. return collapseCounter === 0;
  738. case LogType.groupEnd:
  739. if (collapseCounter > 0) {
  740. collapseCounter--;
  741. return false;
  742. }
  743. return true;
  744. default:
  745. return collapseCounter === 0;
  746. }
  747. }
  748. return true;
  749. });
  750. }
  751. processedLogEntries = processedLogEntries.map(entry => {
  752. let message = undefined;
  753. if (entry.type === LogType.time) {
  754. message = `${entry.args[0]}: ${entry.args[1] * 1000 +
  755. entry.args[2] / 1000000}ms`;
  756. } else if (entry.args && entry.args.length > 0) {
  757. message = util.format(entry.args[0], ...entry.args.slice(1));
  758. }
  759. return {
  760. type:
  761. (debugMode || collapsedGroups) &&
  762. entry.type === LogType.groupCollapsed
  763. ? LogType.group
  764. : entry.type,
  765. message,
  766. trace: showLoggingTrace && entry.trace ? entry.trace : undefined
  767. };
  768. });
  769. let name = identifierUtils
  770. .makePathsRelative(context, origin, compilation.cache)
  771. .replace(/\|/g, " ");
  772. if (name in obj.logging) {
  773. let i = 1;
  774. while (`${name}#${i}` in obj.logging) {
  775. i++;
  776. }
  777. name = `${name}#${i}`;
  778. }
  779. obj.logging[name] = {
  780. entries: processedLogEntries,
  781. filteredEntries: logEntries.length - processedLogEntries.length,
  782. debug: debugMode
  783. };
  784. }
  785. }
  786. if (showChildren) {
  787. obj.children = compilation.children.map((child, idx) => {
  788. const childOptions = Stats.getChildOptions(options, idx);
  789. const obj = new Stats(child).toJson(childOptions, forToString);
  790. delete obj.hash;
  791. delete obj.version;
  792. if (child.name) {
  793. obj.name = identifierUtils.makePathsRelative(
  794. context,
  795. child.name,
  796. compilation.cache
  797. );
  798. }
  799. return obj;
  800. });
  801. }
  802. return obj;
  803. }
  804. toString(options) {
  805. if (typeof options === "boolean" || typeof options === "string") {
  806. options = Stats.presetToOptions(options);
  807. } else if (!options) {
  808. options = {};
  809. }
  810. const useColors = optionsOrFallback(options.colors, false);
  811. const obj = this.toJson(options, true);
  812. return Stats.jsonToString(obj, useColors);
  813. }
  814. static jsonToString(obj, useColors) {
  815. const buf = [];
  816. const defaultColors = {
  817. bold: "\u001b[1m",
  818. yellow: "\u001b[1m\u001b[33m",
  819. red: "\u001b[1m\u001b[31m",
  820. green: "\u001b[1m\u001b[32m",
  821. cyan: "\u001b[1m\u001b[36m",
  822. magenta: "\u001b[1m\u001b[35m"
  823. };
  824. const colors = Object.keys(defaultColors).reduce(
  825. (obj, color) => {
  826. obj[color] = str => {
  827. if (useColors) {
  828. buf.push(
  829. useColors === true || useColors[color] === undefined
  830. ? defaultColors[color]
  831. : useColors[color]
  832. );
  833. }
  834. buf.push(str);
  835. if (useColors) {
  836. buf.push("\u001b[39m\u001b[22m");
  837. }
  838. };
  839. return obj;
  840. },
  841. {
  842. normal: str => buf.push(str)
  843. }
  844. );
  845. const coloredTime = time => {
  846. let times = [800, 400, 200, 100];
  847. if (obj.time) {
  848. times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16];
  849. }
  850. if (time < times[3]) colors.normal(`${time}ms`);
  851. else if (time < times[2]) colors.bold(`${time}ms`);
  852. else if (time < times[1]) colors.green(`${time}ms`);
  853. else if (time < times[0]) colors.yellow(`${time}ms`);
  854. else colors.red(`${time}ms`);
  855. };
  856. const newline = () => buf.push("\n");
  857. const getText = (arr, row, col) => {
  858. return arr[row][col].value;
  859. };
  860. const table = (array, align, splitter) => {
  861. const rows = array.length;
  862. const cols = array[0].length;
  863. const colSizes = new Array(cols);
  864. for (let col = 0; col < cols; col++) {
  865. colSizes[col] = 0;
  866. }
  867. for (let row = 0; row < rows; row++) {
  868. for (let col = 0; col < cols; col++) {
  869. const value = `${getText(array, row, col)}`;
  870. if (value.length > colSizes[col]) {
  871. colSizes[col] = value.length;
  872. }
  873. }
  874. }
  875. for (let row = 0; row < rows; row++) {
  876. for (let col = 0; col < cols; col++) {
  877. const format = array[row][col].color;
  878. const value = `${getText(array, row, col)}`;
  879. let l = value.length;
  880. if (align[col] === "l") {
  881. format(value);
  882. }
  883. for (; l < colSizes[col] && col !== cols - 1; l++) {
  884. colors.normal(" ");
  885. }
  886. if (align[col] === "r") {
  887. format(value);
  888. }
  889. if (col + 1 < cols && colSizes[col] !== 0) {
  890. colors.normal(splitter || " ");
  891. }
  892. }
  893. newline();
  894. }
  895. };
  896. const getAssetColor = (asset, defaultColor) => {
  897. if (asset.isOverSizeLimit) {
  898. return colors.yellow;
  899. }
  900. return defaultColor;
  901. };
  902. if (obj.hash) {
  903. colors.normal("Hash: ");
  904. colors.bold(obj.hash);
  905. newline();
  906. }
  907. if (obj.version) {
  908. colors.normal("Version: webpack ");
  909. colors.bold(obj.version);
  910. newline();
  911. }
  912. if (typeof obj.time === "number") {
  913. colors.normal("Time: ");
  914. colors.bold(obj.time);
  915. colors.normal("ms");
  916. newline();
  917. }
  918. if (typeof obj.builtAt === "number") {
  919. const builtAtDate = new Date(obj.builtAt);
  920. let timeZone = undefined;
  921. try {
  922. builtAtDate.toLocaleTimeString();
  923. } catch (err) {
  924. // Force UTC if runtime timezone is unsupported
  925. timeZone = "UTC";
  926. }
  927. colors.normal("Built at: ");
  928. colors.normal(
  929. builtAtDate.toLocaleDateString(undefined, {
  930. day: "2-digit",
  931. month: "2-digit",
  932. year: "numeric",
  933. timeZone
  934. })
  935. );
  936. colors.normal(" ");
  937. colors.bold(builtAtDate.toLocaleTimeString(undefined, { timeZone }));
  938. newline();
  939. }
  940. if (obj.env) {
  941. colors.normal("Environment (--env): ");
  942. colors.bold(JSON.stringify(obj.env, null, 2));
  943. newline();
  944. }
  945. if (obj.publicPath) {
  946. colors.normal("PublicPath: ");
  947. colors.bold(obj.publicPath);
  948. newline();
  949. }
  950. if (obj.assets && obj.assets.length > 0) {
  951. const t = [
  952. [
  953. {
  954. value: "Asset",
  955. color: colors.bold
  956. },
  957. {
  958. value: "Size",
  959. color: colors.bold
  960. },
  961. {
  962. value: "Chunks",
  963. color: colors.bold
  964. },
  965. {
  966. value: "",
  967. color: colors.bold
  968. },
  969. {
  970. value: "",
  971. color: colors.bold
  972. },
  973. {
  974. value: "Chunk Names",
  975. color: colors.bold
  976. }
  977. ]
  978. ];
  979. for (const asset of obj.assets) {
  980. t.push([
  981. {
  982. value: asset.name,
  983. color: getAssetColor(asset, colors.green)
  984. },
  985. {
  986. value: SizeFormatHelpers.formatSize(asset.size),
  987. color: getAssetColor(asset, colors.normal)
  988. },
  989. {
  990. value: asset.chunks.join(", "),
  991. color: colors.bold
  992. },
  993. {
  994. value: [
  995. asset.emitted && "[emitted]",
  996. asset.info.immutable && "[immutable]",
  997. asset.info.development && "[dev]",
  998. asset.info.hotModuleReplacement && "[hmr]"
  999. ]
  1000. .filter(Boolean)
  1001. .join(" "),
  1002. color: colors.green
  1003. },
  1004. {
  1005. value: asset.isOverSizeLimit ? "[big]" : "",
  1006. color: getAssetColor(asset, colors.normal)
  1007. },
  1008. {
  1009. value: asset.chunkNames.join(", "),
  1010. color: colors.normal
  1011. }
  1012. ]);
  1013. }
  1014. table(t, "rrrlll");
  1015. }
  1016. if (obj.filteredAssets > 0) {
  1017. colors.normal(" ");
  1018. if (obj.assets.length > 0) colors.normal("+ ");
  1019. colors.normal(obj.filteredAssets);
  1020. if (obj.assets.length > 0) colors.normal(" hidden");
  1021. colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset");
  1022. newline();
  1023. }
  1024. const processChunkGroups = (namedGroups, prefix) => {
  1025. for (const name of Object.keys(namedGroups)) {
  1026. const cg = namedGroups[name];
  1027. colors.normal(`${prefix} `);
  1028. colors.bold(name);
  1029. if (cg.isOverSizeLimit) {
  1030. colors.normal(" ");
  1031. colors.yellow("[big]");
  1032. }
  1033. colors.normal(" =");
  1034. for (const asset of cg.assets) {
  1035. colors.normal(" ");
  1036. colors.green(asset);
  1037. }
  1038. for (const name of Object.keys(cg.childAssets)) {
  1039. const assets = cg.childAssets[name];
  1040. if (assets && assets.length > 0) {
  1041. colors.normal(" ");
  1042. colors.magenta(`(${name}:`);
  1043. for (const asset of assets) {
  1044. colors.normal(" ");
  1045. colors.green(asset);
  1046. }
  1047. colors.magenta(")");
  1048. }
  1049. }
  1050. newline();
  1051. }
  1052. };
  1053. if (obj.entrypoints) {
  1054. processChunkGroups(obj.entrypoints, "Entrypoint");
  1055. }
  1056. if (obj.namedChunkGroups) {
  1057. let outputChunkGroups = obj.namedChunkGroups;
  1058. if (obj.entrypoints) {
  1059. outputChunkGroups = Object.keys(outputChunkGroups)
  1060. .filter(name => !obj.entrypoints[name])
  1061. .reduce((result, name) => {
  1062. result[name] = obj.namedChunkGroups[name];
  1063. return result;
  1064. }, {});
  1065. }
  1066. processChunkGroups(outputChunkGroups, "Chunk Group");
  1067. }
  1068. const modulesByIdentifier = {};
  1069. if (obj.modules) {
  1070. for (const module of obj.modules) {
  1071. modulesByIdentifier[`$${module.identifier}`] = module;
  1072. }
  1073. } else if (obj.chunks) {
  1074. for (const chunk of obj.chunks) {
  1075. if (chunk.modules) {
  1076. for (const module of chunk.modules) {
  1077. modulesByIdentifier[`$${module.identifier}`] = module;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. const processModuleAttributes = module => {
  1083. colors.normal(" ");
  1084. colors.normal(SizeFormatHelpers.formatSize(module.size));
  1085. if (module.chunks) {
  1086. for (const chunk of module.chunks) {
  1087. colors.normal(" {");
  1088. colors.yellow(chunk);
  1089. colors.normal("}");
  1090. }
  1091. }
  1092. if (typeof module.depth === "number") {
  1093. colors.normal(` [depth ${module.depth}]`);
  1094. }
  1095. if (module.cacheable === false) {
  1096. colors.red(" [not cacheable]");
  1097. }
  1098. if (module.optional) {
  1099. colors.yellow(" [optional]");
  1100. }
  1101. if (module.built) {
  1102. colors.green(" [built]");
  1103. }
  1104. if (module.assets && module.assets.length) {
  1105. colors.magenta(
  1106. ` [${module.assets.length} asset${
  1107. module.assets.length === 1 ? "" : "s"
  1108. }]`
  1109. );
  1110. }
  1111. if (module.prefetched) {
  1112. colors.magenta(" [prefetched]");
  1113. }
  1114. if (module.failed) colors.red(" [failed]");
  1115. if (module.warnings) {
  1116. colors.yellow(
  1117. ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]`
  1118. );
  1119. }
  1120. if (module.errors) {
  1121. colors.red(
  1122. ` [${module.errors} error${module.errors === 1 ? "" : "s"}]`
  1123. );
  1124. }
  1125. };
  1126. const processModuleContent = (module, prefix) => {
  1127. if (Array.isArray(module.providedExports)) {
  1128. colors.normal(prefix);
  1129. if (module.providedExports.length === 0) {
  1130. colors.cyan("[no exports]");
  1131. } else {
  1132. colors.cyan(`[exports: ${module.providedExports.join(", ")}]`);
  1133. }
  1134. newline();
  1135. }
  1136. if (module.usedExports !== undefined) {
  1137. if (module.usedExports !== true) {
  1138. colors.normal(prefix);
  1139. if (module.usedExports === null) {
  1140. colors.cyan("[used exports unknown]");
  1141. } else if (module.usedExports === false) {
  1142. colors.cyan("[no exports used]");
  1143. } else if (
  1144. Array.isArray(module.usedExports) &&
  1145. module.usedExports.length === 0
  1146. ) {
  1147. colors.cyan("[no exports used]");
  1148. } else if (Array.isArray(module.usedExports)) {
  1149. const providedExportsCount = Array.isArray(module.providedExports)
  1150. ? module.providedExports.length
  1151. : null;
  1152. if (
  1153. providedExportsCount !== null &&
  1154. providedExportsCount === module.usedExports.length
  1155. ) {
  1156. colors.cyan("[all exports used]");
  1157. } else {
  1158. colors.cyan(
  1159. `[only some exports used: ${module.usedExports.join(", ")}]`
  1160. );
  1161. }
  1162. }
  1163. newline();
  1164. }
  1165. }
  1166. if (Array.isArray(module.optimizationBailout)) {
  1167. for (const item of module.optimizationBailout) {
  1168. colors.normal(prefix);
  1169. colors.yellow(item);
  1170. newline();
  1171. }
  1172. }
  1173. if (module.reasons) {
  1174. for (const reason of module.reasons) {
  1175. colors.normal(prefix);
  1176. if (reason.type) {
  1177. colors.normal(reason.type);
  1178. colors.normal(" ");
  1179. }
  1180. if (reason.userRequest) {
  1181. colors.cyan(reason.userRequest);
  1182. colors.normal(" ");
  1183. }
  1184. if (reason.moduleId !== null) {
  1185. colors.normal("[");
  1186. colors.normal(reason.moduleId);
  1187. colors.normal("]");
  1188. }
  1189. if (reason.module && reason.module !== reason.moduleId) {
  1190. colors.normal(" ");
  1191. colors.magenta(reason.module);
  1192. }
  1193. if (reason.loc) {
  1194. colors.normal(" ");
  1195. colors.normal(reason.loc);
  1196. }
  1197. if (reason.explanation) {
  1198. colors.normal(" ");
  1199. colors.cyan(reason.explanation);
  1200. }
  1201. newline();
  1202. }
  1203. }
  1204. if (module.profile) {
  1205. colors.normal(prefix);
  1206. let sum = 0;
  1207. if (module.issuerPath) {
  1208. for (const m of module.issuerPath) {
  1209. colors.normal("[");
  1210. colors.normal(m.id);
  1211. colors.normal("] ");
  1212. if (m.profile) {
  1213. const time = (m.profile.factory || 0) + (m.profile.building || 0);
  1214. coloredTime(time);
  1215. sum += time;
  1216. colors.normal(" ");
  1217. }
  1218. colors.normal("-> ");
  1219. }
  1220. }
  1221. for (const key of Object.keys(module.profile)) {
  1222. colors.normal(`${key}:`);
  1223. const time = module.profile[key];
  1224. coloredTime(time);
  1225. colors.normal(" ");
  1226. sum += time;
  1227. }
  1228. colors.normal("= ");
  1229. coloredTime(sum);
  1230. newline();
  1231. }
  1232. if (module.modules) {
  1233. processModulesList(module, prefix + "| ");
  1234. }
  1235. };
  1236. const processModulesList = (obj, prefix) => {
  1237. if (obj.modules) {
  1238. let maxModuleId = 0;
  1239. for (const module of obj.modules) {
  1240. if (typeof module.id === "number") {
  1241. if (maxModuleId < module.id) maxModuleId = module.id;
  1242. }
  1243. }
  1244. let contentPrefix = prefix + " ";
  1245. if (maxModuleId >= 10) contentPrefix += " ";
  1246. if (maxModuleId >= 100) contentPrefix += " ";
  1247. if (maxModuleId >= 1000) contentPrefix += " ";
  1248. for (const module of obj.modules) {
  1249. colors.normal(prefix);
  1250. const name = module.name || module.identifier;
  1251. if (typeof module.id === "string" || typeof module.id === "number") {
  1252. if (typeof module.id === "number") {
  1253. if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" ");
  1254. if (module.id < 100 && maxModuleId >= 100) colors.normal(" ");
  1255. if (module.id < 10 && maxModuleId >= 10) colors.normal(" ");
  1256. } else {
  1257. if (maxModuleId >= 1000) colors.normal(" ");
  1258. if (maxModuleId >= 100) colors.normal(" ");
  1259. if (maxModuleId >= 10) colors.normal(" ");
  1260. }
  1261. if (name !== module.id) {
  1262. colors.normal("[");
  1263. colors.normal(module.id);
  1264. colors.normal("]");
  1265. colors.normal(" ");
  1266. } else {
  1267. colors.normal("[");
  1268. colors.bold(module.id);
  1269. colors.normal("]");
  1270. }
  1271. }
  1272. if (name !== module.id) {
  1273. colors.bold(name);
  1274. }
  1275. processModuleAttributes(module);
  1276. newline();
  1277. processModuleContent(module, contentPrefix);
  1278. }
  1279. if (obj.filteredModules > 0) {
  1280. colors.normal(prefix);
  1281. colors.normal(" ");
  1282. if (obj.modules.length > 0) colors.normal(" + ");
  1283. colors.normal(obj.filteredModules);
  1284. if (obj.modules.length > 0) colors.normal(" hidden");
  1285. colors.normal(obj.filteredModules !== 1 ? " modules" : " module");
  1286. newline();
  1287. }
  1288. }
  1289. };
  1290. if (obj.chunks) {
  1291. for (const chunk of obj.chunks) {
  1292. colors.normal("chunk ");
  1293. if (chunk.id < 1000) colors.normal(" ");
  1294. if (chunk.id < 100) colors.normal(" ");
  1295. if (chunk.id < 10) colors.normal(" ");
  1296. colors.normal("{");
  1297. colors.yellow(chunk.id);
  1298. colors.normal("} ");
  1299. colors.green(chunk.files.join(", "));
  1300. if (chunk.names && chunk.names.length > 0) {
  1301. colors.normal(" (");
  1302. colors.normal(chunk.names.join(", "));
  1303. colors.normal(")");
  1304. }
  1305. colors.normal(" ");
  1306. colors.normal(SizeFormatHelpers.formatSize(chunk.size));
  1307. for (const id of chunk.parents) {
  1308. colors.normal(" <{");
  1309. colors.yellow(id);
  1310. colors.normal("}>");
  1311. }
  1312. for (const id of chunk.siblings) {
  1313. colors.normal(" ={");
  1314. colors.yellow(id);
  1315. colors.normal("}=");
  1316. }
  1317. for (const id of chunk.children) {
  1318. colors.normal(" >{");
  1319. colors.yellow(id);
  1320. colors.normal("}<");
  1321. }
  1322. if (chunk.childrenByOrder) {
  1323. for (const name of Object.keys(chunk.childrenByOrder)) {
  1324. const children = chunk.childrenByOrder[name];
  1325. colors.normal(" ");
  1326. colors.magenta(`(${name}:`);
  1327. for (const id of children) {
  1328. colors.normal(" {");
  1329. colors.yellow(id);
  1330. colors.normal("}");
  1331. }
  1332. colors.magenta(")");
  1333. }
  1334. }
  1335. if (chunk.entry) {
  1336. colors.yellow(" [entry]");
  1337. } else if (chunk.initial) {
  1338. colors.yellow(" [initial]");
  1339. }
  1340. if (chunk.rendered) {
  1341. colors.green(" [rendered]");
  1342. }
  1343. if (chunk.recorded) {
  1344. colors.green(" [recorded]");
  1345. }
  1346. if (chunk.reason) {
  1347. colors.yellow(` ${chunk.reason}`);
  1348. }
  1349. newline();
  1350. if (chunk.origins) {
  1351. for (const origin of chunk.origins) {
  1352. colors.normal(" > ");
  1353. if (origin.reasons && origin.reasons.length) {
  1354. colors.yellow(origin.reasons.join(" "));
  1355. colors.normal(" ");
  1356. }
  1357. if (origin.request) {
  1358. colors.normal(origin.request);
  1359. colors.normal(" ");
  1360. }
  1361. if (origin.module) {
  1362. colors.normal("[");
  1363. colors.normal(origin.moduleId);
  1364. colors.normal("] ");
  1365. const module = modulesByIdentifier[`$${origin.module}`];
  1366. if (module) {
  1367. colors.bold(module.name);
  1368. colors.normal(" ");
  1369. }
  1370. }
  1371. if (origin.loc) {
  1372. colors.normal(origin.loc);
  1373. }
  1374. newline();
  1375. }
  1376. }
  1377. processModulesList(chunk, " ");
  1378. }
  1379. }
  1380. processModulesList(obj, "");
  1381. if (obj.logging) {
  1382. for (const origin of Object.keys(obj.logging)) {
  1383. const logData = obj.logging[origin];
  1384. if (logData.entries.length > 0) {
  1385. newline();
  1386. if (logData.debug) {
  1387. colors.red("DEBUG ");
  1388. }
  1389. colors.bold("LOG from " + origin);
  1390. newline();
  1391. let indent = "";
  1392. for (const entry of logData.entries) {
  1393. let color = colors.normal;
  1394. let prefix = " ";
  1395. switch (entry.type) {
  1396. case LogType.clear:
  1397. colors.normal(`${indent}-------`);
  1398. newline();
  1399. continue;
  1400. case LogType.error:
  1401. color = colors.red;
  1402. prefix = "<e> ";
  1403. break;
  1404. case LogType.warn:
  1405. color = colors.yellow;
  1406. prefix = "<w> ";
  1407. break;
  1408. case LogType.info:
  1409. color = colors.green;
  1410. prefix = "<i> ";
  1411. break;
  1412. case LogType.log:
  1413. color = colors.bold;
  1414. break;
  1415. case LogType.trace:
  1416. case LogType.debug:
  1417. color = colors.normal;
  1418. break;
  1419. case LogType.status:
  1420. color = colors.magenta;
  1421. prefix = "<s> ";
  1422. break;
  1423. case LogType.profile:
  1424. color = colors.magenta;
  1425. prefix = "<p> ";
  1426. break;
  1427. case LogType.profileEnd:
  1428. color = colors.magenta;
  1429. prefix = "</p> ";
  1430. break;
  1431. case LogType.time:
  1432. color = colors.magenta;
  1433. prefix = "<t> ";
  1434. break;
  1435. case LogType.group:
  1436. color = colors.cyan;
  1437. prefix = "<-> ";
  1438. break;
  1439. case LogType.groupCollapsed:
  1440. color = colors.cyan;
  1441. prefix = "<+> ";
  1442. break;
  1443. case LogType.groupEnd:
  1444. if (indent.length >= 2)
  1445. indent = indent.slice(0, indent.length - 2);
  1446. continue;
  1447. }
  1448. if (entry.message) {
  1449. for (const line of entry.message.split("\n")) {
  1450. colors.normal(`${indent}${prefix}`);
  1451. color(line);
  1452. newline();
  1453. }
  1454. }
  1455. if (entry.trace) {
  1456. for (const line of entry.trace) {
  1457. colors.normal(`${indent}| ${line}`);
  1458. newline();
  1459. }
  1460. }
  1461. switch (entry.type) {
  1462. case LogType.group:
  1463. indent += " ";
  1464. break;
  1465. }
  1466. }
  1467. if (logData.filteredEntries) {
  1468. colors.normal(`+ ${logData.filteredEntries} hidden lines`);
  1469. newline();
  1470. }
  1471. }
  1472. }
  1473. }
  1474. if (obj._showWarnings && obj.warnings) {
  1475. for (const warning of obj.warnings) {
  1476. newline();
  1477. colors.yellow(`WARNING in ${warning}`);
  1478. newline();
  1479. }
  1480. }
  1481. if (obj._showErrors && obj.errors) {
  1482. for (const error of obj.errors) {
  1483. newline();
  1484. colors.red(`ERROR in ${error}`);
  1485. newline();
  1486. }
  1487. }
  1488. if (obj.children) {
  1489. for (const child of obj.children) {
  1490. const childString = Stats.jsonToString(child, useColors);
  1491. if (childString) {
  1492. if (child.name) {
  1493. colors.normal("Child ");
  1494. colors.bold(child.name);
  1495. colors.normal(":");
  1496. } else {
  1497. colors.normal("Child");
  1498. }
  1499. newline();
  1500. buf.push(" ");
  1501. buf.push(childString.replace(/\n/g, "\n "));
  1502. newline();
  1503. }
  1504. }
  1505. }
  1506. if (obj.needAdditionalPass) {
  1507. colors.yellow(
  1508. "Compilation needs an additional pass and will compile again."
  1509. );
  1510. }
  1511. while (buf[buf.length - 1] === "\n") {
  1512. buf.pop();
  1513. }
  1514. return buf.join("");
  1515. }
  1516. static presetToOptions(name) {
  1517. // Accepted values: none, errors-only, minimal, normal, detailed, verbose
  1518. // Any other falsy value will behave as 'none', truthy values as 'normal'
  1519. const pn =
  1520. (typeof name === "string" && name.toLowerCase()) || name || "none";
  1521. switch (pn) {
  1522. case "none":
  1523. return {
  1524. all: false
  1525. };
  1526. case "verbose":
  1527. return {
  1528. entrypoints: true,
  1529. chunkGroups: true,
  1530. modules: false,
  1531. chunks: true,
  1532. chunkModules: true,
  1533. chunkOrigins: true,
  1534. depth: true,
  1535. env: true,
  1536. reasons: true,
  1537. usedExports: true,
  1538. providedExports: true,
  1539. optimizationBailout: true,
  1540. errorDetails: true,
  1541. publicPath: true,
  1542. logging: "verbose",
  1543. exclude: false,
  1544. maxModules: Infinity
  1545. };
  1546. case "detailed":
  1547. return {
  1548. entrypoints: true,
  1549. chunkGroups: true,
  1550. chunks: true,
  1551. chunkModules: false,
  1552. chunkOrigins: true,
  1553. depth: true,
  1554. usedExports: true,
  1555. providedExports: true,
  1556. optimizationBailout: true,
  1557. errorDetails: true,
  1558. publicPath: true,
  1559. logging: true,
  1560. exclude: false,
  1561. maxModules: Infinity
  1562. };
  1563. case "minimal":
  1564. return {
  1565. all: false,
  1566. modules: true,
  1567. maxModules: 0,
  1568. errors: true,
  1569. warnings: true,
  1570. logging: "warn"
  1571. };
  1572. case "errors-only":
  1573. return {
  1574. all: false,
  1575. errors: true,
  1576. moduleTrace: true,
  1577. logging: "error"
  1578. };
  1579. case "errors-warnings":
  1580. return {
  1581. all: false,
  1582. errors: true,
  1583. warnings: true,
  1584. logging: "warn"
  1585. };
  1586. default:
  1587. return {};
  1588. }
  1589. }
  1590. static getChildOptions(options, idx) {
  1591. let innerOptions;
  1592. if (Array.isArray(options.children)) {
  1593. if (idx < options.children.length) {
  1594. innerOptions = options.children[idx];
  1595. }
  1596. } else if (typeof options.children === "object" && options.children) {
  1597. innerOptions = options.children;
  1598. }
  1599. if (typeof innerOptions === "boolean" || typeof innerOptions === "string") {
  1600. innerOptions = Stats.presetToOptions(innerOptions);
  1601. }
  1602. if (!innerOptions) {
  1603. return options;
  1604. }
  1605. const childOptions = Object.assign({}, options);
  1606. delete childOptions.children; // do not inherit children
  1607. return Object.assign(childOptions, innerOptions);
  1608. }
  1609. }
  1610. module.exports = Stats;