DefaultStatsFactoryPlugin.js 84 KB

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