StatsFactory.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { HookMap, SyncBailHook, SyncWaterfallHook } = require("tapable");
  7. const { concatComparators, keepOriginalOrder } = require("../util/comparators");
  8. const smartGrouping = require("../util/smartGrouping");
  9. /** @typedef {import("../Chunk")} Chunk */
  10. /** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */
  11. /** @typedef {import("../Compilation")} Compilation */
  12. /** @typedef {import("../Compilation").Asset} Asset */
  13. /** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
  14. /** @typedef {import("../Dependency")} Dependency */
  15. /** @typedef {import("../Module")} Module */
  16. /** @typedef {import("../ModuleGraph").ModuleProfile} ModuleProfile */
  17. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  18. /** @typedef {import("../WebpackError")} WebpackError */
  19. /** @typedef {import("../util/comparators").Comparator<EXPECTED_ANY>} Comparator */
  20. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  21. /** @typedef {import("../util/smartGrouping").GroupConfig<EXPECTED_ANY, EXPECTED_OBJECT>} GroupConfig */
  22. /** @typedef {import("./DefaultStatsFactoryPlugin").ChunkGroupInfoWithName} ChunkGroupInfoWithName */
  23. /** @typedef {import("./DefaultStatsFactoryPlugin").ModuleIssuerPath} ModuleIssuerPath */
  24. /** @typedef {import("./DefaultStatsFactoryPlugin").ModuleTrace} ModuleTrace */
  25. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */
  26. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */
  27. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */
  28. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */
  29. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */
  30. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsError} StatsError */
  31. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */
  32. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */
  33. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */
  34. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */
  35. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */
  36. /** @typedef {import("./DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */
  37. /**
  38. * @typedef {object} KnownStatsFactoryContext
  39. * @property {string} type
  40. * @property {(path: string) => string} makePathsRelative
  41. * @property {Compilation} compilation
  42. * @property {Set<Module>} rootModules
  43. * @property {Map<string, Chunk[]>} compilationFileToChunks
  44. * @property {Map<string, Chunk[]>} compilationAuxiliaryFileToChunks
  45. * @property {RuntimeSpec} runtime
  46. * @property {(compilation: Compilation) => WebpackError[]} cachedGetErrors
  47. * @property {(compilation: Compilation) => WebpackError[]} cachedGetWarnings
  48. */
  49. /** @typedef {KnownStatsFactoryContext & Record<string, EXPECTED_ANY>} StatsFactoryContext */
  50. // StatsLogging StatsLoggingEntry
  51. /**
  52. * @template T
  53. * @template F
  54. * @typedef {T extends Compilation ? StatsCompilation : T extends ChunkGroupInfoWithName ? StatsChunkGroup : T extends Chunk ? StatsChunk : T extends OriginRecord ? StatsChunkOrigin : T extends Module ? StatsModule : T extends ModuleGraphConnection ? StatsModuleReason : T extends Asset ? StatsAsset : T extends ModuleTrace ? StatsModuleTraceItem : T extends Dependency ? StatsModuleTraceDependency : T extends Error ? StatsError : T extends ModuleProfile ? StatsProfile : F} StatsObject
  55. */
  56. /**
  57. * @template T
  58. * @template F
  59. * @typedef {T extends ChunkGroupInfoWithName[] ? Record<string, StatsObject<ChunkGroupInfoWithName, F>> : T extends (infer V)[] ? StatsObject<V, F>[] : StatsObject<T, F>} CreatedObject
  60. */
  61. /** @typedef {TODO} FactoryData */
  62. /** @typedef {TODO} FactoryDataItem */
  63. /** @typedef {TODO} Result */
  64. /** @typedef {Record<string, TODO>} ObjectForExtract */
  65. /**
  66. * @typedef {object} StatsFactoryHooks
  67. * @property {HookMap<SyncBailHook<[ObjectForExtract, FactoryData, StatsFactoryContext], void>>} extract
  68. * @property {HookMap<SyncBailHook<[FactoryDataItem, StatsFactoryContext, number, number], boolean | void>>} filter
  69. * @property {HookMap<SyncBailHook<[Comparator[], StatsFactoryContext], void>>} sort
  70. * @property {HookMap<SyncBailHook<[FactoryDataItem, StatsFactoryContext, number, number], boolean | void>>} filterSorted
  71. * @property {HookMap<SyncBailHook<[GroupConfig[], StatsFactoryContext], void>>} groupResults
  72. * @property {HookMap<SyncBailHook<[Comparator[], StatsFactoryContext], void>>} sortResults
  73. * @property {HookMap<SyncBailHook<[FactoryDataItem, StatsFactoryContext, number, number], boolean | void>>} filterResults
  74. * @property {HookMap<SyncBailHook<[FactoryDataItem[], StatsFactoryContext], Result | void>>} merge
  75. * @property {HookMap<SyncBailHook<[Result, StatsFactoryContext], Result>>} result
  76. * @property {HookMap<SyncBailHook<[FactoryDataItem, StatsFactoryContext], string | void>>} getItemName
  77. * @property {HookMap<SyncBailHook<[FactoryDataItem, StatsFactoryContext], StatsFactory | void>>} getItemFactory
  78. */
  79. /**
  80. * @template T
  81. * @typedef {Map<string, T[]>} Caches
  82. */
  83. class StatsFactory {
  84. constructor() {
  85. /** @type {StatsFactoryHooks} */
  86. this.hooks = Object.freeze({
  87. extract: new HookMap(
  88. () => new SyncBailHook(["object", "data", "context"])
  89. ),
  90. filter: new HookMap(
  91. () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"])
  92. ),
  93. sort: new HookMap(() => new SyncBailHook(["comparators", "context"])),
  94. filterSorted: new HookMap(
  95. () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"])
  96. ),
  97. groupResults: new HookMap(
  98. () => new SyncBailHook(["groupConfigs", "context"])
  99. ),
  100. sortResults: new HookMap(
  101. () => new SyncBailHook(["comparators", "context"])
  102. ),
  103. filterResults: new HookMap(
  104. () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"])
  105. ),
  106. merge: new HookMap(() => new SyncBailHook(["items", "context"])),
  107. result: new HookMap(() => new SyncWaterfallHook(["result", "context"])),
  108. getItemName: new HookMap(() => new SyncBailHook(["item", "context"])),
  109. getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"]))
  110. });
  111. const hooks = this.hooks;
  112. this._caches = /** @type {TODO} */ ({});
  113. for (const key of Object.keys(hooks)) {
  114. this._caches[/** @type {keyof StatsFactoryHooks} */ (key)] = new Map();
  115. }
  116. this._inCreate = false;
  117. }
  118. /**
  119. * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} HM
  120. * @template {HM extends HookMap<infer H> ? H : never} H
  121. * @param {HM} hookMap hook map
  122. * @param {Caches<H>} cache cache
  123. * @param {string} type type
  124. * @returns {H[]} hooks
  125. * @private
  126. */
  127. _getAllLevelHooks(hookMap, cache, type) {
  128. const cacheEntry = cache.get(type);
  129. if (cacheEntry !== undefined) {
  130. return cacheEntry;
  131. }
  132. const hooks = /** @type {H[]} */ ([]);
  133. const typeParts = type.split(".");
  134. for (let i = 0; i < typeParts.length; i++) {
  135. const hook = /** @type {H} */ (hookMap.get(typeParts.slice(i).join(".")));
  136. if (hook) {
  137. hooks.push(hook);
  138. }
  139. }
  140. cache.set(type, hooks);
  141. return hooks;
  142. }
  143. /**
  144. * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} HM
  145. * @template {HM extends HookMap<infer H> ? H : never} H
  146. * @template {H extends import("tapable").Hook<any, infer R> ? R : never} R
  147. * @param {HM} hookMap hook map
  148. * @param {Caches<H>} cache cache
  149. * @param {string} type type
  150. * @param {(hook: H) => R | void} fn fn
  151. * @returns {R | void} hook
  152. * @private
  153. */
  154. _forEachLevel(hookMap, cache, type, fn) {
  155. for (const hook of this._getAllLevelHooks(hookMap, cache, type)) {
  156. const result = fn(/** @type {H} */ (hook));
  157. if (result !== undefined) return result;
  158. }
  159. }
  160. /**
  161. * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} HM
  162. * @template {HM extends HookMap<infer H> ? H : never} H
  163. * @param {HM} hookMap hook map
  164. * @param {Caches<H>} cache cache
  165. * @param {string} type type
  166. * @param {FactoryData} data data
  167. * @param {(hook: H, factoryData: FactoryData) => FactoryData} fn fn
  168. * @returns {FactoryData} data
  169. * @private
  170. */
  171. _forEachLevelWaterfall(hookMap, cache, type, data, fn) {
  172. for (const hook of this._getAllLevelHooks(hookMap, cache, type)) {
  173. data = fn(/** @type {H} */ (hook), data);
  174. }
  175. return data;
  176. }
  177. /**
  178. * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} T
  179. * @template {T extends HookMap<infer H> ? H : never} H
  180. * @template {H extends import("tapable").Hook<any, infer R> ? R : never} R
  181. * @param {T} hookMap hook map
  182. * @param {Caches<H>} cache cache
  183. * @param {string} type type
  184. * @param {Array<FactoryData>} items items
  185. * @param {(hook: H, item: R, idx: number, i: number) => R | undefined} fn fn
  186. * @param {boolean} forceClone force clone
  187. * @returns {R[]} result for each level
  188. * @private
  189. */
  190. _forEachLevelFilter(hookMap, cache, type, items, fn, forceClone) {
  191. const hooks = this._getAllLevelHooks(hookMap, cache, type);
  192. if (hooks.length === 0) return forceClone ? items.slice() : items;
  193. let i = 0;
  194. return items.filter((item, idx) => {
  195. for (const hook of hooks) {
  196. const r = fn(/** @type {H} */ (hook), item, idx, i);
  197. if (r !== undefined) {
  198. if (r) i++;
  199. return r;
  200. }
  201. }
  202. i++;
  203. return true;
  204. });
  205. }
  206. /**
  207. * @template FactoryData
  208. * @template FallbackCreatedObject
  209. * @param {string} type type
  210. * @param {FactoryData} data factory data
  211. * @param {Omit<StatsFactoryContext, "type">} baseContext context used as base
  212. * @returns {CreatedObject<FactoryData, FallbackCreatedObject>} created object
  213. */
  214. create(type, data, baseContext) {
  215. if (this._inCreate) {
  216. return this._create(type, data, baseContext);
  217. }
  218. try {
  219. this._inCreate = true;
  220. return this._create(type, data, baseContext);
  221. } finally {
  222. for (const key of Object.keys(this._caches))
  223. this._caches[/** @type {keyof StatsFactoryHooks} */ (key)].clear();
  224. this._inCreate = false;
  225. }
  226. }
  227. /**
  228. * @private
  229. * @template FactoryData
  230. * @template FallbackCreatedObject
  231. * @param {string} type type
  232. * @param {FactoryData} data factory data
  233. * @param {Omit<StatsFactoryContext, "type">} baseContext context used as base
  234. * @returns {CreatedObject<FactoryData, FallbackCreatedObject>} created object
  235. */
  236. _create(type, data, baseContext) {
  237. const context = /** @type {StatsFactoryContext} */ ({
  238. ...baseContext,
  239. type,
  240. [type]: data
  241. });
  242. if (Array.isArray(data)) {
  243. // run filter on unsorted items
  244. const items = this._forEachLevelFilter(
  245. this.hooks.filter,
  246. this._caches.filter,
  247. type,
  248. data,
  249. (h, r, idx, i) => h.call(r, context, idx, i),
  250. true
  251. );
  252. // sort items
  253. /** @type {Comparator[]} */
  254. const comparators = [];
  255. this._forEachLevel(this.hooks.sort, this._caches.sort, type, h =>
  256. h.call(comparators, context)
  257. );
  258. if (comparators.length > 0) {
  259. items.sort(
  260. // @ts-expect-error number of arguments is correct
  261. concatComparators(...comparators, keepOriginalOrder(items))
  262. );
  263. }
  264. // run filter on sorted items
  265. const items2 = this._forEachLevelFilter(
  266. this.hooks.filterSorted,
  267. this._caches.filterSorted,
  268. type,
  269. items,
  270. (h, r, idx, i) => h.call(r, context, idx, i),
  271. false
  272. );
  273. // for each item
  274. let resultItems = items2.map((item, i) => {
  275. /** @type {StatsFactoryContext} */
  276. const itemContext = {
  277. ...context,
  278. _index: i
  279. };
  280. // run getItemName
  281. const itemName = this._forEachLevel(
  282. this.hooks.getItemName,
  283. this._caches.getItemName,
  284. `${type}[]`,
  285. h => h.call(item, itemContext)
  286. );
  287. if (itemName) itemContext[itemName] = item;
  288. const innerType = itemName ? `${type}[].${itemName}` : `${type}[]`;
  289. // run getItemFactory
  290. const itemFactory =
  291. this._forEachLevel(
  292. this.hooks.getItemFactory,
  293. this._caches.getItemFactory,
  294. innerType,
  295. h => h.call(item, itemContext)
  296. ) || this;
  297. // run item factory
  298. return itemFactory.create(innerType, item, itemContext);
  299. });
  300. // sort result items
  301. /** @type {Comparator[]} */
  302. const comparators2 = [];
  303. this._forEachLevel(
  304. this.hooks.sortResults,
  305. this._caches.sortResults,
  306. type,
  307. h => h.call(comparators2, context)
  308. );
  309. if (comparators2.length > 0) {
  310. resultItems.sort(
  311. // @ts-expect-error number of arguments is correct
  312. concatComparators(...comparators2, keepOriginalOrder(resultItems))
  313. );
  314. }
  315. // group result items
  316. /** @type {GroupConfig[]} */
  317. const groupConfigs = [];
  318. this._forEachLevel(
  319. this.hooks.groupResults,
  320. this._caches.groupResults,
  321. type,
  322. h => h.call(groupConfigs, context)
  323. );
  324. if (groupConfigs.length > 0) {
  325. resultItems = smartGrouping(resultItems, groupConfigs);
  326. }
  327. // run filter on sorted result items
  328. const finalResultItems = this._forEachLevelFilter(
  329. this.hooks.filterResults,
  330. this._caches.filterResults,
  331. type,
  332. resultItems,
  333. (h, r, idx, i) => h.call(r, context, idx, i),
  334. false
  335. );
  336. // run merge on mapped items
  337. let result = this._forEachLevel(
  338. this.hooks.merge,
  339. this._caches.merge,
  340. type,
  341. h => h.call(finalResultItems, context)
  342. );
  343. if (result === undefined) result = finalResultItems;
  344. // run result on merged items
  345. return this._forEachLevelWaterfall(
  346. this.hooks.result,
  347. this._caches.result,
  348. type,
  349. result,
  350. (h, r) => h.call(r, context)
  351. );
  352. }
  353. /** @type {ObjectForExtract} */
  354. const object = {};
  355. // run extract on value
  356. this._forEachLevel(this.hooks.extract, this._caches.extract, type, h =>
  357. h.call(object, data, context)
  358. );
  359. // run result on extracted object
  360. return this._forEachLevelWaterfall(
  361. this.hooks.result,
  362. this._caches.result,
  363. type,
  364. object,
  365. (h, r) => h.call(r, context)
  366. );
  367. }
  368. }
  369. module.exports = StatsFactory;