提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

674 lines
18 KiB

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