MultiCompiler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("neo-async");
  7. const { SyncHook, MultiHook } = require("tapable");
  8. const ConcurrentCompilationError = require("./ConcurrentCompilationError");
  9. const MultiStats = require("./MultiStats");
  10. const MultiWatching = require("./MultiWatching");
  11. const WebpackError = require("./WebpackError");
  12. const ArrayQueue = require("./util/ArrayQueue");
  13. /** @template T @typedef {import("tapable").AsyncSeriesHook<T>} AsyncSeriesHook<T> */
  14. /** @template T @template R @typedef {import("tapable").SyncBailHook<T, R>} SyncBailHook<T, R> */
  15. /** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
  16. /** @typedef {import("./Compiler")} Compiler */
  17. /** @typedef {import("./Stats")} Stats */
  18. /** @typedef {import("./Watching")} Watching */
  19. /** @typedef {import("./logging/Logger").Logger} Logger */
  20. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  21. /** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
  22. /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
  23. /** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
  24. /**
  25. * @template T
  26. * @callback Callback
  27. * @param {Error | null} err
  28. * @param {T=} result
  29. */
  30. /**
  31. * @callback RunWithDependenciesHandler
  32. * @param {Compiler} compiler
  33. * @param {Callback<MultiStats>} callback
  34. */
  35. /**
  36. * @typedef {object} MultiCompilerOptions
  37. * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel
  38. */
  39. const CLASS_NAME = "MultiCompiler";
  40. module.exports = class MultiCompiler {
  41. /**
  42. * @param {Compiler[] | Record<string, Compiler>} compilers child compilers
  43. * @param {MultiCompilerOptions} options options
  44. */
  45. constructor(compilers, options) {
  46. if (!Array.isArray(compilers)) {
  47. /** @type {Compiler[]} */
  48. compilers = Object.keys(compilers).map(name => {
  49. /** @type {Record<string, Compiler>} */
  50. (compilers)[name].name = name;
  51. return /** @type {Record<string, Compiler>} */ (compilers)[name];
  52. });
  53. }
  54. this.hooks = Object.freeze({
  55. /** @type {SyncHook<[MultiStats]>} */
  56. done: new SyncHook(["stats"]),
  57. /** @type {MultiHook<SyncHook<[string | null, number]>>} */
  58. invalid: new MultiHook(compilers.map(c => c.hooks.invalid)),
  59. /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
  60. run: new MultiHook(compilers.map(c => c.hooks.run)),
  61. /** @type {SyncHook<[]>} */
  62. watchClose: new SyncHook([]),
  63. /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
  64. watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)),
  65. /** @type {MultiHook<SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>>} */
  66. infrastructureLog: new MultiHook(
  67. compilers.map(c => c.hooks.infrastructureLog)
  68. )
  69. });
  70. this.compilers = compilers;
  71. /** @type {MultiCompilerOptions} */
  72. this._options = {
  73. parallelism: options.parallelism || Infinity
  74. };
  75. /** @type {WeakMap<Compiler, string[]>} */
  76. this.dependencies = new WeakMap();
  77. this.running = false;
  78. /** @type {(Stats | null)[]} */
  79. const compilerStats = this.compilers.map(() => null);
  80. let doneCompilers = 0;
  81. for (let index = 0; index < this.compilers.length; index++) {
  82. const compiler = this.compilers[index];
  83. const compilerIndex = index;
  84. let compilerDone = false;
  85. // eslint-disable-next-line no-loop-func
  86. compiler.hooks.done.tap(CLASS_NAME, stats => {
  87. if (!compilerDone) {
  88. compilerDone = true;
  89. doneCompilers++;
  90. }
  91. compilerStats[compilerIndex] = stats;
  92. if (doneCompilers === this.compilers.length) {
  93. this.hooks.done.call(
  94. new MultiStats(/** @type {Stats[]} */ (compilerStats))
  95. );
  96. }
  97. });
  98. // eslint-disable-next-line no-loop-func
  99. compiler.hooks.invalid.tap(CLASS_NAME, () => {
  100. if (compilerDone) {
  101. compilerDone = false;
  102. doneCompilers--;
  103. }
  104. });
  105. }
  106. this._validateCompilersOptions();
  107. }
  108. _validateCompilersOptions() {
  109. if (this.compilers.length < 2) return;
  110. /**
  111. * @param {Compiler} compiler compiler
  112. * @param {WebpackError} warning warning
  113. */
  114. const addWarning = (compiler, warning) => {
  115. compiler.hooks.thisCompilation.tap(CLASS_NAME, compilation => {
  116. compilation.warnings.push(warning);
  117. });
  118. };
  119. const cacheNames = new Set();
  120. for (const compiler of this.compilers) {
  121. if (compiler.options.cache && "name" in compiler.options.cache) {
  122. const name = compiler.options.cache.name;
  123. if (cacheNames.has(name)) {
  124. addWarning(
  125. compiler,
  126. new WebpackError(
  127. `${
  128. compiler.name
  129. ? `Compiler with name "${compiler.name}" doesn't use unique cache name. `
  130. : ""
  131. }Please set unique "cache.name" option. Name "${name}" already used.`
  132. )
  133. );
  134. } else {
  135. cacheNames.add(name);
  136. }
  137. }
  138. }
  139. }
  140. get options() {
  141. return Object.assign(
  142. this.compilers.map(c => c.options),
  143. this._options
  144. );
  145. }
  146. get outputPath() {
  147. let commonPath = this.compilers[0].outputPath;
  148. for (const compiler of this.compilers) {
  149. while (
  150. compiler.outputPath.indexOf(commonPath) !== 0 &&
  151. /[/\\]/.test(commonPath)
  152. ) {
  153. commonPath = commonPath.replace(/[/\\][^/\\]*$/, "");
  154. }
  155. }
  156. if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/";
  157. return commonPath;
  158. }
  159. get inputFileSystem() {
  160. throw new Error("Cannot read inputFileSystem of a MultiCompiler");
  161. }
  162. /**
  163. * @param {InputFileSystem} value the new input file system
  164. */
  165. set inputFileSystem(value) {
  166. for (const compiler of this.compilers) {
  167. compiler.inputFileSystem = value;
  168. }
  169. }
  170. get outputFileSystem() {
  171. throw new Error("Cannot read outputFileSystem of a MultiCompiler");
  172. }
  173. /**
  174. * @param {OutputFileSystem} value the new output file system
  175. */
  176. set outputFileSystem(value) {
  177. for (const compiler of this.compilers) {
  178. compiler.outputFileSystem = value;
  179. }
  180. }
  181. get watchFileSystem() {
  182. throw new Error("Cannot read watchFileSystem of a MultiCompiler");
  183. }
  184. /**
  185. * @param {WatchFileSystem} value the new watch file system
  186. */
  187. set watchFileSystem(value) {
  188. for (const compiler of this.compilers) {
  189. compiler.watchFileSystem = value;
  190. }
  191. }
  192. /**
  193. * @param {IntermediateFileSystem} value the new intermediate file system
  194. */
  195. set intermediateFileSystem(value) {
  196. for (const compiler of this.compilers) {
  197. compiler.intermediateFileSystem = value;
  198. }
  199. }
  200. get intermediateFileSystem() {
  201. throw new Error("Cannot read outputFileSystem of a MultiCompiler");
  202. }
  203. /**
  204. * @param {string | (() => string)} name name of the logger, or function called once to get the logger name
  205. * @returns {Logger} a logger with that name
  206. */
  207. getInfrastructureLogger(name) {
  208. return this.compilers[0].getInfrastructureLogger(name);
  209. }
  210. /**
  211. * @param {Compiler} compiler the child compiler
  212. * @param {string[]} dependencies its dependencies
  213. * @returns {void}
  214. */
  215. setDependencies(compiler, dependencies) {
  216. this.dependencies.set(compiler, dependencies);
  217. }
  218. /**
  219. * @param {Callback<MultiStats>} callback signals when the validation is complete
  220. * @returns {boolean} true if the dependencies are valid
  221. */
  222. validateDependencies(callback) {
  223. /** @type {Set<{source: Compiler, target: Compiler}>} */
  224. const edges = new Set();
  225. /** @type {string[]} */
  226. const missing = [];
  227. /**
  228. * @param {Compiler} compiler compiler
  229. * @returns {boolean} target was found
  230. */
  231. const targetFound = compiler => {
  232. for (const edge of edges) {
  233. if (edge.target === compiler) {
  234. return true;
  235. }
  236. }
  237. return false;
  238. };
  239. /**
  240. * @param {{source: Compiler, target: Compiler}} e1 edge 1
  241. * @param {{source: Compiler, target: Compiler}} e2 edge 2
  242. * @returns {number} result
  243. */
  244. const sortEdges = (e1, e2) =>
  245. /** @type {string} */
  246. (e1.source.name).localeCompare(/** @type {string} */ (e2.source.name)) ||
  247. /** @type {string} */
  248. (e1.target.name).localeCompare(/** @type {string} */ (e2.target.name));
  249. for (const source of this.compilers) {
  250. const dependencies = this.dependencies.get(source);
  251. if (dependencies) {
  252. for (const dep of dependencies) {
  253. const target = this.compilers.find(c => c.name === dep);
  254. if (!target) {
  255. missing.push(dep);
  256. } else {
  257. edges.add({
  258. source,
  259. target
  260. });
  261. }
  262. }
  263. }
  264. }
  265. /** @type {string[]} */
  266. const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`);
  267. const stack = this.compilers.filter(c => !targetFound(c));
  268. while (stack.length > 0) {
  269. const current = stack.pop();
  270. for (const edge of edges) {
  271. if (edge.source === current) {
  272. edges.delete(edge);
  273. const target = edge.target;
  274. if (!targetFound(target)) {
  275. stack.push(target);
  276. }
  277. }
  278. }
  279. }
  280. if (edges.size > 0) {
  281. /** @type {string[]} */
  282. const lines = Array.from(edges)
  283. .sort(sortEdges)
  284. .map(edge => `${edge.source.name} -> ${edge.target.name}`);
  285. lines.unshift("Circular dependency found in compiler dependencies.");
  286. errors.unshift(lines.join("\n"));
  287. }
  288. if (errors.length > 0) {
  289. const message = errors.join("\n");
  290. callback(new Error(message));
  291. return false;
  292. }
  293. return true;
  294. }
  295. // TODO webpack 6 remove
  296. /**
  297. * @deprecated This method should have been private
  298. * @param {Compiler[]} compilers the child compilers
  299. * @param {RunWithDependenciesHandler} fn a handler to run for each compiler
  300. * @param {Callback<MultiStats>} callback the compiler's handler
  301. * @returns {void}
  302. */
  303. runWithDependencies(compilers, fn, callback) {
  304. const fulfilledNames = new Set();
  305. let remainingCompilers = compilers;
  306. /**
  307. * @param {string} d dependency
  308. * @returns {boolean} when dependency was fulfilled
  309. */
  310. const isDependencyFulfilled = d => fulfilledNames.has(d);
  311. /**
  312. * @returns {Compiler[]} compilers
  313. */
  314. const getReadyCompilers = () => {
  315. const readyCompilers = [];
  316. const list = remainingCompilers;
  317. remainingCompilers = [];
  318. for (const c of list) {
  319. const dependencies = this.dependencies.get(c);
  320. const ready =
  321. !dependencies || dependencies.every(isDependencyFulfilled);
  322. if (ready) {
  323. readyCompilers.push(c);
  324. } else {
  325. remainingCompilers.push(c);
  326. }
  327. }
  328. return readyCompilers;
  329. };
  330. /**
  331. * @param {Callback<MultiStats>} callback callback
  332. * @returns {void}
  333. */
  334. const runCompilers = callback => {
  335. if (remainingCompilers.length === 0) return callback(null);
  336. asyncLib.map(
  337. getReadyCompilers(),
  338. (compiler, callback) => {
  339. fn(compiler, err => {
  340. if (err) return callback(err);
  341. fulfilledNames.add(compiler.name);
  342. runCompilers(callback);
  343. });
  344. },
  345. (err, results) => {
  346. callback(err, /** @type {TODO} */ (results));
  347. }
  348. );
  349. };
  350. runCompilers(callback);
  351. }
  352. /**
  353. * @template SetupResult
  354. * @param {(compiler: Compiler, index: number, doneCallback: Callback<Stats>, isBlocked: () => boolean, setChanged: () => void, setInvalid: () => void) => SetupResult} setup setup a single compiler
  355. * @param {(compiler: Compiler, setupResult: SetupResult, callback: Callback<Stats>) => void} run run/continue a single compiler
  356. * @param {Callback<MultiStats>} callback callback when all compilers are done, result includes Stats of all changed compilers
  357. * @returns {SetupResult[]} result of setup
  358. */
  359. _runGraph(setup, run, callback) {
  360. /** @typedef {{ compiler: Compiler, setupResult: undefined | SetupResult, result: undefined | Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */
  361. // State transitions for nodes:
  362. // -> blocked (initial)
  363. // blocked -> starting [running++] (when all parents done)
  364. // queued -> starting [running++] (when processing the queue)
  365. // starting -> running (when run has been called)
  366. // running -> done [running--] (when compilation is done)
  367. // done -> pending (when invalidated from file change)
  368. // pending -> blocked [add to queue] (when invalidated from aggregated changes)
  369. // done -> blocked [add to queue] (when invalidated, from parent invalidation)
  370. // running -> running-outdated (when invalidated, either from change or parent invalidation)
  371. // running-outdated -> blocked [running--] (when compilation is done)
  372. /** @type {Node[]} */
  373. const nodes = this.compilers.map(compiler => ({
  374. compiler,
  375. setupResult: undefined,
  376. result: undefined,
  377. state: "blocked",
  378. children: [],
  379. parents: []
  380. }));
  381. /** @type {Map<string, Node>} */
  382. const compilerToNode = new Map();
  383. for (const node of nodes) {
  384. compilerToNode.set(/** @type {string} */ (node.compiler.name), node);
  385. }
  386. for (const node of nodes) {
  387. const dependencies = this.dependencies.get(node.compiler);
  388. if (!dependencies) continue;
  389. for (const dep of dependencies) {
  390. const parent = /** @type {Node} */ (compilerToNode.get(dep));
  391. node.parents.push(parent);
  392. parent.children.push(node);
  393. }
  394. }
  395. /** @type {ArrayQueue<Node>} */
  396. const queue = new ArrayQueue();
  397. for (const node of nodes) {
  398. if (node.parents.length === 0) {
  399. node.state = "queued";
  400. queue.enqueue(node);
  401. }
  402. }
  403. let errored = false;
  404. let running = 0;
  405. const parallelism = /** @type {number} */ (this._options.parallelism);
  406. /**
  407. * @param {Node} node node
  408. * @param {(Error | null)=} err error
  409. * @param {Stats=} stats result
  410. * @returns {void}
  411. */
  412. const nodeDone = (node, err, stats) => {
  413. if (errored) return;
  414. if (err) {
  415. errored = true;
  416. return asyncLib.each(
  417. nodes,
  418. (node, callback) => {
  419. if (node.compiler.watching) {
  420. node.compiler.watching.close(callback);
  421. } else {
  422. callback();
  423. }
  424. },
  425. () => callback(err)
  426. );
  427. }
  428. node.result = stats;
  429. running--;
  430. if (node.state === "running") {
  431. node.state = "done";
  432. for (const child of node.children) {
  433. if (child.state === "blocked") queue.enqueue(child);
  434. }
  435. } else if (node.state === "running-outdated") {
  436. node.state = "blocked";
  437. queue.enqueue(node);
  438. }
  439. processQueue();
  440. };
  441. /**
  442. * @param {Node} node node
  443. * @returns {void}
  444. */
  445. const nodeInvalidFromParent = node => {
  446. if (node.state === "done") {
  447. node.state = "blocked";
  448. } else if (node.state === "running") {
  449. node.state = "running-outdated";
  450. }
  451. for (const child of node.children) {
  452. nodeInvalidFromParent(child);
  453. }
  454. };
  455. /**
  456. * @param {Node} node node
  457. * @returns {void}
  458. */
  459. const nodeInvalid = node => {
  460. if (node.state === "done") {
  461. node.state = "pending";
  462. } else if (node.state === "running") {
  463. node.state = "running-outdated";
  464. }
  465. for (const child of node.children) {
  466. nodeInvalidFromParent(child);
  467. }
  468. };
  469. /**
  470. * @param {Node} node node
  471. * @returns {void}
  472. */
  473. const nodeChange = node => {
  474. nodeInvalid(node);
  475. if (node.state === "pending") {
  476. node.state = "blocked";
  477. }
  478. if (node.state === "blocked") {
  479. queue.enqueue(node);
  480. processQueue();
  481. }
  482. };
  483. /** @type {SetupResult[]} */
  484. const setupResults = [];
  485. for (const [i, node] of nodes.entries()) {
  486. setupResults.push(
  487. (node.setupResult = setup(
  488. node.compiler,
  489. i,
  490. nodeDone.bind(null, node),
  491. () => node.state !== "starting" && node.state !== "running",
  492. () => nodeChange(node),
  493. () => nodeInvalid(node)
  494. ))
  495. );
  496. }
  497. let processing = true;
  498. const processQueue = () => {
  499. if (processing) return;
  500. processing = true;
  501. process.nextTick(processQueueWorker);
  502. };
  503. const processQueueWorker = () => {
  504. // eslint-disable-next-line no-unmodified-loop-condition
  505. while (running < parallelism && queue.length > 0 && !errored) {
  506. const node = /** @type {Node} */ (queue.dequeue());
  507. if (
  508. node.state === "queued" ||
  509. (node.state === "blocked" &&
  510. node.parents.every(p => p.state === "done"))
  511. ) {
  512. running++;
  513. node.state = "starting";
  514. run(
  515. node.compiler,
  516. /** @type {SetupResult} */ (node.setupResult),
  517. nodeDone.bind(null, node)
  518. );
  519. node.state = "running";
  520. }
  521. }
  522. processing = false;
  523. if (
  524. !errored &&
  525. running === 0 &&
  526. nodes.every(node => node.state === "done")
  527. ) {
  528. const stats = [];
  529. for (const node of nodes) {
  530. const result = node.result;
  531. if (result) {
  532. node.result = undefined;
  533. stats.push(result);
  534. }
  535. }
  536. if (stats.length > 0) {
  537. callback(null, new MultiStats(stats));
  538. }
  539. }
  540. };
  541. processQueueWorker();
  542. return setupResults;
  543. }
  544. /**
  545. * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options
  546. * @param {Callback<MultiStats>} handler signals when the call finishes
  547. * @returns {MultiWatching} a compiler watcher
  548. */
  549. watch(watchOptions, handler) {
  550. if (this.running) {
  551. return handler(new ConcurrentCompilationError());
  552. }
  553. this.running = true;
  554. if (this.validateDependencies(handler)) {
  555. const watchings = this._runGraph(
  556. (compiler, idx, callback, isBlocked, setChanged, setInvalid) => {
  557. const watching = compiler.watch(
  558. Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions,
  559. callback
  560. );
  561. if (watching) {
  562. watching._onInvalid = setInvalid;
  563. watching._onChange = setChanged;
  564. watching._isBlocked = isBlocked;
  565. }
  566. return watching;
  567. },
  568. (compiler, watching, callback) => {
  569. if (compiler.watching !== watching) return;
  570. if (!watching.running) watching.invalidate();
  571. },
  572. handler
  573. );
  574. return new MultiWatching(watchings, this);
  575. }
  576. return new MultiWatching([], this);
  577. }
  578. /**
  579. * @param {Callback<MultiStats>} callback signals when the call finishes
  580. * @returns {void}
  581. */
  582. run(callback) {
  583. if (this.running) {
  584. return callback(new ConcurrentCompilationError());
  585. }
  586. this.running = true;
  587. if (this.validateDependencies(callback)) {
  588. this._runGraph(
  589. () => {},
  590. (compiler, setupResult, callback) => compiler.run(callback),
  591. (err, stats) => {
  592. this.running = false;
  593. if (callback !== undefined) {
  594. return callback(err, stats);
  595. }
  596. }
  597. );
  598. }
  599. }
  600. purgeInputFileSystem() {
  601. for (const compiler of this.compilers) {
  602. if (compiler.inputFileSystem && compiler.inputFileSystem.purge) {
  603. compiler.inputFileSystem.purge();
  604. }
  605. }
  606. }
  607. /**
  608. * @param {Callback<void>} callback signals when the compiler closes
  609. * @returns {void}
  610. */
  611. close(callback) {
  612. asyncLib.each(
  613. this.compilers,
  614. (compiler, callback) => {
  615. compiler.close(callback);
  616. },
  617. error => {
  618. callback(error);
  619. }
  620. );
  621. }
  622. };