DefaultStatsFactoryPlugin.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const { WEBPACK_MODULE_TYPE_RUNTIME } = require("../ModuleTypeConstants");
  8. const ModuleDependency = require("../dependencies/ModuleDependency");
  9. const formatLocation = require("../formatLocation");
  10. const { LogType } = require("../logging/Logger");
  11. const AggressiveSplittingPlugin = require("../optimize/AggressiveSplittingPlugin");
  12. const SizeLimitsPlugin = require("../performance/SizeLimitsPlugin");
  13. const { countIterable } = require("../util/IterableHelpers");
  14. const {
  15. compareLocations,
  16. compareChunksById,
  17. compareNumbers,
  18. compareIds,
  19. concatComparators,
  20. compareSelect,
  21. compareModulesByIdentifier
  22. } = require("../util/comparators");
  23. const { makePathsRelative, parseResource } = require("../util/identifier");
  24. /** @typedef {import("webpack-sources").Source} Source */
  25. /** @typedef {import("../Chunk")} Chunk */
  26. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  27. /** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */
  28. /** @typedef {import("../Compilation")} Compilation */
  29. /** @typedef {import("../Compilation").Asset} Asset */
  30. /** @typedef {import("../Compilation").AssetInfo} AssetInfo */
  31. /** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
  32. /** @typedef {import("../Compiler")} Compiler */
  33. /** @typedef {import("../Dependency")} Dependency */
  34. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  35. /** @typedef {import("../Module")} Module */
  36. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  37. /** @typedef {import("../ModuleProfile")} ModuleProfile */
  38. /** @typedef {import("../RequestShortener")} RequestShortener */
  39. /** @typedef {import("../WebpackError")} WebpackError */
  40. /** @template T @typedef {import("../util/comparators").Comparator<T>} Comparator<T> */
  41. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  42. /** @typedef {import("../util/smartGrouping").GroupConfig<any, object>} GroupConfig */
  43. /** @typedef {import("./StatsFactory")} StatsFactory */
  44. /** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */
  45. /** @typedef {KnownStatsCompilation & Record<string, any>} StatsCompilation */
  46. /**
  47. * @typedef {object} KnownStatsCompilation
  48. * @property {any=} env
  49. * @property {string=} name
  50. * @property {string=} hash
  51. * @property {string=} version
  52. * @property {number=} time
  53. * @property {number=} builtAt
  54. * @property {boolean=} needAdditionalPass
  55. * @property {string=} publicPath
  56. * @property {string=} outputPath
  57. * @property {Record<string, string[]>=} assetsByChunkName
  58. * @property {StatsAsset[]=} assets
  59. * @property {number=} filteredAssets
  60. * @property {StatsChunk[]=} chunks
  61. * @property {StatsModule[]=} modules
  62. * @property {number=} filteredModules
  63. * @property {Record<string, StatsChunkGroup>=} entrypoints
  64. * @property {Record<string, StatsChunkGroup>=} namedChunkGroups
  65. * @property {StatsError[]=} errors
  66. * @property {number=} errorsCount
  67. * @property {StatsError[]=} warnings
  68. * @property {number=} warningsCount
  69. * @property {StatsCompilation[]=} children
  70. * @property {Record<string, StatsLogging>=} logging
  71. */
  72. /** @typedef {KnownStatsLogging & Record<string, any>} StatsLogging */
  73. /**
  74. * @typedef {object} KnownStatsLogging
  75. * @property {StatsLoggingEntry[]} entries
  76. * @property {number} filteredEntries
  77. * @property {boolean} debug
  78. */
  79. /** @typedef {KnownStatsLoggingEntry & Record<string, any>} StatsLoggingEntry */
  80. /**
  81. * @typedef {object} KnownStatsLoggingEntry
  82. * @property {string} type
  83. * @property {string} message
  84. * @property {string[]=} trace
  85. * @property {StatsLoggingEntry[]=} children
  86. * @property {any[]=} args
  87. * @property {number=} time
  88. */
  89. /** @typedef {KnownStatsAsset & Record<string, any>} StatsAsset */
  90. /**
  91. * @typedef {object} KnownStatsAsset
  92. * @property {string} type
  93. * @property {string} name
  94. * @property {AssetInfo} info
  95. * @property {number} size
  96. * @property {boolean} emitted
  97. * @property {boolean} comparedForEmit
  98. * @property {boolean} cached
  99. * @property {StatsAsset[]=} related
  100. * @property {(string|number)[]=} chunkNames
  101. * @property {(string|number)[]=} chunkIdHints
  102. * @property {(string|number)[]=} chunks
  103. * @property {(string|number)[]=} auxiliaryChunkNames
  104. * @property {(string|number)[]=} auxiliaryChunks
  105. * @property {(string|number)[]=} auxiliaryChunkIdHints
  106. * @property {number=} filteredRelated
  107. * @property {boolean=} isOverSizeLimit
  108. */
  109. /** @typedef {KnownStatsChunkGroup & Record<string, any>} StatsChunkGroup */
  110. /**
  111. * @typedef {object} KnownStatsChunkGroup
  112. * @property {string=} name
  113. * @property {(string|number)[]=} chunks
  114. * @property {({ name: string, size?: number })[]=} assets
  115. * @property {number=} filteredAssets
  116. * @property {number=} assetsSize
  117. * @property {({ name: string, size?: number })[]=} auxiliaryAssets
  118. * @property {number=} filteredAuxiliaryAssets
  119. * @property {number=} auxiliaryAssetsSize
  120. * @property {{ [x: string]: StatsChunkGroup[] }=} children
  121. * @property {{ [x: string]: string[] }=} childAssets
  122. * @property {boolean=} isOverSizeLimit
  123. */
  124. /** @typedef {KnownStatsModule & Record<string, any>} StatsModule */
  125. /**
  126. * @typedef {object} KnownStatsModule
  127. * @property {string=} type
  128. * @property {string=} moduleType
  129. * @property {string=} layer
  130. * @property {string=} identifier
  131. * @property {string=} name
  132. * @property {string=} nameForCondition
  133. * @property {number=} index
  134. * @property {number=} preOrderIndex
  135. * @property {number=} index2
  136. * @property {number=} postOrderIndex
  137. * @property {number=} size
  138. * @property {{[x: string]: number}=} sizes
  139. * @property {boolean=} cacheable
  140. * @property {boolean=} built
  141. * @property {boolean=} codeGenerated
  142. * @property {boolean=} buildTimeExecuted
  143. * @property {boolean=} cached
  144. * @property {boolean=} optional
  145. * @property {boolean=} orphan
  146. * @property {string|number=} id
  147. * @property {string|number=} issuerId
  148. * @property {(string|number)[]=} chunks
  149. * @property {(string|number)[]=} assets
  150. * @property {boolean=} dependent
  151. * @property {string=} issuer
  152. * @property {string=} issuerName
  153. * @property {StatsModuleIssuer[]=} issuerPath
  154. * @property {boolean=} failed
  155. * @property {number=} errors
  156. * @property {number=} warnings
  157. * @property {StatsProfile=} profile
  158. * @property {StatsModuleReason[]=} reasons
  159. * @property {(boolean | string[])=} usedExports
  160. * @property {string[]=} providedExports
  161. * @property {string[]=} optimizationBailout
  162. * @property {number=} depth
  163. * @property {StatsModule[]=} modules
  164. * @property {number=} filteredModules
  165. * @property {ReturnType<Source["source"]>=} source
  166. */
  167. /** @typedef {KnownStatsProfile & Record<string, any>} StatsProfile */
  168. /**
  169. * @typedef {object} KnownStatsProfile
  170. * @property {number} total
  171. * @property {number} resolving
  172. * @property {number} restoring
  173. * @property {number} building
  174. * @property {number} integration
  175. * @property {number} storing
  176. * @property {number} additionalResolving
  177. * @property {number} additionalIntegration
  178. * @property {number} factory
  179. * @property {number} dependencies
  180. */
  181. /** @typedef {KnownStatsModuleIssuer & Record<string, any>} StatsModuleIssuer */
  182. /**
  183. * @typedef {object} KnownStatsModuleIssuer
  184. * @property {string=} identifier
  185. * @property {string=} name
  186. * @property {(string|number)=} id
  187. * @property {StatsProfile=} profile
  188. */
  189. /** @typedef {KnownStatsModuleReason & Record<string, any>} StatsModuleReason */
  190. /**
  191. * @typedef {object} KnownStatsModuleReason
  192. * @property {string=} moduleIdentifier
  193. * @property {string=} module
  194. * @property {string=} moduleName
  195. * @property {string=} resolvedModuleIdentifier
  196. * @property {string=} resolvedModule
  197. * @property {string=} type
  198. * @property {boolean} active
  199. * @property {string=} explanation
  200. * @property {string=} userRequest
  201. * @property {string=} loc
  202. * @property {(string|number)=} moduleId
  203. * @property {(string|number)=} resolvedModuleId
  204. */
  205. /** @typedef {KnownStatsChunk & Record<string, any>} StatsChunk */
  206. /**
  207. * @typedef {object} KnownStatsChunk
  208. * @property {boolean} rendered
  209. * @property {boolean} initial
  210. * @property {boolean} entry
  211. * @property {boolean} recorded
  212. * @property {string=} reason
  213. * @property {number} size
  214. * @property {Record<string, number>=} sizes
  215. * @property {string[]=} names
  216. * @property {string[]=} idHints
  217. * @property {string[]=} runtime
  218. * @property {string[]=} files
  219. * @property {string[]=} auxiliaryFiles
  220. * @property {string} hash
  221. * @property {Record<string, (string|number)[]>=} childrenByOrder
  222. * @property {(string|number)=} id
  223. * @property {(string|number)[]=} siblings
  224. * @property {(string|number)[]=} parents
  225. * @property {(string|number)[]=} children
  226. * @property {StatsModule[]=} modules
  227. * @property {number=} filteredModules
  228. * @property {StatsChunkOrigin[]=} origins
  229. */
  230. /** @typedef {KnownStatsChunkOrigin & Record<string, any>} StatsChunkOrigin */
  231. /**
  232. * @typedef {object} KnownStatsChunkOrigin
  233. * @property {string=} module
  234. * @property {string=} moduleIdentifier
  235. * @property {string=} moduleName
  236. * @property {string=} loc
  237. * @property {string=} request
  238. * @property {(string|number)=} moduleId
  239. */
  240. /** @typedef {KnownStatsModuleTraceItem & Record<string, any>} StatsModuleTraceItem */
  241. /**
  242. * @typedef {object} KnownStatsModuleTraceItem
  243. * @property {string=} originIdentifier
  244. * @property {string=} originName
  245. * @property {string=} moduleIdentifier
  246. * @property {string=} moduleName
  247. * @property {StatsModuleTraceDependency[]=} dependencies
  248. * @property {(string|number)=} originId
  249. * @property {(string|number)=} moduleId
  250. */
  251. /** @typedef {KnownStatsModuleTraceDependency & Record<string, any>} StatsModuleTraceDependency */
  252. /**
  253. * @typedef {object} KnownStatsModuleTraceDependency
  254. * @property {string=} loc
  255. */
  256. /** @typedef {KnownStatsError & Record<string, any>} StatsError */
  257. /**
  258. * @typedef {object} KnownStatsError
  259. * @property {string} message
  260. * @property {string=} chunkName
  261. * @property {boolean=} chunkEntry
  262. * @property {boolean=} chunkInitial
  263. * @property {string=} file
  264. * @property {string=} moduleIdentifier
  265. * @property {string=} moduleName
  266. * @property {string=} loc
  267. * @property {string|number=} chunkId
  268. * @property {string|number=} moduleId
  269. * @property {StatsModuleTraceItem[]=} moduleTrace
  270. * @property {any=} details
  271. * @property {string=} stack
  272. */
  273. /** @typedef {Asset & { type: string, related: PreprocessedAsset[] }} PreprocessedAsset */
  274. /**
  275. * @template T
  276. * @template O
  277. * @typedef {Record<string, (object: O, data: T, context: StatsFactoryContext, options: NormalizedStatsOptions, factory: StatsFactory) => void>} ExtractorsByOption
  278. */
  279. /**
  280. * @typedef {object} SimpleExtractors
  281. * @property {ExtractorsByOption<Compilation, StatsCompilation>} compilation
  282. * @property {ExtractorsByOption<PreprocessedAsset, StatsAsset>} asset
  283. * @property {ExtractorsByOption<PreprocessedAsset, StatsAsset>} asset$visible
  284. * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }, StatsChunkGroup>} chunkGroup
  285. * @property {ExtractorsByOption<Module, StatsModule>} module
  286. * @property {ExtractorsByOption<Module, StatsModule>} module$visible
  287. * @property {ExtractorsByOption<Module, StatsModuleIssuer>} moduleIssuer
  288. * @property {ExtractorsByOption<ModuleProfile, StatsProfile>} profile
  289. * @property {ExtractorsByOption<ModuleGraphConnection, StatsModuleReason>} moduleReason
  290. * @property {ExtractorsByOption<Chunk, StatsChunk>} chunk
  291. * @property {ExtractorsByOption<OriginRecord, StatsChunkOrigin>} chunkOrigin
  292. * @property {ExtractorsByOption<WebpackError, StatsError>} error
  293. * @property {ExtractorsByOption<WebpackError, StatsError>} warning
  294. * @property {ExtractorsByOption<{ origin: Module, module: Module }, StatsModuleTraceItem>} moduleTraceItem
  295. * @property {ExtractorsByOption<Dependency, StatsModuleTraceDependency>} moduleTraceDependency
  296. */
  297. /**
  298. * @template T
  299. * @template I
  300. * @param {Iterable<T>} items items to select from
  301. * @param {function(T): Iterable<I>} selector selector function to select values from item
  302. * @returns {I[]} array of values
  303. */
  304. const uniqueArray = (items, selector) => {
  305. /** @type {Set<I>} */
  306. const set = new Set();
  307. for (const item of items) {
  308. for (const i of selector(item)) {
  309. set.add(i);
  310. }
  311. }
  312. return Array.from(set);
  313. };
  314. /**
  315. * @template T
  316. * @template I
  317. * @param {Iterable<T>} items items to select from
  318. * @param {function(T): Iterable<I>} selector selector function to select values from item
  319. * @param {Comparator<I>} comparator comparator function
  320. * @returns {I[]} array of values
  321. */
  322. const uniqueOrderedArray = (items, selector, comparator) => {
  323. return uniqueArray(items, selector).sort(comparator);
  324. };
  325. /** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues<T, R> */
  326. /**
  327. * @template T
  328. * @template R
  329. * @param {T} obj object to be mapped
  330. * @param {function(T[keyof T], keyof T): R} fn mapping function
  331. * @returns {MappedValues<T, R>} mapped object
  332. */
  333. const mapObject = (obj, fn) => {
  334. const newObj = Object.create(null);
  335. for (const key of Object.keys(obj)) {
  336. newObj[key] = fn(obj[key], /** @type {keyof T} */ (key));
  337. }
  338. return newObj;
  339. };
  340. /**
  341. * @param {Compilation} compilation the compilation
  342. * @param {function(Compilation, string): any[]} getItems get items
  343. * @returns {number} total number
  344. */
  345. const countWithChildren = (compilation, getItems) => {
  346. let count = getItems(compilation, "").length;
  347. for (const child of compilation.children) {
  348. count += countWithChildren(child, (c, type) =>
  349. getItems(c, `.children[].compilation${type}`)
  350. );
  351. }
  352. return count;
  353. };
  354. /** @type {ExtractorsByOption<WebpackError | string, StatsError>} */
  355. const EXTRACT_ERROR = {
  356. _: (object, error, context, { requestShortener }) => {
  357. // TODO webpack 6 disallow strings in the errors/warnings list
  358. if (typeof error === "string") {
  359. object.message = error;
  360. } else {
  361. if (error.chunk) {
  362. object.chunkName = error.chunk.name;
  363. object.chunkEntry = error.chunk.hasRuntime();
  364. object.chunkInitial = error.chunk.canBeInitial();
  365. }
  366. if (error.file) {
  367. object.file = error.file;
  368. }
  369. if (error.module) {
  370. object.moduleIdentifier = error.module.identifier();
  371. object.moduleName = error.module.readableIdentifier(requestShortener);
  372. }
  373. if (error.loc) {
  374. object.loc = formatLocation(error.loc);
  375. }
  376. object.message = error.message;
  377. }
  378. },
  379. ids: (object, error, { compilation: { chunkGraph } }) => {
  380. if (typeof error !== "string") {
  381. if (error.chunk) {
  382. object.chunkId = error.chunk.id;
  383. }
  384. if (error.module) {
  385. object.moduleId = chunkGraph.getModuleId(error.module);
  386. }
  387. }
  388. },
  389. moduleTrace: (object, error, context, options, factory) => {
  390. if (typeof error !== "string" && error.module) {
  391. const {
  392. type,
  393. compilation: { moduleGraph }
  394. } = context;
  395. /** @type {Set<Module>} */
  396. const visitedModules = new Set();
  397. const moduleTrace = [];
  398. let current = error.module;
  399. while (current) {
  400. if (visitedModules.has(current)) break; // circular (technically impossible, but how knows)
  401. visitedModules.add(current);
  402. const origin = moduleGraph.getIssuer(current);
  403. if (!origin) break;
  404. moduleTrace.push({ origin, module: current });
  405. current = origin;
  406. }
  407. object.moduleTrace = factory.create(
  408. `${type}.moduleTrace`,
  409. moduleTrace,
  410. context
  411. );
  412. }
  413. },
  414. errorDetails: (
  415. object,
  416. error,
  417. { type, compilation, cachedGetErrors, cachedGetWarnings },
  418. { errorDetails }
  419. ) => {
  420. if (
  421. typeof error !== "string" &&
  422. (errorDetails === true ||
  423. (type.endsWith(".error") && cachedGetErrors(compilation).length < 3))
  424. ) {
  425. object.details = error.details;
  426. }
  427. },
  428. errorStack: (object, error) => {
  429. if (typeof error !== "string") {
  430. object.stack = error.stack;
  431. }
  432. }
  433. };
  434. /** @type {SimpleExtractors} */
  435. const SIMPLE_EXTRACTORS = {
  436. compilation: {
  437. _: (object, compilation, context, options) => {
  438. if (!context.makePathsRelative) {
  439. context.makePathsRelative = makePathsRelative.bindContextCache(
  440. compilation.compiler.context,
  441. compilation.compiler.root
  442. );
  443. }
  444. if (!context.cachedGetErrors) {
  445. const map = new WeakMap();
  446. context.cachedGetErrors = compilation => {
  447. return (
  448. map.get(compilation) ||
  449. (errors => (map.set(compilation, errors), errors))(
  450. compilation.getErrors()
  451. )
  452. );
  453. };
  454. }
  455. if (!context.cachedGetWarnings) {
  456. const map = new WeakMap();
  457. context.cachedGetWarnings = compilation => {
  458. return (
  459. map.get(compilation) ||
  460. (warnings => (map.set(compilation, warnings), warnings))(
  461. compilation.getWarnings()
  462. )
  463. );
  464. };
  465. }
  466. if (compilation.name) {
  467. object.name = compilation.name;
  468. }
  469. if (compilation.needAdditionalPass) {
  470. object.needAdditionalPass = true;
  471. }
  472. const { logging, loggingDebug, loggingTrace } = options;
  473. if (logging || (loggingDebug && loggingDebug.length > 0)) {
  474. const util = require("util");
  475. object.logging = {};
  476. let acceptedTypes;
  477. let collapsedGroups = false;
  478. switch (logging) {
  479. default:
  480. acceptedTypes = new Set();
  481. break;
  482. case "error":
  483. acceptedTypes = new Set([LogType.error]);
  484. break;
  485. case "warn":
  486. acceptedTypes = new Set([LogType.error, LogType.warn]);
  487. break;
  488. case "info":
  489. acceptedTypes = new Set([
  490. LogType.error,
  491. LogType.warn,
  492. LogType.info
  493. ]);
  494. break;
  495. case "log":
  496. acceptedTypes = new Set([
  497. LogType.error,
  498. LogType.warn,
  499. LogType.info,
  500. LogType.log,
  501. LogType.group,
  502. LogType.groupEnd,
  503. LogType.groupCollapsed,
  504. LogType.clear
  505. ]);
  506. break;
  507. case "verbose":
  508. acceptedTypes = new Set([
  509. LogType.error,
  510. LogType.warn,
  511. LogType.info,
  512. LogType.log,
  513. LogType.group,
  514. LogType.groupEnd,
  515. LogType.groupCollapsed,
  516. LogType.profile,
  517. LogType.profileEnd,
  518. LogType.time,
  519. LogType.status,
  520. LogType.clear
  521. ]);
  522. collapsedGroups = true;
  523. break;
  524. }
  525. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  526. options.context,
  527. compilation.compiler.root
  528. );
  529. let depthInCollapsedGroup = 0;
  530. for (const [origin, logEntries] of compilation.logging) {
  531. const debugMode = loggingDebug.some(fn => fn(origin));
  532. if (logging === false && !debugMode) continue;
  533. /** @type {KnownStatsLoggingEntry[]} */
  534. const groupStack = [];
  535. /** @type {KnownStatsLoggingEntry[]} */
  536. const rootList = [];
  537. let currentList = rootList;
  538. let processedLogEntries = 0;
  539. for (const entry of logEntries) {
  540. let type = entry.type;
  541. if (!debugMode && !acceptedTypes.has(type)) continue;
  542. // Expand groups in verbose and debug modes
  543. if (
  544. type === LogType.groupCollapsed &&
  545. (debugMode || collapsedGroups)
  546. )
  547. type = LogType.group;
  548. if (depthInCollapsedGroup === 0) {
  549. processedLogEntries++;
  550. }
  551. if (type === LogType.groupEnd) {
  552. groupStack.pop();
  553. if (groupStack.length > 0) {
  554. currentList = groupStack[groupStack.length - 1].children;
  555. } else {
  556. currentList = rootList;
  557. }
  558. if (depthInCollapsedGroup > 0) depthInCollapsedGroup--;
  559. continue;
  560. }
  561. let message = undefined;
  562. if (entry.type === LogType.time) {
  563. message = `${entry.args[0]}: ${
  564. entry.args[1] * 1000 + entry.args[2] / 1000000
  565. } ms`;
  566. } else if (entry.args && entry.args.length > 0) {
  567. message = util.format(entry.args[0], ...entry.args.slice(1));
  568. }
  569. /** @type {KnownStatsLoggingEntry} */
  570. const newEntry = {
  571. ...entry,
  572. type,
  573. message,
  574. trace: loggingTrace ? entry.trace : undefined,
  575. children:
  576. type === LogType.group || type === LogType.groupCollapsed
  577. ? []
  578. : undefined
  579. };
  580. currentList.push(newEntry);
  581. if (newEntry.children) {
  582. groupStack.push(newEntry);
  583. currentList = newEntry.children;
  584. if (depthInCollapsedGroup > 0) {
  585. depthInCollapsedGroup++;
  586. } else if (type === LogType.groupCollapsed) {
  587. depthInCollapsedGroup = 1;
  588. }
  589. }
  590. }
  591. let name = cachedMakePathsRelative(origin).replace(/\|/g, " ");
  592. if (name in object.logging) {
  593. let i = 1;
  594. while (`${name}#${i}` in object.logging) {
  595. i++;
  596. }
  597. name = `${name}#${i}`;
  598. }
  599. object.logging[name] = {
  600. entries: rootList,
  601. filteredEntries: logEntries.length - processedLogEntries,
  602. debug: debugMode
  603. };
  604. }
  605. }
  606. },
  607. hash: (object, compilation) => {
  608. object.hash = compilation.hash;
  609. },
  610. version: object => {
  611. object.version = require("../../package.json").version;
  612. },
  613. env: (object, compilation, context, { _env }) => {
  614. object.env = _env;
  615. },
  616. timings: (object, compilation) => {
  617. object.time = compilation.endTime - compilation.startTime;
  618. },
  619. builtAt: (object, compilation) => {
  620. object.builtAt = compilation.endTime;
  621. },
  622. publicPath: (object, compilation) => {
  623. object.publicPath = compilation.getPath(
  624. compilation.outputOptions.publicPath
  625. );
  626. },
  627. outputPath: (object, compilation) => {
  628. object.outputPath = compilation.outputOptions.path;
  629. },
  630. assets: (object, compilation, context, options, factory) => {
  631. const { type } = context;
  632. /** @type {Map<string, Chunk[]>} */
  633. const compilationFileToChunks = new Map();
  634. /** @type {Map<string, Chunk[]>} */
  635. const compilationAuxiliaryFileToChunks = new Map();
  636. for (const chunk of compilation.chunks) {
  637. for (const file of chunk.files) {
  638. let array = compilationFileToChunks.get(file);
  639. if (array === undefined) {
  640. array = [];
  641. compilationFileToChunks.set(file, array);
  642. }
  643. array.push(chunk);
  644. }
  645. for (const file of chunk.auxiliaryFiles) {
  646. let array = compilationAuxiliaryFileToChunks.get(file);
  647. if (array === undefined) {
  648. array = [];
  649. compilationAuxiliaryFileToChunks.set(file, array);
  650. }
  651. array.push(chunk);
  652. }
  653. }
  654. /** @type {Map<string, PreprocessedAsset>} */
  655. const assetMap = new Map();
  656. /** @type {Set<PreprocessedAsset>} */
  657. const assets = new Set();
  658. for (const asset of compilation.getAssets()) {
  659. /** @type {PreprocessedAsset} */
  660. const item = {
  661. ...asset,
  662. type: "asset",
  663. related: undefined
  664. };
  665. assets.add(item);
  666. assetMap.set(asset.name, item);
  667. }
  668. for (const item of assetMap.values()) {
  669. const related = item.info.related;
  670. if (!related) continue;
  671. for (const type of Object.keys(related)) {
  672. const relatedEntry = related[type];
  673. const deps = Array.isArray(relatedEntry)
  674. ? relatedEntry
  675. : [relatedEntry];
  676. for (const dep of deps) {
  677. const depItem = assetMap.get(dep);
  678. if (!depItem) continue;
  679. assets.delete(depItem);
  680. depItem.type = type;
  681. item.related = item.related || [];
  682. item.related.push(depItem);
  683. }
  684. }
  685. }
  686. object.assetsByChunkName = {};
  687. for (const [file, chunks] of compilationFileToChunks) {
  688. for (const chunk of chunks) {
  689. const name = chunk.name;
  690. if (!name) continue;
  691. if (
  692. !Object.prototype.hasOwnProperty.call(
  693. object.assetsByChunkName,
  694. name
  695. )
  696. ) {
  697. object.assetsByChunkName[name] = [];
  698. }
  699. object.assetsByChunkName[name].push(file);
  700. }
  701. }
  702. const groupedAssets = factory.create(
  703. `${type}.assets`,
  704. Array.from(assets),
  705. {
  706. ...context,
  707. compilationFileToChunks,
  708. compilationAuxiliaryFileToChunks
  709. }
  710. );
  711. const limited = spaceLimited(groupedAssets, options.assetsSpace);
  712. object.assets = limited.children;
  713. object.filteredAssets = limited.filteredChildren;
  714. },
  715. chunks: (object, compilation, context, options, factory) => {
  716. const { type } = context;
  717. object.chunks = factory.create(
  718. `${type}.chunks`,
  719. Array.from(compilation.chunks),
  720. context
  721. );
  722. },
  723. modules: (object, compilation, context, options, factory) => {
  724. const { type } = context;
  725. const array = Array.from(compilation.modules);
  726. const groupedModules = factory.create(`${type}.modules`, array, context);
  727. const limited = spaceLimited(groupedModules, options.modulesSpace);
  728. object.modules = limited.children;
  729. object.filteredModules = limited.filteredChildren;
  730. },
  731. entrypoints: (
  732. object,
  733. compilation,
  734. context,
  735. { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren },
  736. factory
  737. ) => {
  738. const { type } = context;
  739. const array = Array.from(compilation.entrypoints, ([key, value]) => ({
  740. name: key,
  741. chunkGroup: value
  742. }));
  743. if (entrypoints === "auto" && !chunkGroups) {
  744. if (array.length > 5) return;
  745. if (
  746. !chunkGroupChildren &&
  747. array.every(({ chunkGroup }) => {
  748. if (chunkGroup.chunks.length !== 1) return false;
  749. const chunk = chunkGroup.chunks[0];
  750. return (
  751. chunk.files.size === 1 &&
  752. (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0)
  753. );
  754. })
  755. ) {
  756. return;
  757. }
  758. }
  759. object.entrypoints = factory.create(
  760. `${type}.entrypoints`,
  761. array,
  762. context
  763. );
  764. },
  765. chunkGroups: (object, compilation, context, options, factory) => {
  766. const { type } = context;
  767. const array = Array.from(
  768. compilation.namedChunkGroups,
  769. ([key, value]) => ({
  770. name: key,
  771. chunkGroup: value
  772. })
  773. );
  774. object.namedChunkGroups = factory.create(
  775. `${type}.namedChunkGroups`,
  776. array,
  777. context
  778. );
  779. },
  780. errors: (object, compilation, context, options, factory) => {
  781. const { type, cachedGetErrors } = context;
  782. const rawErrors = cachedGetErrors(compilation);
  783. const factorizedErrors = factory.create(
  784. `${type}.errors`,
  785. cachedGetErrors(compilation),
  786. context
  787. );
  788. let filtered = 0;
  789. if (options.errorDetails === "auto" && rawErrors.length >= 3) {
  790. filtered = rawErrors
  791. .map(e => typeof e !== "string" && e.details)
  792. .filter(Boolean).length;
  793. }
  794. if (
  795. options.errorDetails === true ||
  796. !Number.isFinite(options.errorsSpace)
  797. ) {
  798. object.errors = factorizedErrors;
  799. if (filtered) object.filteredErrorDetailsCount = filtered;
  800. return;
  801. }
  802. const [errors, filteredBySpace] = errorsSpaceLimit(
  803. factorizedErrors,
  804. options.errorsSpace
  805. );
  806. object.filteredErrorDetailsCount = filtered + filteredBySpace;
  807. object.errors = errors;
  808. },
  809. errorsCount: (object, compilation, { cachedGetErrors }) => {
  810. object.errorsCount = countWithChildren(compilation, c =>
  811. cachedGetErrors(c)
  812. );
  813. },
  814. warnings: (object, compilation, context, options, factory) => {
  815. const { type, cachedGetWarnings } = context;
  816. const rawWarnings = factory.create(
  817. `${type}.warnings`,
  818. cachedGetWarnings(compilation),
  819. context
  820. );
  821. let filtered = 0;
  822. if (options.errorDetails === "auto") {
  823. filtered = cachedGetWarnings(compilation)
  824. .map(e => typeof e !== "string" && e.details)
  825. .filter(Boolean).length;
  826. }
  827. if (
  828. options.errorDetails === true ||
  829. !Number.isFinite(options.warningsSpace)
  830. ) {
  831. object.warnings = rawWarnings;
  832. if (filtered) object.filteredWarningDetailsCount = filtered;
  833. return;
  834. }
  835. const [warnings, filteredBySpace] = errorsSpaceLimit(
  836. rawWarnings,
  837. options.warningsSpace
  838. );
  839. object.filteredWarningDetailsCount = filtered + filteredBySpace;
  840. object.warnings = warnings;
  841. },
  842. warningsCount: (
  843. object,
  844. compilation,
  845. context,
  846. { warningsFilter },
  847. factory
  848. ) => {
  849. const { type, cachedGetWarnings } = context;
  850. object.warningsCount = countWithChildren(compilation, (c, childType) => {
  851. if (!warningsFilter && warningsFilter.length === 0)
  852. return cachedGetWarnings(c);
  853. return factory
  854. .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context)
  855. .filter(warning => {
  856. const warningString = Object.keys(warning)
  857. .map(key => `${warning[key]}`)
  858. .join("\n");
  859. return !warningsFilter.some(filter =>
  860. filter(warning, warningString)
  861. );
  862. });
  863. });
  864. },
  865. children: (object, compilation, context, options, factory) => {
  866. const { type } = context;
  867. object.children = factory.create(
  868. `${type}.children`,
  869. compilation.children,
  870. context
  871. );
  872. }
  873. },
  874. asset: {
  875. _: (object, asset, context, options, factory) => {
  876. const { compilation } = context;
  877. object.type = asset.type;
  878. object.name = asset.name;
  879. object.size = asset.source.size();
  880. object.emitted = compilation.emittedAssets.has(asset.name);
  881. object.comparedForEmit = compilation.comparedForEmitAssets.has(
  882. asset.name
  883. );
  884. const cached = !object.emitted && !object.comparedForEmit;
  885. object.cached = cached;
  886. object.info = asset.info;
  887. if (!cached || options.cachedAssets) {
  888. Object.assign(
  889. object,
  890. factory.create(`${context.type}$visible`, asset, context)
  891. );
  892. }
  893. }
  894. },
  895. asset$visible: {
  896. _: (
  897. object,
  898. asset,
  899. { compilation, compilationFileToChunks, compilationAuxiliaryFileToChunks }
  900. ) => {
  901. const chunks = compilationFileToChunks.get(asset.name) || [];
  902. const auxiliaryChunks =
  903. compilationAuxiliaryFileToChunks.get(asset.name) || [];
  904. object.chunkNames = uniqueOrderedArray(
  905. chunks,
  906. c => (c.name ? [c.name] : []),
  907. compareIds
  908. );
  909. object.chunkIdHints = uniqueOrderedArray(
  910. chunks,
  911. c => Array.from(c.idNameHints),
  912. compareIds
  913. );
  914. object.auxiliaryChunkNames = uniqueOrderedArray(
  915. auxiliaryChunks,
  916. c => (c.name ? [c.name] : []),
  917. compareIds
  918. );
  919. object.auxiliaryChunkIdHints = uniqueOrderedArray(
  920. auxiliaryChunks,
  921. c => Array.from(c.idNameHints),
  922. compareIds
  923. );
  924. object.filteredRelated = asset.related ? asset.related.length : undefined;
  925. },
  926. relatedAssets: (object, asset, context, options, factory) => {
  927. const { type } = context;
  928. object.related = factory.create(
  929. `${type.slice(0, -8)}.related`,
  930. asset.related,
  931. context
  932. );
  933. object.filteredRelated = asset.related
  934. ? asset.related.length - object.related.length
  935. : undefined;
  936. },
  937. ids: (
  938. object,
  939. asset,
  940. { compilationFileToChunks, compilationAuxiliaryFileToChunks }
  941. ) => {
  942. const chunks = compilationFileToChunks.get(asset.name) || [];
  943. const auxiliaryChunks =
  944. compilationAuxiliaryFileToChunks.get(asset.name) || [];
  945. object.chunks = uniqueOrderedArray(chunks, c => c.ids, compareIds);
  946. object.auxiliaryChunks = uniqueOrderedArray(
  947. auxiliaryChunks,
  948. c => c.ids,
  949. compareIds
  950. );
  951. },
  952. performance: (object, asset) => {
  953. object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source);
  954. }
  955. },
  956. chunkGroup: {
  957. _: (
  958. object,
  959. { name, chunkGroup },
  960. { compilation, compilation: { moduleGraph, chunkGraph } },
  961. { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets }
  962. ) => {
  963. const children =
  964. chunkGroupChildren &&
  965. chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph);
  966. /**
  967. * @param {string} name Name
  968. * @returns {{ name: string, size: number }} Asset object
  969. */
  970. const toAsset = name => {
  971. const asset = compilation.getAsset(name);
  972. return {
  973. name,
  974. size: asset ? asset.info.size : -1
  975. };
  976. };
  977. /** @type {(total: number, asset: { size: number }) => number} */
  978. const sizeReducer = (total, { size }) => total + size;
  979. const assets = uniqueArray(chunkGroup.chunks, c => c.files).map(toAsset);
  980. const auxiliaryAssets = uniqueOrderedArray(
  981. chunkGroup.chunks,
  982. c => c.auxiliaryFiles,
  983. compareIds
  984. ).map(toAsset);
  985. const assetsSize = assets.reduce(sizeReducer, 0);
  986. const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0);
  987. /** @type {KnownStatsChunkGroup} */
  988. const statsChunkGroup = {
  989. name,
  990. chunks: ids ? chunkGroup.chunks.map(c => c.id) : undefined,
  991. assets: assets.length <= chunkGroupMaxAssets ? assets : undefined,
  992. filteredAssets:
  993. assets.length <= chunkGroupMaxAssets ? 0 : assets.length,
  994. assetsSize,
  995. auxiliaryAssets:
  996. chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets
  997. ? auxiliaryAssets
  998. : undefined,
  999. filteredAuxiliaryAssets:
  1000. chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets
  1001. ? 0
  1002. : auxiliaryAssets.length,
  1003. auxiliaryAssetsSize,
  1004. children: children
  1005. ? mapObject(children, groups =>
  1006. groups.map(group => {
  1007. const assets = uniqueArray(group.chunks, c => c.files).map(
  1008. toAsset
  1009. );
  1010. const auxiliaryAssets = uniqueOrderedArray(
  1011. group.chunks,
  1012. c => c.auxiliaryFiles,
  1013. compareIds
  1014. ).map(toAsset);
  1015. /** @type {KnownStatsChunkGroup} */
  1016. const childStatsChunkGroup = {
  1017. name: group.name,
  1018. chunks: ids ? group.chunks.map(c => c.id) : undefined,
  1019. assets:
  1020. assets.length <= chunkGroupMaxAssets ? assets : undefined,
  1021. filteredAssets:
  1022. assets.length <= chunkGroupMaxAssets ? 0 : assets.length,
  1023. auxiliaryAssets:
  1024. chunkGroupAuxiliary &&
  1025. auxiliaryAssets.length <= chunkGroupMaxAssets
  1026. ? auxiliaryAssets
  1027. : undefined,
  1028. filteredAuxiliaryAssets:
  1029. chunkGroupAuxiliary &&
  1030. auxiliaryAssets.length <= chunkGroupMaxAssets
  1031. ? 0
  1032. : auxiliaryAssets.length
  1033. };
  1034. return childStatsChunkGroup;
  1035. })
  1036. )
  1037. : undefined,
  1038. childAssets: children
  1039. ? mapObject(children, groups => {
  1040. /** @type {Set<string>} */
  1041. const set = new Set();
  1042. for (const group of groups) {
  1043. for (const chunk of group.chunks) {
  1044. for (const asset of chunk.files) {
  1045. set.add(asset);
  1046. }
  1047. }
  1048. }
  1049. return Array.from(set);
  1050. })
  1051. : undefined
  1052. };
  1053. Object.assign(object, statsChunkGroup);
  1054. },
  1055. performance: (object, { chunkGroup }) => {
  1056. object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup);
  1057. }
  1058. },
  1059. module: {
  1060. _: (object, module, context, options, factory) => {
  1061. const { compilation, type } = context;
  1062. const built = compilation.builtModules.has(module);
  1063. const codeGenerated = compilation.codeGeneratedModules.has(module);
  1064. const buildTimeExecuted =
  1065. compilation.buildTimeExecutedModules.has(module);
  1066. /** @type {{[x: string]: number}} */
  1067. const sizes = {};
  1068. for (const sourceType of module.getSourceTypes()) {
  1069. sizes[sourceType] = module.size(sourceType);
  1070. }
  1071. /** @type {KnownStatsModule} */
  1072. const statsModule = {
  1073. type: "module",
  1074. moduleType: module.type,
  1075. layer: module.layer,
  1076. size: module.size(),
  1077. sizes,
  1078. built,
  1079. codeGenerated,
  1080. buildTimeExecuted,
  1081. cached: !built && !codeGenerated
  1082. };
  1083. Object.assign(object, statsModule);
  1084. if (built || codeGenerated || options.cachedModules) {
  1085. Object.assign(
  1086. object,
  1087. factory.create(`${type}$visible`, module, context)
  1088. );
  1089. }
  1090. }
  1091. },
  1092. module$visible: {
  1093. _: (object, module, context, { requestShortener }, factory) => {
  1094. const { compilation, type, rootModules } = context;
  1095. const { moduleGraph } = compilation;
  1096. /** @type {Module[]} */
  1097. const path = [];
  1098. const issuer = moduleGraph.getIssuer(module);
  1099. let current = issuer;
  1100. while (current) {
  1101. path.push(current);
  1102. current = moduleGraph.getIssuer(current);
  1103. }
  1104. path.reverse();
  1105. const profile = moduleGraph.getProfile(module);
  1106. const errors = module.getErrors();
  1107. const errorsCount = errors !== undefined ? countIterable(errors) : 0;
  1108. const warnings = module.getWarnings();
  1109. const warningsCount =
  1110. warnings !== undefined ? countIterable(warnings) : 0;
  1111. /** @type {{[x: string]: number}} */
  1112. const sizes = {};
  1113. for (const sourceType of module.getSourceTypes()) {
  1114. sizes[sourceType] = module.size(sourceType);
  1115. }
  1116. /** @type {KnownStatsModule} */
  1117. const statsModule = {
  1118. identifier: module.identifier(),
  1119. name: module.readableIdentifier(requestShortener),
  1120. nameForCondition: module.nameForCondition(),
  1121. index: moduleGraph.getPreOrderIndex(module),
  1122. preOrderIndex: moduleGraph.getPreOrderIndex(module),
  1123. index2: moduleGraph.getPostOrderIndex(module),
  1124. postOrderIndex: moduleGraph.getPostOrderIndex(module),
  1125. cacheable: module.buildInfo.cacheable,
  1126. optional: module.isOptional(moduleGraph),
  1127. orphan:
  1128. !type.endsWith("module.modules[].module$visible") &&
  1129. compilation.chunkGraph.getNumberOfModuleChunks(module) === 0,
  1130. dependent: rootModules ? !rootModules.has(module) : undefined,
  1131. issuer: issuer && issuer.identifier(),
  1132. issuerName: issuer && issuer.readableIdentifier(requestShortener),
  1133. issuerPath:
  1134. issuer &&
  1135. factory.create(`${type.slice(0, -8)}.issuerPath`, path, context),
  1136. failed: errorsCount > 0,
  1137. errors: errorsCount,
  1138. warnings: warningsCount
  1139. };
  1140. Object.assign(object, statsModule);
  1141. if (profile) {
  1142. object.profile = factory.create(
  1143. `${type.slice(0, -8)}.profile`,
  1144. profile,
  1145. context
  1146. );
  1147. }
  1148. },
  1149. ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => {
  1150. object.id = chunkGraph.getModuleId(module);
  1151. const issuer = moduleGraph.getIssuer(module);
  1152. object.issuerId = issuer && chunkGraph.getModuleId(issuer);
  1153. object.chunks = Array.from(
  1154. chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById),
  1155. chunk => chunk.id
  1156. );
  1157. },
  1158. moduleAssets: (object, module) => {
  1159. object.assets = module.buildInfo.assets
  1160. ? Object.keys(module.buildInfo.assets)
  1161. : [];
  1162. },
  1163. reasons: (object, module, context, options, factory) => {
  1164. const {
  1165. type,
  1166. compilation: { moduleGraph }
  1167. } = context;
  1168. const groupsReasons = factory.create(
  1169. `${type.slice(0, -8)}.reasons`,
  1170. Array.from(moduleGraph.getIncomingConnections(module)),
  1171. context
  1172. );
  1173. const limited = spaceLimited(groupsReasons, options.reasonsSpace);
  1174. object.reasons = limited.children;
  1175. object.filteredReasons = limited.filteredChildren;
  1176. },
  1177. usedExports: (
  1178. object,
  1179. module,
  1180. { runtime, compilation: { moduleGraph } }
  1181. ) => {
  1182. const usedExports = moduleGraph.getUsedExports(module, runtime);
  1183. if (usedExports === null) {
  1184. object.usedExports = null;
  1185. } else if (typeof usedExports === "boolean") {
  1186. object.usedExports = usedExports;
  1187. } else {
  1188. object.usedExports = Array.from(usedExports);
  1189. }
  1190. },
  1191. providedExports: (object, module, { compilation: { moduleGraph } }) => {
  1192. const providedExports = moduleGraph.getProvidedExports(module);
  1193. object.providedExports = Array.isArray(providedExports)
  1194. ? providedExports
  1195. : null;
  1196. },
  1197. optimizationBailout: (
  1198. object,
  1199. module,
  1200. { compilation: { moduleGraph } },
  1201. { requestShortener }
  1202. ) => {
  1203. object.optimizationBailout = moduleGraph
  1204. .getOptimizationBailout(module)
  1205. .map(item => {
  1206. if (typeof item === "function") return item(requestShortener);
  1207. return item;
  1208. });
  1209. },
  1210. depth: (object, module, { compilation: { moduleGraph } }) => {
  1211. object.depth = moduleGraph.getDepth(module);
  1212. },
  1213. nestedModules: (object, module, context, options, factory) => {
  1214. const { type } = context;
  1215. const innerModules = /** @type {Module & { modules?: Module[] }} */ (
  1216. module
  1217. ).modules;
  1218. if (Array.isArray(innerModules)) {
  1219. const groupedModules = factory.create(
  1220. `${type.slice(0, -8)}.modules`,
  1221. innerModules,
  1222. context
  1223. );
  1224. const limited = spaceLimited(
  1225. groupedModules,
  1226. options.nestedModulesSpace
  1227. );
  1228. object.modules = limited.children;
  1229. object.filteredModules = limited.filteredChildren;
  1230. }
  1231. },
  1232. source: (object, module) => {
  1233. const originalSource = module.originalSource();
  1234. if (originalSource) {
  1235. object.source = originalSource.source();
  1236. }
  1237. }
  1238. },
  1239. profile: {
  1240. _: (object, profile) => {
  1241. /** @type {KnownStatsProfile} */
  1242. const statsProfile = {
  1243. total:
  1244. profile.factory +
  1245. profile.restoring +
  1246. profile.integration +
  1247. profile.building +
  1248. profile.storing,
  1249. resolving: profile.factory,
  1250. restoring: profile.restoring,
  1251. building: profile.building,
  1252. integration: profile.integration,
  1253. storing: profile.storing,
  1254. additionalResolving: profile.additionalFactories,
  1255. additionalIntegration: profile.additionalIntegration,
  1256. // TODO remove this in webpack 6
  1257. factory: profile.factory,
  1258. // TODO remove this in webpack 6
  1259. dependencies: profile.additionalFactories
  1260. };
  1261. Object.assign(object, statsProfile);
  1262. }
  1263. },
  1264. moduleIssuer: {
  1265. _: (object, module, context, { requestShortener }, factory) => {
  1266. const { compilation, type } = context;
  1267. const { moduleGraph } = compilation;
  1268. const profile = moduleGraph.getProfile(module);
  1269. /** @type {KnownStatsModuleIssuer} */
  1270. const statsModuleIssuer = {
  1271. identifier: module.identifier(),
  1272. name: module.readableIdentifier(requestShortener)
  1273. };
  1274. Object.assign(object, statsModuleIssuer);
  1275. if (profile) {
  1276. object.profile = factory.create(`${type}.profile`, profile, context);
  1277. }
  1278. },
  1279. ids: (object, module, { compilation: { chunkGraph } }) => {
  1280. object.id = chunkGraph.getModuleId(module);
  1281. }
  1282. },
  1283. moduleReason: {
  1284. _: (object, reason, { runtime }, { requestShortener }) => {
  1285. const dep = reason.dependency;
  1286. const moduleDep =
  1287. dep && dep instanceof ModuleDependency ? dep : undefined;
  1288. /** @type {KnownStatsModuleReason} */
  1289. const statsModuleReason = {
  1290. moduleIdentifier: reason.originModule
  1291. ? reason.originModule.identifier()
  1292. : null,
  1293. module: reason.originModule
  1294. ? reason.originModule.readableIdentifier(requestShortener)
  1295. : null,
  1296. moduleName: reason.originModule
  1297. ? reason.originModule.readableIdentifier(requestShortener)
  1298. : null,
  1299. resolvedModuleIdentifier: reason.resolvedOriginModule
  1300. ? reason.resolvedOriginModule.identifier()
  1301. : null,
  1302. resolvedModule: reason.resolvedOriginModule
  1303. ? reason.resolvedOriginModule.readableIdentifier(requestShortener)
  1304. : null,
  1305. type: reason.dependency ? reason.dependency.type : null,
  1306. active: reason.isActive(runtime),
  1307. explanation: reason.explanation,
  1308. userRequest: (moduleDep && moduleDep.userRequest) || null
  1309. };
  1310. Object.assign(object, statsModuleReason);
  1311. if (reason.dependency) {
  1312. const locInfo = formatLocation(reason.dependency.loc);
  1313. if (locInfo) {
  1314. object.loc = locInfo;
  1315. }
  1316. }
  1317. },
  1318. ids: (object, reason, { compilation: { chunkGraph } }) => {
  1319. object.moduleId = reason.originModule
  1320. ? chunkGraph.getModuleId(reason.originModule)
  1321. : null;
  1322. object.resolvedModuleId = reason.resolvedOriginModule
  1323. ? chunkGraph.getModuleId(reason.resolvedOriginModule)
  1324. : null;
  1325. }
  1326. },
  1327. chunk: {
  1328. _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => {
  1329. const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph);
  1330. /** @type {KnownStatsChunk} */
  1331. const statsChunk = {
  1332. rendered: chunk.rendered,
  1333. initial: chunk.canBeInitial(),
  1334. entry: chunk.hasRuntime(),
  1335. recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk),
  1336. reason: chunk.chunkReason,
  1337. size: chunkGraph.getChunkModulesSize(chunk),
  1338. sizes: chunkGraph.getChunkModulesSizes(chunk),
  1339. names: chunk.name ? [chunk.name] : [],
  1340. idHints: Array.from(chunk.idNameHints),
  1341. runtime:
  1342. chunk.runtime === undefined
  1343. ? undefined
  1344. : typeof chunk.runtime === "string"
  1345. ? [makePathsRelative(chunk.runtime)]
  1346. : Array.from(chunk.runtime.sort(), makePathsRelative),
  1347. files: Array.from(chunk.files),
  1348. auxiliaryFiles: Array.from(chunk.auxiliaryFiles).sort(compareIds),
  1349. hash: chunk.renderedHash,
  1350. childrenByOrder: childIdByOrder
  1351. };
  1352. Object.assign(object, statsChunk);
  1353. },
  1354. ids: (object, chunk) => {
  1355. object.id = chunk.id;
  1356. },
  1357. chunkRelations: (object, chunk, { compilation: { chunkGraph } }) => {
  1358. /** @type {Set<string|number>} */
  1359. const parents = new Set();
  1360. /** @type {Set<string|number>} */
  1361. const children = new Set();
  1362. /** @type {Set<string|number>} */
  1363. const siblings = new Set();
  1364. for (const chunkGroup of chunk.groupsIterable) {
  1365. for (const parentGroup of chunkGroup.parentsIterable) {
  1366. for (const chunk of parentGroup.chunks) {
  1367. parents.add(chunk.id);
  1368. }
  1369. }
  1370. for (const childGroup of chunkGroup.childrenIterable) {
  1371. for (const chunk of childGroup.chunks) {
  1372. children.add(chunk.id);
  1373. }
  1374. }
  1375. for (const sibling of chunkGroup.chunks) {
  1376. if (sibling !== chunk) siblings.add(sibling.id);
  1377. }
  1378. }
  1379. object.siblings = Array.from(siblings).sort(compareIds);
  1380. object.parents = Array.from(parents).sort(compareIds);
  1381. object.children = Array.from(children).sort(compareIds);
  1382. },
  1383. chunkModules: (object, chunk, context, options, factory) => {
  1384. const {
  1385. type,
  1386. compilation: { chunkGraph }
  1387. } = context;
  1388. const array = chunkGraph.getChunkModules(chunk);
  1389. const groupedModules = factory.create(`${type}.modules`, array, {
  1390. ...context,
  1391. runtime: chunk.runtime,
  1392. rootModules: new Set(chunkGraph.getChunkRootModules(chunk))
  1393. });
  1394. const limited = spaceLimited(groupedModules, options.chunkModulesSpace);
  1395. object.modules = limited.children;
  1396. object.filteredModules = limited.filteredChildren;
  1397. },
  1398. chunkOrigins: (object, chunk, context, options, factory) => {
  1399. const {
  1400. type,
  1401. compilation: { chunkGraph }
  1402. } = context;
  1403. /** @type {Set<string>} */
  1404. const originsKeySet = new Set();
  1405. const origins = [];
  1406. for (const g of chunk.groupsIterable) {
  1407. origins.push(...g.origins);
  1408. }
  1409. const array = origins.filter(origin => {
  1410. const key = [
  1411. origin.module ? chunkGraph.getModuleId(origin.module) : undefined,
  1412. formatLocation(origin.loc),
  1413. origin.request
  1414. ].join();
  1415. if (originsKeySet.has(key)) return false;
  1416. originsKeySet.add(key);
  1417. return true;
  1418. });
  1419. object.origins = factory.create(`${type}.origins`, array, context);
  1420. }
  1421. },
  1422. chunkOrigin: {
  1423. _: (object, origin, context, { requestShortener }) => {
  1424. /** @type {KnownStatsChunkOrigin} */
  1425. const statsChunkOrigin = {
  1426. module: origin.module ? origin.module.identifier() : "",
  1427. moduleIdentifier: origin.module ? origin.module.identifier() : "",
  1428. moduleName: origin.module
  1429. ? origin.module.readableIdentifier(requestShortener)
  1430. : "",
  1431. loc: formatLocation(origin.loc),
  1432. request: origin.request
  1433. };
  1434. Object.assign(object, statsChunkOrigin);
  1435. },
  1436. ids: (object, origin, { compilation: { chunkGraph } }) => {
  1437. object.moduleId = origin.module
  1438. ? chunkGraph.getModuleId(origin.module)
  1439. : undefined;
  1440. }
  1441. },
  1442. error: EXTRACT_ERROR,
  1443. warning: EXTRACT_ERROR,
  1444. moduleTraceItem: {
  1445. _: (object, { origin, module }, context, { requestShortener }, factory) => {
  1446. const {
  1447. type,
  1448. compilation: { moduleGraph }
  1449. } = context;
  1450. object.originIdentifier = origin.identifier();
  1451. object.originName = origin.readableIdentifier(requestShortener);
  1452. object.moduleIdentifier = module.identifier();
  1453. object.moduleName = module.readableIdentifier(requestShortener);
  1454. const dependencies = Array.from(
  1455. moduleGraph.getIncomingConnections(module)
  1456. )
  1457. .filter(c => c.resolvedOriginModule === origin && c.dependency)
  1458. .map(c => c.dependency);
  1459. object.dependencies = factory.create(
  1460. `${type}.dependencies`,
  1461. Array.from(new Set(dependencies)),
  1462. context
  1463. );
  1464. },
  1465. ids: (object, { origin, module }, { compilation: { chunkGraph } }) => {
  1466. object.originId = chunkGraph.getModuleId(origin);
  1467. object.moduleId = chunkGraph.getModuleId(module);
  1468. }
  1469. },
  1470. moduleTraceDependency: {
  1471. _: (object, dependency) => {
  1472. object.loc = formatLocation(dependency.loc);
  1473. }
  1474. }
  1475. };
  1476. /** @type {Record<string, Record<string, (thing: any, context: StatsFactoryContext, options: NormalizedStatsOptions) => boolean | undefined>>} */
  1477. const FILTER = {
  1478. "module.reasons": {
  1479. "!orphanModules": (reason, { compilation: { chunkGraph } }) => {
  1480. if (
  1481. reason.originModule &&
  1482. chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0
  1483. ) {
  1484. return false;
  1485. }
  1486. }
  1487. }
  1488. };
  1489. /** @type {Record<string, Record<string, (thing: object, context: StatsFactoryContext, options: NormalizedStatsOptions) => boolean | undefined>>} */
  1490. const FILTER_RESULTS = {
  1491. "compilation.warnings": {
  1492. warningsFilter: util.deprecate(
  1493. (warning, context, { warningsFilter }) => {
  1494. const warningString = Object.keys(warning)
  1495. .map(key => `${warning[key]}`)
  1496. .join("\n");
  1497. return !warningsFilter.some(filter => filter(warning, warningString));
  1498. },
  1499. "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings",
  1500. "DEP_WEBPACK_STATS_WARNINGS_FILTER"
  1501. )
  1502. }
  1503. };
  1504. /** @type {Record<string, (comparators: Function[], context: StatsFactoryContext) => void>} */
  1505. const MODULES_SORTER = {
  1506. _: (comparators, { compilation: { moduleGraph } }) => {
  1507. comparators.push(
  1508. compareSelect(
  1509. /**
  1510. * @param {Module} m module
  1511. * @returns {number} depth
  1512. */
  1513. m => moduleGraph.getDepth(m),
  1514. compareNumbers
  1515. ),
  1516. compareSelect(
  1517. /**
  1518. * @param {Module} m module
  1519. * @returns {number} index
  1520. */
  1521. m => moduleGraph.getPreOrderIndex(m),
  1522. compareNumbers
  1523. ),
  1524. compareSelect(
  1525. /**
  1526. * @param {Module} m module
  1527. * @returns {string} identifier
  1528. */
  1529. m => m.identifier(),
  1530. compareIds
  1531. )
  1532. );
  1533. }
  1534. };
  1535. /** @type {Record<string, Record<string, (comparators: Function[], context: StatsFactoryContext) => void>>} */
  1536. const SORTERS = {
  1537. "compilation.chunks": {
  1538. _: comparators => {
  1539. comparators.push(compareSelect(c => c.id, compareIds));
  1540. }
  1541. },
  1542. "compilation.modules": MODULES_SORTER,
  1543. "chunk.rootModules": MODULES_SORTER,
  1544. "chunk.modules": MODULES_SORTER,
  1545. "module.modules": MODULES_SORTER,
  1546. "module.reasons": {
  1547. _: (comparators, { compilation: { chunkGraph } }) => {
  1548. comparators.push(
  1549. compareSelect(x => x.originModule, compareModulesByIdentifier)
  1550. );
  1551. comparators.push(
  1552. compareSelect(x => x.resolvedOriginModule, compareModulesByIdentifier)
  1553. );
  1554. comparators.push(
  1555. compareSelect(
  1556. x => x.dependency,
  1557. concatComparators(
  1558. compareSelect(
  1559. /**
  1560. * @param {Dependency} x dependency
  1561. * @returns {DependencyLocation} location
  1562. */
  1563. x => x.loc,
  1564. compareLocations
  1565. ),
  1566. compareSelect(x => x.type, compareIds)
  1567. )
  1568. )
  1569. );
  1570. }
  1571. },
  1572. "chunk.origins": {
  1573. _: (comparators, { compilation: { chunkGraph } }) => {
  1574. comparators.push(
  1575. compareSelect(
  1576. origin =>
  1577. origin.module ? chunkGraph.getModuleId(origin.module) : undefined,
  1578. compareIds
  1579. ),
  1580. compareSelect(origin => formatLocation(origin.loc), compareIds),
  1581. compareSelect(origin => origin.request, compareIds)
  1582. );
  1583. }
  1584. }
  1585. };
  1586. const getItemSize = item => {
  1587. // Each item takes 1 line
  1588. // + the size of the children
  1589. // + 1 extra line when it has children and filteredChildren
  1590. return !item.children
  1591. ? 1
  1592. : item.filteredChildren
  1593. ? 2 + getTotalSize(item.children)
  1594. : 1 + getTotalSize(item.children);
  1595. };
  1596. const getTotalSize = children => {
  1597. let size = 0;
  1598. for (const child of children) {
  1599. size += getItemSize(child);
  1600. }
  1601. return size;
  1602. };
  1603. const getTotalItems = children => {
  1604. let count = 0;
  1605. for (const child of children) {
  1606. if (!child.children && !child.filteredChildren) {
  1607. count++;
  1608. } else {
  1609. if (child.children) count += getTotalItems(child.children);
  1610. if (child.filteredChildren) count += child.filteredChildren;
  1611. }
  1612. }
  1613. return count;
  1614. };
  1615. const collapse = children => {
  1616. // After collapse each child must take exactly one line
  1617. const newChildren = [];
  1618. for (const child of children) {
  1619. if (child.children) {
  1620. let filteredChildren = child.filteredChildren || 0;
  1621. filteredChildren += getTotalItems(child.children);
  1622. newChildren.push({
  1623. ...child,
  1624. children: undefined,
  1625. filteredChildren
  1626. });
  1627. } else {
  1628. newChildren.push(child);
  1629. }
  1630. }
  1631. return newChildren;
  1632. };
  1633. const spaceLimited = (
  1634. itemsAndGroups,
  1635. max,
  1636. filteredChildrenLineReserved = false
  1637. ) => {
  1638. if (max < 1) {
  1639. return {
  1640. children: undefined,
  1641. filteredChildren: getTotalItems(itemsAndGroups)
  1642. };
  1643. }
  1644. /** @type {any[] | undefined} */
  1645. let children = undefined;
  1646. /** @type {number | undefined} */
  1647. let filteredChildren = undefined;
  1648. // This are the groups, which take 1+ lines each
  1649. const groups = [];
  1650. // The sizes of the groups are stored in groupSizes
  1651. const groupSizes = [];
  1652. // This are the items, which take 1 line each
  1653. const items = [];
  1654. // The total of group sizes
  1655. let groupsSize = 0;
  1656. for (const itemOrGroup of itemsAndGroups) {
  1657. // is item
  1658. if (!itemOrGroup.children && !itemOrGroup.filteredChildren) {
  1659. items.push(itemOrGroup);
  1660. } else {
  1661. groups.push(itemOrGroup);
  1662. const size = getItemSize(itemOrGroup);
  1663. groupSizes.push(size);
  1664. groupsSize += size;
  1665. }
  1666. }
  1667. if (groupsSize + items.length <= max) {
  1668. // The total size in the current state fits into the max
  1669. // keep all
  1670. children = groups.length > 0 ? groups.concat(items) : items;
  1671. } else if (groups.length === 0) {
  1672. // slice items to max
  1673. // inner space marks that lines for filteredChildren already reserved
  1674. const limit = max - (filteredChildrenLineReserved ? 0 : 1);
  1675. filteredChildren = items.length - limit;
  1676. items.length = limit;
  1677. children = items;
  1678. } else {
  1679. // limit is the size when all groups are collapsed
  1680. const limit =
  1681. groups.length +
  1682. (filteredChildrenLineReserved || items.length === 0 ? 0 : 1);
  1683. if (limit < max) {
  1684. // calculate how much we are over the size limit
  1685. // this allows to approach the limit faster
  1686. let oversize;
  1687. // If each group would take 1 line the total would be below the maximum
  1688. // collapse some groups, keep items
  1689. while (
  1690. (oversize =
  1691. groupsSize +
  1692. items.length +
  1693. (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) -
  1694. max) > 0
  1695. ) {
  1696. // Find the maximum group and process only this one
  1697. const maxGroupSize = Math.max(...groupSizes);
  1698. if (maxGroupSize < items.length) {
  1699. filteredChildren = items.length;
  1700. items.length = 0;
  1701. continue;
  1702. }
  1703. for (let i = 0; i < groups.length; i++) {
  1704. if (groupSizes[i] === maxGroupSize) {
  1705. const group = groups[i];
  1706. // run this algorithm recursively and limit the size of the children to
  1707. // current size - oversize / number of groups
  1708. // So it should always end up being smaller
  1709. const headerSize = group.filteredChildren ? 2 : 1;
  1710. const limited = spaceLimited(
  1711. group.children,
  1712. maxGroupSize -
  1713. // we should use ceil to always feet in max
  1714. Math.ceil(oversize / groups.length) -
  1715. // we substitute size of group head
  1716. headerSize,
  1717. headerSize === 2
  1718. );
  1719. groups[i] = {
  1720. ...group,
  1721. children: limited.children,
  1722. filteredChildren: limited.filteredChildren
  1723. ? (group.filteredChildren || 0) + limited.filteredChildren
  1724. : group.filteredChildren
  1725. };
  1726. const newSize = getItemSize(groups[i]);
  1727. groupsSize -= maxGroupSize - newSize;
  1728. groupSizes[i] = newSize;
  1729. break;
  1730. }
  1731. }
  1732. }
  1733. children = groups.concat(items);
  1734. } else if (limit === max) {
  1735. // If we have only enough space to show one line per group and one line for the filtered items
  1736. // collapse all groups and items
  1737. children = collapse(groups);
  1738. filteredChildren = items.length;
  1739. } else {
  1740. // If we have no space
  1741. // collapse complete group
  1742. filteredChildren = getTotalItems(itemsAndGroups);
  1743. }
  1744. }
  1745. return {
  1746. children,
  1747. filteredChildren
  1748. };
  1749. };
  1750. const errorsSpaceLimit = (errors, max) => {
  1751. let filtered = 0;
  1752. // Can not fit into limit
  1753. // print only messages
  1754. if (errors.length + 1 >= max)
  1755. return [
  1756. errors.map(error => {
  1757. if (typeof error === "string" || !error.details) return error;
  1758. filtered++;
  1759. return { ...error, details: "" };
  1760. }),
  1761. filtered
  1762. ];
  1763. let fullLength = errors.length;
  1764. let result = errors;
  1765. let i = 0;
  1766. for (; i < errors.length; i++) {
  1767. const error = errors[i];
  1768. if (typeof error !== "string" && error.details) {
  1769. const splitted = error.details.split("\n");
  1770. const len = splitted.length;
  1771. fullLength += len;
  1772. if (fullLength > max) {
  1773. result = i > 0 ? errors.slice(0, i) : [];
  1774. const overLimit = fullLength - max + 1;
  1775. const error = errors[i++];
  1776. result.push({
  1777. ...error,
  1778. details: error.details.split("\n").slice(0, -overLimit).join("\n"),
  1779. filteredDetails: overLimit
  1780. });
  1781. filtered = errors.length - i;
  1782. for (; i < errors.length; i++) {
  1783. const error = errors[i];
  1784. if (typeof error === "string" || !error.details) result.push(error);
  1785. result.push({ ...error, details: "" });
  1786. }
  1787. break;
  1788. } else if (fullLength === max) {
  1789. result = errors.slice(0, ++i);
  1790. filtered = errors.length - i;
  1791. for (; i < errors.length; i++) {
  1792. const error = errors[i];
  1793. if (typeof error === "string" || !error.details) result.push(error);
  1794. result.push({ ...error, details: "" });
  1795. }
  1796. break;
  1797. }
  1798. }
  1799. }
  1800. return [result, filtered];
  1801. };
  1802. const assetGroup = (children, assets) => {
  1803. let size = 0;
  1804. for (const asset of children) {
  1805. size += asset.size;
  1806. }
  1807. return {
  1808. size
  1809. };
  1810. };
  1811. const moduleGroup = (children, modules) => {
  1812. let size = 0;
  1813. const sizes = {};
  1814. for (const module of children) {
  1815. size += module.size;
  1816. for (const key of Object.keys(module.sizes)) {
  1817. sizes[key] = (sizes[key] || 0) + module.sizes[key];
  1818. }
  1819. }
  1820. return {
  1821. size,
  1822. sizes
  1823. };
  1824. };
  1825. const reasonGroup = (children, reasons) => {
  1826. let active = false;
  1827. for (const reason of children) {
  1828. active = active || reason.active;
  1829. }
  1830. return {
  1831. active
  1832. };
  1833. };
  1834. const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/;
  1835. const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/;
  1836. /** @type {Record<string, (groupConfigs: GroupConfig[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} */
  1837. const ASSETS_GROUPERS = {
  1838. _: (groupConfigs, context, options) => {
  1839. const groupByFlag = (name, exclude) => {
  1840. groupConfigs.push({
  1841. getKeys: asset => {
  1842. return asset[name] ? ["1"] : undefined;
  1843. },
  1844. getOptions: () => {
  1845. return {
  1846. groupChildren: !exclude,
  1847. force: exclude
  1848. };
  1849. },
  1850. createGroup: (key, children, assets) => {
  1851. return exclude
  1852. ? {
  1853. type: "assets by status",
  1854. [name]: !!key,
  1855. filteredChildren: assets.length,
  1856. ...assetGroup(children, assets)
  1857. }
  1858. : {
  1859. type: "assets by status",
  1860. [name]: !!key,
  1861. children,
  1862. ...assetGroup(children, assets)
  1863. };
  1864. }
  1865. });
  1866. };
  1867. const {
  1868. groupAssetsByEmitStatus,
  1869. groupAssetsByPath,
  1870. groupAssetsByExtension
  1871. } = options;
  1872. if (groupAssetsByEmitStatus) {
  1873. groupByFlag("emitted");
  1874. groupByFlag("comparedForEmit");
  1875. groupByFlag("isOverSizeLimit");
  1876. }
  1877. if (groupAssetsByEmitStatus || !options.cachedAssets) {
  1878. groupByFlag("cached", !options.cachedAssets);
  1879. }
  1880. if (groupAssetsByPath || groupAssetsByExtension) {
  1881. groupConfigs.push({
  1882. getKeys: asset => {
  1883. const extensionMatch =
  1884. groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name);
  1885. const extension = extensionMatch ? extensionMatch[1] : "";
  1886. const pathMatch =
  1887. groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name);
  1888. const path = pathMatch ? pathMatch[1].split(/[/\\]/) : [];
  1889. const keys = [];
  1890. if (groupAssetsByPath) {
  1891. keys.push(".");
  1892. if (extension)
  1893. keys.push(
  1894. path.length
  1895. ? `${path.join("/")}/*${extension}`
  1896. : `*${extension}`
  1897. );
  1898. while (path.length > 0) {
  1899. keys.push(path.join("/") + "/");
  1900. path.pop();
  1901. }
  1902. } else {
  1903. if (extension) keys.push(`*${extension}`);
  1904. }
  1905. return keys;
  1906. },
  1907. createGroup: (key, children, assets) => {
  1908. return {
  1909. type: groupAssetsByPath ? "assets by path" : "assets by extension",
  1910. name: key,
  1911. children,
  1912. ...assetGroup(children, assets)
  1913. };
  1914. }
  1915. });
  1916. }
  1917. },
  1918. groupAssetsByInfo: (groupConfigs, context, options) => {
  1919. const groupByAssetInfoFlag = name => {
  1920. groupConfigs.push({
  1921. getKeys: asset => {
  1922. return asset.info && asset.info[name] ? ["1"] : undefined;
  1923. },
  1924. createGroup: (key, children, assets) => {
  1925. return {
  1926. type: "assets by info",
  1927. info: {
  1928. [name]: !!key
  1929. },
  1930. children,
  1931. ...assetGroup(children, assets)
  1932. };
  1933. }
  1934. });
  1935. };
  1936. groupByAssetInfoFlag("immutable");
  1937. groupByAssetInfoFlag("development");
  1938. groupByAssetInfoFlag("hotModuleReplacement");
  1939. },
  1940. groupAssetsByChunk: (groupConfigs, context, options) => {
  1941. const groupByNames = name => {
  1942. groupConfigs.push({
  1943. getKeys: asset => {
  1944. return asset[name];
  1945. },
  1946. createGroup: (key, children, assets) => {
  1947. return {
  1948. type: "assets by chunk",
  1949. [name]: [key],
  1950. children,
  1951. ...assetGroup(children, assets)
  1952. };
  1953. }
  1954. });
  1955. };
  1956. groupByNames("chunkNames");
  1957. groupByNames("auxiliaryChunkNames");
  1958. groupByNames("chunkIdHints");
  1959. groupByNames("auxiliaryChunkIdHints");
  1960. },
  1961. excludeAssets: (groupConfigs, context, { excludeAssets }) => {
  1962. groupConfigs.push({
  1963. getKeys: asset => {
  1964. const ident = asset.name;
  1965. const excluded = excludeAssets.some(fn => fn(ident, asset));
  1966. if (excluded) return ["excluded"];
  1967. },
  1968. getOptions: () => ({
  1969. groupChildren: false,
  1970. force: true
  1971. }),
  1972. createGroup: (key, children, assets) => ({
  1973. type: "hidden assets",
  1974. filteredChildren: assets.length,
  1975. ...assetGroup(children, assets)
  1976. })
  1977. });
  1978. }
  1979. };
  1980. /** @type {function("module" | "chunk" | "root-of-chunk" | "nested"): Record<string, (groupConfigs: GroupConfig[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} */
  1981. const MODULES_GROUPERS = type => ({
  1982. _: (groupConfigs, context, options) => {
  1983. const groupByFlag = (name, type, exclude) => {
  1984. groupConfigs.push({
  1985. getKeys: module => {
  1986. return module[name] ? ["1"] : undefined;
  1987. },
  1988. getOptions: () => {
  1989. return {
  1990. groupChildren: !exclude,
  1991. force: exclude
  1992. };
  1993. },
  1994. createGroup: (key, children, modules) => {
  1995. return {
  1996. type,
  1997. [name]: !!key,
  1998. ...(exclude ? { filteredChildren: modules.length } : { children }),
  1999. ...moduleGroup(children, modules)
  2000. };
  2001. }
  2002. });
  2003. };
  2004. const {
  2005. groupModulesByCacheStatus,
  2006. groupModulesByLayer,
  2007. groupModulesByAttributes,
  2008. groupModulesByType,
  2009. groupModulesByPath,
  2010. groupModulesByExtension
  2011. } = options;
  2012. if (groupModulesByAttributes) {
  2013. groupByFlag("errors", "modules with errors");
  2014. groupByFlag("warnings", "modules with warnings");
  2015. groupByFlag("assets", "modules with assets");
  2016. groupByFlag("optional", "optional modules");
  2017. }
  2018. if (groupModulesByCacheStatus) {
  2019. groupByFlag("cacheable", "cacheable modules");
  2020. groupByFlag("built", "built modules");
  2021. groupByFlag("codeGenerated", "code generated modules");
  2022. }
  2023. if (groupModulesByCacheStatus || !options.cachedModules) {
  2024. groupByFlag("cached", "cached modules", !options.cachedModules);
  2025. }
  2026. if (groupModulesByAttributes || !options.orphanModules) {
  2027. groupByFlag("orphan", "orphan modules", !options.orphanModules);
  2028. }
  2029. if (groupModulesByAttributes || !options.dependentModules) {
  2030. groupByFlag("dependent", "dependent modules", !options.dependentModules);
  2031. }
  2032. if (groupModulesByType || !options.runtimeModules) {
  2033. groupConfigs.push({
  2034. getKeys: module => {
  2035. if (!module.moduleType) return;
  2036. if (groupModulesByType) {
  2037. return [module.moduleType.split("/", 1)[0]];
  2038. } else if (module.moduleType === WEBPACK_MODULE_TYPE_RUNTIME) {
  2039. return [WEBPACK_MODULE_TYPE_RUNTIME];
  2040. }
  2041. },
  2042. getOptions: key => {
  2043. const exclude =
  2044. key === WEBPACK_MODULE_TYPE_RUNTIME && !options.runtimeModules;
  2045. return {
  2046. groupChildren: !exclude,
  2047. force: exclude
  2048. };
  2049. },
  2050. createGroup: (key, children, modules) => {
  2051. const exclude =
  2052. key === WEBPACK_MODULE_TYPE_RUNTIME && !options.runtimeModules;
  2053. return {
  2054. type: `${key} modules`,
  2055. moduleType: key,
  2056. ...(exclude ? { filteredChildren: modules.length } : { children }),
  2057. ...moduleGroup(children, modules)
  2058. };
  2059. }
  2060. });
  2061. }
  2062. if (groupModulesByLayer) {
  2063. groupConfigs.push({
  2064. getKeys: module => {
  2065. return [module.layer];
  2066. },
  2067. createGroup: (key, children, modules) => {
  2068. return {
  2069. type: "modules by layer",
  2070. layer: key,
  2071. children,
  2072. ...moduleGroup(children, modules)
  2073. };
  2074. }
  2075. });
  2076. }
  2077. if (groupModulesByPath || groupModulesByExtension) {
  2078. groupConfigs.push({
  2079. getKeys: module => {
  2080. if (!module.name) return;
  2081. const resource = parseResource(module.name.split("!").pop()).path;
  2082. const dataUrl = /^data:[^,;]+/.exec(resource);
  2083. if (dataUrl) return [dataUrl[0]];
  2084. const extensionMatch =
  2085. groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource);
  2086. const extension = extensionMatch ? extensionMatch[1] : "";
  2087. const pathMatch =
  2088. groupModulesByPath && GROUP_PATH_REGEXP.exec(resource);
  2089. const path = pathMatch ? pathMatch[1].split(/[/\\]/) : [];
  2090. const keys = [];
  2091. if (groupModulesByPath) {
  2092. if (extension)
  2093. keys.push(
  2094. path.length
  2095. ? `${path.join("/")}/*${extension}`
  2096. : `*${extension}`
  2097. );
  2098. while (path.length > 0) {
  2099. keys.push(path.join("/") + "/");
  2100. path.pop();
  2101. }
  2102. } else {
  2103. if (extension) keys.push(`*${extension}`);
  2104. }
  2105. return keys;
  2106. },
  2107. createGroup: (key, children, modules) => {
  2108. const isDataUrl = key.startsWith("data:");
  2109. return {
  2110. type: isDataUrl
  2111. ? "modules by mime type"
  2112. : groupModulesByPath
  2113. ? "modules by path"
  2114. : "modules by extension",
  2115. name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key,
  2116. children,
  2117. ...moduleGroup(children, modules)
  2118. };
  2119. }
  2120. });
  2121. }
  2122. },
  2123. excludeModules: (groupConfigs, context, { excludeModules }) => {
  2124. groupConfigs.push({
  2125. getKeys: module => {
  2126. const name = module.name;
  2127. if (name) {
  2128. const excluded = excludeModules.some(fn => fn(name, module, type));
  2129. if (excluded) return ["1"];
  2130. }
  2131. },
  2132. getOptions: () => ({
  2133. groupChildren: false,
  2134. force: true
  2135. }),
  2136. createGroup: (key, children, modules) => ({
  2137. type: "hidden modules",
  2138. filteredChildren: children.length,
  2139. ...moduleGroup(children, modules)
  2140. })
  2141. });
  2142. }
  2143. });
  2144. /** @type {Record<string, Record<string, (groupConfigs: GroupConfig[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */
  2145. const RESULT_GROUPERS = {
  2146. "compilation.assets": ASSETS_GROUPERS,
  2147. "asset.related": ASSETS_GROUPERS,
  2148. "compilation.modules": MODULES_GROUPERS("module"),
  2149. "chunk.modules": MODULES_GROUPERS("chunk"),
  2150. "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"),
  2151. "module.modules": MODULES_GROUPERS("nested"),
  2152. "module.reasons": {
  2153. groupReasonsByOrigin: groupConfigs => {
  2154. groupConfigs.push({
  2155. getKeys: reason => {
  2156. return [reason.module];
  2157. },
  2158. createGroup: (key, children, reasons) => {
  2159. return {
  2160. type: "from origin",
  2161. module: key,
  2162. children,
  2163. ...reasonGroup(children, reasons)
  2164. };
  2165. }
  2166. });
  2167. }
  2168. }
  2169. };
  2170. // remove a prefixed "!" that can be specified to reverse sort order
  2171. const normalizeFieldKey = field => {
  2172. if (field[0] === "!") {
  2173. return field.slice(1);
  2174. }
  2175. return field;
  2176. };
  2177. // if a field is prefixed by a "!" reverse sort order
  2178. const sortOrderRegular = field => {
  2179. if (field[0] === "!") {
  2180. return false;
  2181. }
  2182. return true;
  2183. };
  2184. /**
  2185. * @param {string} field field name
  2186. * @returns {function(object, object): number} comparators
  2187. */
  2188. const sortByField = field => {
  2189. if (!field) {
  2190. /**
  2191. * @param {any} a first
  2192. * @param {any} b second
  2193. * @returns {-1|0|1} zero
  2194. */
  2195. const noSort = (a, b) => 0;
  2196. return noSort;
  2197. }
  2198. const fieldKey = normalizeFieldKey(field);
  2199. let sortFn = compareSelect(m => m[fieldKey], compareIds);
  2200. // if a field is prefixed with a "!" the sort is reversed!
  2201. const sortIsRegular = sortOrderRegular(field);
  2202. if (!sortIsRegular) {
  2203. const oldSortFn = sortFn;
  2204. sortFn = (a, b) => oldSortFn(b, a);
  2205. }
  2206. return sortFn;
  2207. };
  2208. const ASSET_SORTERS = {
  2209. /** @type {(comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void} */
  2210. assetsSort: (comparators, context, { assetsSort }) => {
  2211. comparators.push(sortByField(assetsSort));
  2212. },
  2213. _: comparators => {
  2214. comparators.push(compareSelect(a => a.name, compareIds));
  2215. }
  2216. };
  2217. /** @type {Record<string, Record<string, (comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */
  2218. const RESULT_SORTERS = {
  2219. "compilation.chunks": {
  2220. chunksSort: (comparators, context, { chunksSort }) => {
  2221. comparators.push(sortByField(chunksSort));
  2222. }
  2223. },
  2224. "compilation.modules": {
  2225. modulesSort: (comparators, context, { modulesSort }) => {
  2226. comparators.push(sortByField(modulesSort));
  2227. }
  2228. },
  2229. "chunk.modules": {
  2230. chunkModulesSort: (comparators, context, { chunkModulesSort }) => {
  2231. comparators.push(sortByField(chunkModulesSort));
  2232. }
  2233. },
  2234. "module.modules": {
  2235. nestedModulesSort: (comparators, context, { nestedModulesSort }) => {
  2236. comparators.push(sortByField(nestedModulesSort));
  2237. }
  2238. },
  2239. "compilation.assets": ASSET_SORTERS,
  2240. "asset.related": ASSET_SORTERS
  2241. };
  2242. /**
  2243. * @param {Record<string, Record<string, Function>>} config the config see above
  2244. * @param {NormalizedStatsOptions} options stats options
  2245. * @param {function(string, Function): void} fn handler function called for every active line in config
  2246. * @returns {void}
  2247. */
  2248. const iterateConfig = (config, options, fn) => {
  2249. for (const hookFor of Object.keys(config)) {
  2250. const subConfig = config[hookFor];
  2251. for (const option of Object.keys(subConfig)) {
  2252. if (option !== "_") {
  2253. if (option.startsWith("!")) {
  2254. if (options[option.slice(1)]) continue;
  2255. } else {
  2256. const value = options[option];
  2257. if (
  2258. value === false ||
  2259. value === undefined ||
  2260. (Array.isArray(value) && value.length === 0)
  2261. )
  2262. continue;
  2263. }
  2264. }
  2265. fn(hookFor, subConfig[option]);
  2266. }
  2267. }
  2268. };
  2269. /** @type {Record<string, string>} */
  2270. const ITEM_NAMES = {
  2271. "compilation.children[]": "compilation",
  2272. "compilation.modules[]": "module",
  2273. "compilation.entrypoints[]": "chunkGroup",
  2274. "compilation.namedChunkGroups[]": "chunkGroup",
  2275. "compilation.errors[]": "error",
  2276. "compilation.warnings[]": "warning",
  2277. "chunk.modules[]": "module",
  2278. "chunk.rootModules[]": "module",
  2279. "chunk.origins[]": "chunkOrigin",
  2280. "compilation.chunks[]": "chunk",
  2281. "compilation.assets[]": "asset",
  2282. "asset.related[]": "asset",
  2283. "module.issuerPath[]": "moduleIssuer",
  2284. "module.reasons[]": "moduleReason",
  2285. "module.modules[]": "module",
  2286. "module.children[]": "module",
  2287. "moduleTrace[]": "moduleTraceItem",
  2288. "moduleTraceItem.dependencies[]": "moduleTraceDependency"
  2289. };
  2290. /**
  2291. * @param {object[]} items items to be merged
  2292. * @returns {object} an object
  2293. */
  2294. const mergeToObject = items => {
  2295. const obj = Object.create(null);
  2296. for (const item of items) {
  2297. obj[item.name] = item;
  2298. }
  2299. return obj;
  2300. };
  2301. /** @type {Record<string, (items: object[]) => any>} */
  2302. const MERGER = {
  2303. "compilation.entrypoints": mergeToObject,
  2304. "compilation.namedChunkGroups": mergeToObject
  2305. };
  2306. class DefaultStatsFactoryPlugin {
  2307. /**
  2308. * Apply the plugin
  2309. * @param {Compiler} compiler the compiler instance
  2310. * @returns {void}
  2311. */
  2312. apply(compiler) {
  2313. compiler.hooks.compilation.tap("DefaultStatsFactoryPlugin", compilation => {
  2314. compilation.hooks.statsFactory.tap(
  2315. "DefaultStatsFactoryPlugin",
  2316. (stats, options, context) => {
  2317. iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => {
  2318. stats.hooks.extract
  2319. .for(hookFor)
  2320. .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) =>
  2321. fn(obj, data, ctx, options, stats)
  2322. );
  2323. });
  2324. iterateConfig(FILTER, options, (hookFor, fn) => {
  2325. stats.hooks.filter
  2326. .for(hookFor)
  2327. .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) =>
  2328. fn(item, ctx, options, idx, i)
  2329. );
  2330. });
  2331. iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => {
  2332. stats.hooks.filterResults
  2333. .for(hookFor)
  2334. .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) =>
  2335. fn(item, ctx, options, idx, i)
  2336. );
  2337. });
  2338. iterateConfig(SORTERS, options, (hookFor, fn) => {
  2339. stats.hooks.sort
  2340. .for(hookFor)
  2341. .tap("DefaultStatsFactoryPlugin", (comparators, ctx) =>
  2342. fn(comparators, ctx, options)
  2343. );
  2344. });
  2345. iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => {
  2346. stats.hooks.sortResults
  2347. .for(hookFor)
  2348. .tap("DefaultStatsFactoryPlugin", (comparators, ctx) =>
  2349. fn(comparators, ctx, options)
  2350. );
  2351. });
  2352. iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => {
  2353. stats.hooks.groupResults
  2354. .for(hookFor)
  2355. .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) =>
  2356. fn(groupConfigs, ctx, options)
  2357. );
  2358. });
  2359. for (const key of Object.keys(ITEM_NAMES)) {
  2360. const itemName = ITEM_NAMES[key];
  2361. stats.hooks.getItemName
  2362. .for(key)
  2363. .tap("DefaultStatsFactoryPlugin", () => itemName);
  2364. }
  2365. for (const key of Object.keys(MERGER)) {
  2366. const merger = MERGER[key];
  2367. stats.hooks.merge.for(key).tap("DefaultStatsFactoryPlugin", merger);
  2368. }
  2369. if (options.children) {
  2370. if (Array.isArray(options.children)) {
  2371. stats.hooks.getItemFactory
  2372. .for("compilation.children[].compilation")
  2373. .tap("DefaultStatsFactoryPlugin", (comp, { _index: idx }) => {
  2374. if (idx < options.children.length) {
  2375. return compilation.createStatsFactory(
  2376. compilation.createStatsOptions(
  2377. options.children[idx],
  2378. context
  2379. )
  2380. );
  2381. }
  2382. });
  2383. } else if (options.children !== true) {
  2384. const childFactory = compilation.createStatsFactory(
  2385. compilation.createStatsOptions(options.children, context)
  2386. );
  2387. stats.hooks.getItemFactory
  2388. .for("compilation.children[].compilation")
  2389. .tap("DefaultStatsFactoryPlugin", () => {
  2390. return childFactory;
  2391. });
  2392. }
  2393. }
  2394. }
  2395. );
  2396. });
  2397. }
  2398. }
  2399. module.exports = DefaultStatsFactoryPlugin;