DefaultStatsFactoryPlugin.js 89 KB

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