ProgressPlugin.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Compiler = require("./Compiler");
  7. const MultiCompiler = require("./MultiCompiler");
  8. const NormalModule = require("./NormalModule");
  9. const createSchemaValidation = require("./util/create-schema-validation");
  10. const { contextify } = require("./util/identifier");
  11. /** @typedef {import("tapable").Tap} Tap */
  12. /** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */
  13. /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
  14. /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */
  15. /** @typedef {import("./Dependency")} Dependency */
  16. /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
  17. /** @typedef {import("./Module")} Module */
  18. /** @typedef {import("./logging/Logger").Logger} Logger */
  19. /**
  20. * @typedef {object} CountsData
  21. * @property {number} modulesCount modules count
  22. * @property {number} dependenciesCount dependencies count
  23. */
  24. const validate = createSchemaValidation(
  25. require("../schemas/plugins/ProgressPlugin.check.js"),
  26. () => require("../schemas/plugins/ProgressPlugin.json"),
  27. {
  28. name: "Progress Plugin",
  29. baseDataPath: "options"
  30. }
  31. );
  32. /**
  33. * @param {number} a a
  34. * @param {number} b b
  35. * @param {number} c c
  36. * @returns {number} median
  37. */
  38. const median3 = (a, b, c) => {
  39. return a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
  40. };
  41. /**
  42. * @param {boolean | null | undefined} profile need profile
  43. * @param {Logger} logger logger
  44. * @returns {defaultHandler} default handler
  45. */
  46. const createDefaultHandler = (profile, logger) => {
  47. /** @type {{ value: string | undefined, time: number }[]} */
  48. const lastStateInfo = [];
  49. /**
  50. * @param {number} percentage percentage
  51. * @param {string} msg message
  52. * @param {...string} args additional arguments
  53. */
  54. const defaultHandler = (percentage, msg, ...args) => {
  55. if (profile) {
  56. if (percentage === 0) {
  57. lastStateInfo.length = 0;
  58. }
  59. const fullState = [msg, ...args];
  60. const state = fullState.map(s => s.replace(/\d+\/\d+ /g, ""));
  61. const now = Date.now();
  62. const len = Math.max(state.length, lastStateInfo.length);
  63. for (let i = len; i >= 0; i--) {
  64. const stateItem = i < state.length ? state[i] : undefined;
  65. const lastStateItem =
  66. i < lastStateInfo.length ? lastStateInfo[i] : undefined;
  67. if (lastStateItem) {
  68. if (stateItem !== lastStateItem.value) {
  69. const diff = now - lastStateItem.time;
  70. if (lastStateItem.value) {
  71. let reportState = lastStateItem.value;
  72. if (i > 0) {
  73. reportState = lastStateInfo[i - 1].value + " > " + reportState;
  74. }
  75. const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
  76. const d = diff;
  77. // This depends on timing so we ignore it for coverage
  78. /* istanbul ignore next */
  79. {
  80. if (d > 10000) {
  81. logger.error(stateMsg);
  82. } else if (d > 1000) {
  83. logger.warn(stateMsg);
  84. } else if (d > 10) {
  85. logger.info(stateMsg);
  86. } else if (d > 5) {
  87. logger.log(stateMsg);
  88. } else {
  89. logger.debug(stateMsg);
  90. }
  91. }
  92. }
  93. if (stateItem === undefined) {
  94. lastStateInfo.length = i;
  95. } else {
  96. lastStateItem.value = stateItem;
  97. lastStateItem.time = now;
  98. lastStateInfo.length = i + 1;
  99. }
  100. }
  101. } else {
  102. lastStateInfo[i] = {
  103. value: stateItem,
  104. time: now
  105. };
  106. }
  107. }
  108. }
  109. logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args);
  110. if (percentage === 1 || (!msg && args.length === 0)) logger.status();
  111. };
  112. return defaultHandler;
  113. };
  114. /**
  115. * @callback ReportProgress
  116. * @param {number} p percentage
  117. * @param {...string} args additional arguments
  118. * @returns {void}
  119. */
  120. /** @type {WeakMap<Compiler, ReportProgress | undefined>} */
  121. const progressReporters = new WeakMap();
  122. class ProgressPlugin {
  123. /**
  124. * @param {Compiler} compiler the current compiler
  125. * @returns {ReportProgress | undefined} a progress reporter, if any
  126. */
  127. static getReporter(compiler) {
  128. return progressReporters.get(compiler);
  129. }
  130. /**
  131. * @param {ProgressPluginArgument} options options
  132. */
  133. constructor(options = {}) {
  134. if (typeof options === "function") {
  135. options = {
  136. handler: options
  137. };
  138. }
  139. validate(options);
  140. options = { ...ProgressPlugin.defaultOptions, ...options };
  141. this.profile = options.profile;
  142. this.handler = options.handler;
  143. this.modulesCount = options.modulesCount;
  144. this.dependenciesCount = options.dependenciesCount;
  145. this.showEntries = options.entries;
  146. this.showModules = options.modules;
  147. this.showDependencies = options.dependencies;
  148. this.showActiveModules = options.activeModules;
  149. this.percentBy = options.percentBy;
  150. }
  151. /**
  152. * @param {Compiler | MultiCompiler} compiler webpack compiler
  153. * @returns {void}
  154. */
  155. apply(compiler) {
  156. const handler =
  157. this.handler ||
  158. createDefaultHandler(
  159. this.profile,
  160. compiler.getInfrastructureLogger("webpack.Progress")
  161. );
  162. if (compiler instanceof MultiCompiler) {
  163. this._applyOnMultiCompiler(compiler, handler);
  164. } else if (compiler instanceof Compiler) {
  165. this._applyOnCompiler(compiler, handler);
  166. }
  167. }
  168. /**
  169. * @param {MultiCompiler} compiler webpack multi-compiler
  170. * @param {HandlerFunction} handler function that executes for every progress step
  171. * @returns {void}
  172. */
  173. _applyOnMultiCompiler(compiler, handler) {
  174. const states = compiler.compilers.map(
  175. () => /** @type {[number, ...string[]]} */ ([0])
  176. );
  177. compiler.compilers.forEach((compiler, idx) => {
  178. new ProgressPlugin((p, msg, ...args) => {
  179. states[idx] = [p, msg, ...args];
  180. let sum = 0;
  181. for (const [p] of states) sum += p;
  182. handler(sum / states.length, `[${idx}] ${msg}`, ...args);
  183. }).apply(compiler);
  184. });
  185. }
  186. /**
  187. * @param {Compiler} compiler webpack compiler
  188. * @param {HandlerFunction} handler function that executes for every progress step
  189. * @returns {void}
  190. */
  191. _applyOnCompiler(compiler, handler) {
  192. const showEntries = this.showEntries;
  193. const showModules = this.showModules;
  194. const showDependencies = this.showDependencies;
  195. const showActiveModules = this.showActiveModules;
  196. let lastActiveModule = "";
  197. let currentLoader = "";
  198. let lastModulesCount = 0;
  199. let lastDependenciesCount = 0;
  200. let lastEntriesCount = 0;
  201. let modulesCount = 0;
  202. let dependenciesCount = 0;
  203. let entriesCount = 1;
  204. let doneModules = 0;
  205. let doneDependencies = 0;
  206. let doneEntries = 0;
  207. const activeModules = new Set();
  208. let lastUpdate = 0;
  209. const updateThrottled = () => {
  210. if (lastUpdate + 500 < Date.now()) update();
  211. };
  212. const update = () => {
  213. /** @type {string[]} */
  214. const items = [];
  215. const percentByModules =
  216. doneModules /
  217. Math.max(lastModulesCount || this.modulesCount || 1, modulesCount);
  218. const percentByEntries =
  219. doneEntries /
  220. Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount);
  221. const percentByDependencies =
  222. doneDependencies /
  223. Math.max(lastDependenciesCount || 1, dependenciesCount);
  224. let percentageFactor;
  225. switch (this.percentBy) {
  226. case "entries":
  227. percentageFactor = percentByEntries;
  228. break;
  229. case "dependencies":
  230. percentageFactor = percentByDependencies;
  231. break;
  232. case "modules":
  233. percentageFactor = percentByModules;
  234. break;
  235. default:
  236. percentageFactor = median3(
  237. percentByModules,
  238. percentByEntries,
  239. percentByDependencies
  240. );
  241. }
  242. const percentage = 0.1 + percentageFactor * 0.55;
  243. if (currentLoader) {
  244. items.push(
  245. `import loader ${contextify(
  246. compiler.context,
  247. currentLoader,
  248. compiler.root
  249. )}`
  250. );
  251. } else {
  252. const statItems = [];
  253. if (showEntries) {
  254. statItems.push(`${doneEntries}/${entriesCount} entries`);
  255. }
  256. if (showDependencies) {
  257. statItems.push(
  258. `${doneDependencies}/${dependenciesCount} dependencies`
  259. );
  260. }
  261. if (showModules) {
  262. statItems.push(`${doneModules}/${modulesCount} modules`);
  263. }
  264. if (showActiveModules) {
  265. statItems.push(`${activeModules.size} active`);
  266. }
  267. if (statItems.length > 0) {
  268. items.push(statItems.join(" "));
  269. }
  270. if (showActiveModules) {
  271. items.push(lastActiveModule);
  272. }
  273. }
  274. handler(percentage, "building", ...items);
  275. lastUpdate = Date.now();
  276. };
  277. const factorizeAdd = () => {
  278. dependenciesCount++;
  279. if (dependenciesCount < 50 || dependenciesCount % 100 === 0)
  280. updateThrottled();
  281. };
  282. const factorizeDone = () => {
  283. doneDependencies++;
  284. if (doneDependencies < 50 || doneDependencies % 100 === 0)
  285. updateThrottled();
  286. };
  287. const moduleAdd = () => {
  288. modulesCount++;
  289. if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled();
  290. };
  291. // only used when showActiveModules is set
  292. /**
  293. * @param {Module} module the module
  294. */
  295. const moduleBuild = module => {
  296. const ident = module.identifier();
  297. if (ident) {
  298. activeModules.add(ident);
  299. lastActiveModule = ident;
  300. update();
  301. }
  302. };
  303. /**
  304. * @param {Dependency} entry entry dependency
  305. * @param {EntryOptions} options options object
  306. */
  307. const entryAdd = (entry, options) => {
  308. entriesCount++;
  309. if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled();
  310. };
  311. /**
  312. * @param {Module} module the module
  313. */
  314. const moduleDone = module => {
  315. doneModules++;
  316. if (showActiveModules) {
  317. const ident = module.identifier();
  318. if (ident) {
  319. activeModules.delete(ident);
  320. if (lastActiveModule === ident) {
  321. lastActiveModule = "";
  322. for (const m of activeModules) {
  323. lastActiveModule = m;
  324. }
  325. update();
  326. return;
  327. }
  328. }
  329. }
  330. if (doneModules < 50 || doneModules % 100 === 0) updateThrottled();
  331. };
  332. /**
  333. * @param {Dependency} entry entry dependency
  334. * @param {EntryOptions} options options object
  335. */
  336. const entryDone = (entry, options) => {
  337. doneEntries++;
  338. update();
  339. };
  340. const cache = compiler
  341. .getCache("ProgressPlugin")
  342. .getItemCache("counts", null);
  343. /** @type {Promise<CountsData> | undefined} */
  344. let cacheGetPromise;
  345. compiler.hooks.beforeCompile.tap("ProgressPlugin", () => {
  346. if (!cacheGetPromise) {
  347. cacheGetPromise = cache.getPromise().then(
  348. data => {
  349. if (data) {
  350. lastModulesCount = lastModulesCount || data.modulesCount;
  351. lastDependenciesCount =
  352. lastDependenciesCount || data.dependenciesCount;
  353. }
  354. return data;
  355. },
  356. err => {
  357. // Ignore error
  358. }
  359. );
  360. }
  361. });
  362. compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => {
  363. if (compilation.compiler.isChild()) return Promise.resolve();
  364. return /** @type {Promise<CountsData>} */ (cacheGetPromise).then(
  365. async oldData => {
  366. if (
  367. !oldData ||
  368. oldData.modulesCount !== modulesCount ||
  369. oldData.dependenciesCount !== dependenciesCount
  370. ) {
  371. await cache.storePromise({ modulesCount, dependenciesCount });
  372. }
  373. }
  374. );
  375. });
  376. compiler.hooks.compilation.tap("ProgressPlugin", compilation => {
  377. if (compilation.compiler.isChild()) return;
  378. lastModulesCount = modulesCount;
  379. lastEntriesCount = entriesCount;
  380. lastDependenciesCount = dependenciesCount;
  381. modulesCount = dependenciesCount = entriesCount = 0;
  382. doneModules = doneDependencies = doneEntries = 0;
  383. compilation.factorizeQueue.hooks.added.tap(
  384. "ProgressPlugin",
  385. factorizeAdd
  386. );
  387. compilation.factorizeQueue.hooks.result.tap(
  388. "ProgressPlugin",
  389. factorizeDone
  390. );
  391. compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd);
  392. compilation.processDependenciesQueue.hooks.result.tap(
  393. "ProgressPlugin",
  394. moduleDone
  395. );
  396. if (showActiveModules) {
  397. compilation.hooks.buildModule.tap("ProgressPlugin", moduleBuild);
  398. }
  399. compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd);
  400. compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone);
  401. compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone);
  402. // avoid dynamic require if bundled with webpack
  403. // @ts-expect-error
  404. if (typeof __webpack_require__ !== "function") {
  405. const requiredLoaders = new Set();
  406. NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
  407. "ProgressPlugin",
  408. loaders => {
  409. for (const loader of loaders) {
  410. if (
  411. loader.type !== "module" &&
  412. !requiredLoaders.has(loader.loader)
  413. ) {
  414. requiredLoaders.add(loader.loader);
  415. currentLoader = loader.loader;
  416. update();
  417. require(loader.loader);
  418. }
  419. }
  420. if (currentLoader) {
  421. currentLoader = "";
  422. update();
  423. }
  424. }
  425. );
  426. }
  427. const hooks = {
  428. finishModules: "finish module graph",
  429. seal: "plugins",
  430. optimizeDependencies: "dependencies optimization",
  431. afterOptimizeDependencies: "after dependencies optimization",
  432. beforeChunks: "chunk graph",
  433. afterChunks: "after chunk graph",
  434. optimize: "optimizing",
  435. optimizeModules: "module optimization",
  436. afterOptimizeModules: "after module optimization",
  437. optimizeChunks: "chunk optimization",
  438. afterOptimizeChunks: "after chunk optimization",
  439. optimizeTree: "module and chunk tree optimization",
  440. afterOptimizeTree: "after module and chunk tree optimization",
  441. optimizeChunkModules: "chunk modules optimization",
  442. afterOptimizeChunkModules: "after chunk modules optimization",
  443. reviveModules: "module reviving",
  444. beforeModuleIds: "before module ids",
  445. moduleIds: "module ids",
  446. optimizeModuleIds: "module id optimization",
  447. afterOptimizeModuleIds: "module id optimization",
  448. reviveChunks: "chunk reviving",
  449. beforeChunkIds: "before chunk ids",
  450. chunkIds: "chunk ids",
  451. optimizeChunkIds: "chunk id optimization",
  452. afterOptimizeChunkIds: "after chunk id optimization",
  453. recordModules: "record modules",
  454. recordChunks: "record chunks",
  455. beforeModuleHash: "module hashing",
  456. beforeCodeGeneration: "code generation",
  457. beforeRuntimeRequirements: "runtime requirements",
  458. beforeHash: "hashing",
  459. afterHash: "after hashing",
  460. recordHash: "record hash",
  461. beforeModuleAssets: "module assets processing",
  462. beforeChunkAssets: "chunk assets processing",
  463. processAssets: "asset processing",
  464. afterProcessAssets: "after asset optimization",
  465. record: "recording",
  466. afterSeal: "after seal"
  467. };
  468. const numberOfHooks = Object.keys(hooks).length;
  469. Object.keys(hooks).forEach((name, idx) => {
  470. const title = hooks[/** @type {keyof typeof hooks} */ (name)];
  471. const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
  472. compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
  473. name: "ProgressPlugin",
  474. call() {
  475. handler(percentage, "sealing", title);
  476. },
  477. done() {
  478. progressReporters.set(compiler, undefined);
  479. handler(percentage, "sealing", title);
  480. },
  481. result() {
  482. handler(percentage, "sealing", title);
  483. },
  484. error() {
  485. handler(percentage, "sealing", title);
  486. },
  487. tap(tap) {
  488. // p is percentage from 0 to 1
  489. // args is any number of messages in a hierarchical matter
  490. progressReporters.set(compilation.compiler, (p, ...args) => {
  491. handler(percentage, "sealing", title, tap.name, ...args);
  492. });
  493. handler(percentage, "sealing", title, tap.name);
  494. }
  495. });
  496. });
  497. });
  498. compiler.hooks.make.intercept({
  499. name: "ProgressPlugin",
  500. call() {
  501. handler(0.1, "building");
  502. },
  503. done() {
  504. handler(0.65, "building");
  505. }
  506. });
  507. /**
  508. * @param {TODO} hook hook
  509. * @param {number} progress progress from 0 to 1
  510. * @param {string} category category
  511. * @param {string} name name
  512. */
  513. const interceptHook = (hook, progress, category, name) => {
  514. hook.intercept({
  515. name: "ProgressPlugin",
  516. call() {
  517. handler(progress, category, name);
  518. },
  519. done() {
  520. progressReporters.set(compiler, undefined);
  521. handler(progress, category, name);
  522. },
  523. result() {
  524. handler(progress, category, name);
  525. },
  526. error() {
  527. handler(progress, category, name);
  528. },
  529. /**
  530. * @param {Tap} tap tap
  531. */
  532. tap(tap) {
  533. progressReporters.set(compiler, (p, ...args) => {
  534. handler(progress, category, name, tap.name, ...args);
  535. });
  536. handler(progress, category, name, tap.name);
  537. }
  538. });
  539. };
  540. compiler.cache.hooks.endIdle.intercept({
  541. name: "ProgressPlugin",
  542. call() {
  543. handler(0, "");
  544. }
  545. });
  546. interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle");
  547. compiler.hooks.beforeRun.intercept({
  548. name: "ProgressPlugin",
  549. call() {
  550. handler(0, "");
  551. }
  552. });
  553. interceptHook(compiler.hooks.beforeRun, 0.01, "setup", "before run");
  554. interceptHook(compiler.hooks.run, 0.02, "setup", "run");
  555. interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run");
  556. interceptHook(
  557. compiler.hooks.normalModuleFactory,
  558. 0.04,
  559. "setup",
  560. "normal module factory"
  561. );
  562. interceptHook(
  563. compiler.hooks.contextModuleFactory,
  564. 0.05,
  565. "setup",
  566. "context module factory"
  567. );
  568. interceptHook(
  569. compiler.hooks.beforeCompile,
  570. 0.06,
  571. "setup",
  572. "before compile"
  573. );
  574. interceptHook(compiler.hooks.compile, 0.07, "setup", "compile");
  575. interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation");
  576. interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation");
  577. interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish");
  578. interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit");
  579. interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit");
  580. interceptHook(compiler.hooks.done, 0.99, "done", "plugins");
  581. compiler.hooks.done.intercept({
  582. name: "ProgressPlugin",
  583. done() {
  584. handler(0.99, "");
  585. }
  586. });
  587. interceptHook(
  588. compiler.cache.hooks.storeBuildDependencies,
  589. 0.99,
  590. "cache",
  591. "store build dependencies"
  592. );
  593. interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown");
  594. interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle");
  595. interceptHook(
  596. compiler.hooks.watchClose,
  597. 0.99,
  598. "end",
  599. "closing watch compilation"
  600. );
  601. compiler.cache.hooks.beginIdle.intercept({
  602. name: "ProgressPlugin",
  603. done() {
  604. handler(1, "");
  605. }
  606. });
  607. compiler.cache.hooks.shutdown.intercept({
  608. name: "ProgressPlugin",
  609. done() {
  610. handler(1, "");
  611. }
  612. });
  613. }
  614. }
  615. ProgressPlugin.defaultOptions = {
  616. profile: false,
  617. modulesCount: 5000,
  618. dependenciesCount: 10000,
  619. modules: true,
  620. dependencies: true,
  621. activeModules: false,
  622. entries: true
  623. };
  624. ProgressPlugin.createDefaultHandler = createDefaultHandler;
  625. module.exports = ProgressPlugin;