UNPKG

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