UNPKG

84.6 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 { create: createResolver } = require("enhanced-resolve");
9const asyncLib = require("neo-async");
10const AsyncQueue = require("./util/AsyncQueue");
11const createHash = require("./util/createHash");
12const { join, dirname, relative } = require("./util/fs");
13const makeSerializable = require("./util/makeSerializable");
14const processAsyncTree = require("./util/processAsyncTree");
15
16/** @typedef {import("./WebpackError")} WebpackError */
17/** @typedef {import("./logging/Logger").Logger} Logger */
18/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
19
20const supportsEsm = +process.versions.modules >= 83;
21
22let FS_ACCURACY = 2000;
23
24const EMPTY_SET = new Set();
25
26const RBDT_RESOLVE_CJS = 0;
27const RBDT_RESOLVE_ESM = 1;
28const RBDT_RESOLVE_DIRECTORY = 2;
29const RBDT_RESOLVE_CJS_FILE = 3;
30const RBDT_RESOLVE_ESM_FILE = 4;
31const RBDT_DIRECTORY = 5;
32const RBDT_FILE = 6;
33const RBDT_DIRECTORY_DEPENDENCIES = 7;
34const RBDT_FILE_DEPENDENCIES = 8;
35
36const INVALID = Symbol("invalid");
37
38/**
39 * @typedef {Object} FileSystemInfoEntry
40 * @property {number} safeTime
41 * @property {number=} timestamp
42 * @property {string=} timestampHash
43 */
44
45/**
46 * @typedef {Object} TimestampAndHash
47 * @property {number} safeTime
48 * @property {number=} timestamp
49 * @property {string=} timestampHash
50 * @property {string} hash
51 */
52
53/**
54 * @typedef {Object} SnapshotOptimizationEntry
55 * @property {Snapshot} snapshot
56 * @property {number} shared
57 * @property {Set<string>} snapshotContent
58 * @property {Set<SnapshotOptimizationEntry>} children
59 */
60
61/**
62 * @typedef {Object} ResolveBuildDependenciesResult
63 * @property {Set<string>} files list of files
64 * @property {Set<string>} directories list of directories
65 * @property {Set<string>} missing list of missing entries
66 * @property {Map<string, string>} resolveResults stored resolve results
67 * @property {Object} resolveDependencies dependencies of the resolving
68 * @property {Set<string>} resolveDependencies.files list of files
69 * @property {Set<string>} resolveDependencies.directories list of directories
70 * @property {Set<string>} resolveDependencies.missing list of missing entries
71 */
72
73const DONE_ITERATOR_RESULT = new Set().keys().next();
74
75// cspell:word tshs
76// Tsh = Timestamp + Hash
77// Tshs = Timestamp + Hash combinations
78
79class Snapshot {
80 constructor() {
81 this._flags = 0;
82 /** @type {number | undefined} */
83 this.startTime = undefined;
84 /** @type {Map<string, FileSystemInfoEntry> | undefined} */
85 this.fileTimestamps = undefined;
86 /** @type {Map<string, string> | undefined} */
87 this.fileHashes = undefined;
88 /** @type {Map<string, TimestampAndHash | string> | undefined} */
89 this.fileTshs = undefined;
90 /** @type {Map<string, FileSystemInfoEntry> | undefined} */
91 this.contextTimestamps = undefined;
92 /** @type {Map<string, string> | undefined} */
93 this.contextHashes = undefined;
94 /** @type {Map<string, TimestampAndHash | string> | undefined} */
95 this.contextTshs = undefined;
96 /** @type {Map<string, boolean> | undefined} */
97 this.missingExistence = undefined;
98 /** @type {Map<string, string> | undefined} */
99 this.managedItemInfo = undefined;
100 /** @type {Set<string> | undefined} */
101 this.managedFiles = undefined;
102 /** @type {Set<string> | undefined} */
103 this.managedContexts = undefined;
104 /** @type {Set<string> | undefined} */
105 this.managedMissing = undefined;
106 /** @type {Set<Snapshot> | undefined} */
107 this.children = undefined;
108 }
109
110 hasStartTime() {
111 return (this._flags & 1) !== 0;
112 }
113
114 setStartTime(value) {
115 this._flags = this._flags | 1;
116 this.startTime = value;
117 }
118
119 setMergedStartTime(value, snapshot) {
120 if (value) {
121 if (snapshot.hasStartTime()) {
122 this.setStartTime(Math.min(value, snapshot.startTime));
123 } else {
124 this.setStartTime(value);
125 }
126 } else {
127 if (snapshot.hasStartTime()) this.setStartTime(snapshot.startTime);
128 }
129 }
130
131 hasFileTimestamps() {
132 return (this._flags & 2) !== 0;
133 }
134
135 setFileTimestamps(value) {
136 this._flags = this._flags | 2;
137 this.fileTimestamps = value;
138 }
139
140 hasFileHashes() {
141 return (this._flags & 4) !== 0;
142 }
143
144 setFileHashes(value) {
145 this._flags = this._flags | 4;
146 this.fileHashes = value;
147 }
148
149 hasFileTshs() {
150 return (this._flags & 8) !== 0;
151 }
152
153 setFileTshs(value) {
154 this._flags = this._flags | 8;
155 this.fileTshs = value;
156 }
157
158 hasContextTimestamps() {
159 return (this._flags & 0x10) !== 0;
160 }
161
162 setContextTimestamps(value) {
163 this._flags = this._flags | 0x10;
164 this.contextTimestamps = value;
165 }
166
167 hasContextHashes() {
168 return (this._flags & 0x20) !== 0;
169 }
170
171 setContextHashes(value) {
172 this._flags = this._flags | 0x20;
173 this.contextHashes = value;
174 }
175
176 hasContextTshs() {
177 return (this._flags & 0x40) !== 0;
178 }
179
180 setContextTshs(value) {
181 this._flags = this._flags | 0x40;
182 this.contextTshs = value;
183 }
184
185 hasMissingExistence() {
186 return (this._flags & 0x80) !== 0;
187 }
188
189 setMissingExistence(value) {
190 this._flags = this._flags | 0x80;
191 this.missingExistence = value;
192 }
193
194 hasManagedItemInfo() {
195 return (this._flags & 0x100) !== 0;
196 }
197
198 setManagedItemInfo(value) {
199 this._flags = this._flags | 0x100;
200 this.managedItemInfo = value;
201 }
202
203 hasManagedFiles() {
204 return (this._flags & 0x200) !== 0;
205 }
206
207 setManagedFiles(value) {
208 this._flags = this._flags | 0x200;
209 this.managedFiles = value;
210 }
211
212 hasManagedContexts() {
213 return (this._flags & 0x400) !== 0;
214 }
215
216 setManagedContexts(value) {
217 this._flags = this._flags | 0x400;
218 this.managedContexts = value;
219 }
220
221 hasManagedMissing() {
222 return (this._flags & 0x800) !== 0;
223 }
224
225 setManagedMissing(value) {
226 this._flags = this._flags | 0x800;
227 this.managedMissing = value;
228 }
229
230 hasChildren() {
231 return (this._flags & 0x1000) !== 0;
232 }
233
234 setChildren(value) {
235 this._flags = this._flags | 0x1000;
236 this.children = value;
237 }
238
239 addChild(child) {
240 if (!this.hasChildren()) {
241 this.setChildren(new Set());
242 }
243 this.children.add(child);
244 }
245
246 serialize({ write }) {
247 write(this._flags);
248 if (this.hasStartTime()) write(this.startTime);
249 if (this.hasFileTimestamps()) write(this.fileTimestamps);
250 if (this.hasFileHashes()) write(this.fileHashes);
251 if (this.hasFileTshs()) write(this.fileTshs);
252 if (this.hasContextTimestamps()) write(this.contextTimestamps);
253 if (this.hasContextHashes()) write(this.contextHashes);
254 if (this.hasContextTshs()) write(this.contextTshs);
255 if (this.hasMissingExistence()) write(this.missingExistence);
256 if (this.hasManagedItemInfo()) write(this.managedItemInfo);
257 if (this.hasManagedFiles()) write(this.managedFiles);
258 if (this.hasManagedContexts()) write(this.managedContexts);
259 if (this.hasManagedMissing()) write(this.managedMissing);
260 if (this.hasChildren()) write(this.children);
261 }
262
263 deserialize({ read }) {
264 this._flags = read();
265 if (this.hasStartTime()) this.startTime = read();
266 if (this.hasFileTimestamps()) this.fileTimestamps = read();
267 if (this.hasFileHashes()) this.fileHashes = read();
268 if (this.hasFileTshs()) this.fileTshs = read();
269 if (this.hasContextTimestamps()) this.contextTimestamps = read();
270 if (this.hasContextHashes()) this.contextHashes = read();
271 if (this.hasContextTshs()) this.contextTshs = read();
272 if (this.hasMissingExistence()) this.missingExistence = read();
273 if (this.hasManagedItemInfo()) this.managedItemInfo = read();
274 if (this.hasManagedFiles()) this.managedFiles = read();
275 if (this.hasManagedContexts()) this.managedContexts = read();
276 if (this.hasManagedMissing()) this.managedMissing = read();
277 if (this.hasChildren()) this.children = read();
278 }
279
280 /**
281 * @param {function(Snapshot): (Map<string, any> | Set<string>)[]} getMaps first
282 * @returns {Iterable<string>} iterable
283 */
284 _createIterable(getMaps) {
285 let snapshot = this;
286 return {
287 [Symbol.iterator]() {
288 let state = 0;
289 /** @type {IterableIterator<string>} */
290 let it;
291 let maps = getMaps(snapshot);
292 const queue = [];
293 return {
294 next() {
295 for (;;) {
296 switch (state) {
297 case 0:
298 if (maps.length > 0) {
299 const map = maps.pop();
300 if (map !== undefined) {
301 it = map.keys();
302 state = 1;
303 } else {
304 break;
305 }
306 } else {
307 state = 2;
308 break;
309 }
310 /* falls through */
311 case 1: {
312 const result = it.next();
313 if (!result.done) return result;
314 state = 0;
315 break;
316 }
317 case 2: {
318 const children = snapshot.children;
319 if (children !== undefined) {
320 for (const child of children) {
321 queue.push(child);
322 }
323 }
324 if (queue.length > 0) {
325 snapshot = queue.pop();
326 maps = getMaps(snapshot);
327 state = 0;
328 break;
329 } else {
330 state = 3;
331 }
332 }
333 /* falls through */
334 case 3:
335 return DONE_ITERATOR_RESULT;
336 }
337 }
338 }
339 };
340 }
341 };
342 }
343
344 /**
345 * @returns {Iterable<string>} iterable
346 */
347 getFileIterable() {
348 return this._createIterable(s => [
349 s.fileTimestamps,
350 s.fileHashes,
351 s.fileTshs,
352 s.managedFiles
353 ]);
354 }
355
356 /**
357 * @returns {Iterable<string>} iterable
358 */
359 getContextIterable() {
360 return this._createIterable(s => [
361 s.contextTimestamps,
362 s.contextHashes,
363 s.contextTshs,
364 s.managedContexts
365 ]);
366 }
367
368 /**
369 * @returns {Iterable<string>} iterable
370 */
371 getMissingIterable() {
372 return this._createIterable(s => [s.missingExistence, s.managedMissing]);
373 }
374}
375
376makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot");
377
378const MIN_COMMON_SNAPSHOT_SIZE = 3;
379
380/**
381 * @template T
382 */
383class SnapshotOptimization {
384 /**
385 * @param {function(Snapshot): boolean} has has value
386 * @param {function(Snapshot): Map<string, T> | Set<string>} get get value
387 * @param {function(Snapshot, Map<string, T> | Set<string>): void} set set value
388 * @param {boolean=} isSet value is an Set instead of a Map
389 */
390 constructor(has, get, set, isSet = false) {
391 this._has = has;
392 this._get = get;
393 this._set = set;
394 this._isSet = isSet;
395 /** @type {Map<string, SnapshotOptimizationEntry>} */
396 this._map = new Map();
397 this._statItemsShared = 0;
398 this._statItemsUnshared = 0;
399 this._statSharedSnapshots = 0;
400 this._statReusedSharedSnapshots = 0;
401 }
402
403 getStatisticMessage() {
404 const total = this._statItemsShared + this._statItemsUnshared;
405 if (total === 0) return undefined;
406 return `${
407 this._statItemsShared && Math.round((this._statItemsShared * 100) / total)
408 }% (${this._statItemsShared}/${total}) entries shared via ${
409 this._statSharedSnapshots
410 } shared snapshots (${
411 this._statReusedSharedSnapshots + this._statSharedSnapshots
412 } times referenced)`;
413 }
414
415 clear() {
416 this._map.clear();
417 this._statItemsShared = 0;
418 this._statItemsUnshared = 0;
419 this._statSharedSnapshots = 0;
420 this._statReusedSharedSnapshots = 0;
421 }
422
423 storeUnsharedSnapshot(snapshot, locations) {
424 if (locations === undefined) return;
425 const optimizationEntry = {
426 snapshot,
427 shared: 0,
428 snapshotContent: undefined,
429 children: undefined
430 };
431 for (const path of locations) {
432 this._map.set(path, optimizationEntry);
433 }
434 }
435
436 optimize(capturedFiles, startTime, children) {
437 /** @type {Set<string>} */
438 const unsetOptimizationEntries = new Set();
439 /** @type {Set<SnapshotOptimizationEntry>} */
440 const checkedOptimizationEntries = new Set();
441 /**
442 * @param {SnapshotOptimizationEntry} entry optimization entry
443 * @returns {void}
444 */
445 const increaseSharedAndStoreOptimizationEntry = entry => {
446 if (entry.children !== undefined) {
447 entry.children.forEach(increaseSharedAndStoreOptimizationEntry);
448 }
449 entry.shared++;
450 storeOptimizationEntry(entry);
451 };
452 /**
453 * @param {SnapshotOptimizationEntry} entry optimization entry
454 * @returns {void}
455 */
456 const storeOptimizationEntry = entry => {
457 for (const path of entry.snapshotContent) {
458 const old = this._map.get(path);
459 if (old.shared < entry.shared) {
460 this._map.set(path, entry);
461 }
462 capturedFiles.delete(path);
463 }
464 };
465 const capturedFilesSize = capturedFiles.size;
466 capturedFiles: for (const path of capturedFiles) {
467 const optimizationEntry = this._map.get(path);
468 if (optimizationEntry === undefined) {
469 unsetOptimizationEntries.add(path);
470 continue;
471 }
472 if (checkedOptimizationEntries.has(optimizationEntry)) continue;
473 const snapshot = optimizationEntry.snapshot;
474 if (optimizationEntry.shared > 0) {
475 // It's a shared snapshot
476 // We can't change it, so we can only use it when all files match
477 // and startTime is compatible
478 if (
479 startTime &&
480 (!snapshot.startTime || snapshot.startTime > startTime)
481 ) {
482 continue;
483 }
484 const nonSharedFiles = new Set();
485 const snapshotContent = optimizationEntry.snapshotContent;
486 const snapshotEntries = this._get(snapshot);
487 for (const path of snapshotContent) {
488 if (!capturedFiles.has(path)) {
489 if (!snapshotEntries.has(path)) {
490 // File is not shared and can't be removed from the snapshot
491 // because it's in a child of the snapshot
492 checkedOptimizationEntries.add(optimizationEntry);
493 continue capturedFiles;
494 }
495 nonSharedFiles.add(path);
496 continue;
497 }
498 }
499 if (nonSharedFiles.size === 0) {
500 // The complete snapshot is shared
501 // add it as child
502 children.add(snapshot);
503 increaseSharedAndStoreOptimizationEntry(optimizationEntry);
504 this._statReusedSharedSnapshots++;
505 } else {
506 // Only a part of the snapshot is shared
507 const sharedCount = snapshotContent.size - nonSharedFiles.size;
508 if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) {
509 // Common part it too small
510 checkedOptimizationEntries.add(optimizationEntry);
511 continue capturedFiles;
512 }
513 // Extract common timestamps from both snapshots
514 let commonMap;
515 if (this._isSet) {
516 commonMap = new Set();
517 for (const path of /** @type {Set<string>} */ (snapshotEntries)) {
518 if (nonSharedFiles.has(path)) continue;
519 commonMap.add(path);
520 snapshotEntries.delete(path);
521 }
522 } else {
523 commonMap = new Map();
524 const map = /** @type {Map<string, T>} */ (snapshotEntries);
525 for (const [path, value] of map) {
526 if (nonSharedFiles.has(path)) continue;
527 commonMap.set(path, value);
528 snapshotEntries.delete(path);
529 }
530 }
531 // Create and attach snapshot
532 const commonSnapshot = new Snapshot();
533 commonSnapshot.setMergedStartTime(startTime, snapshot);
534 this._set(commonSnapshot, commonMap);
535 children.add(commonSnapshot);
536 snapshot.addChild(commonSnapshot);
537 // Create optimization entry
538 const newEntry = {
539 snapshot: commonSnapshot,
540 shared: optimizationEntry.shared + 1,
541 snapshotContent: new Set(commonMap.keys()),
542 children: undefined
543 };
544 if (optimizationEntry.children === undefined)
545 optimizationEntry.children = new Set();
546 optimizationEntry.children.add(newEntry);
547 storeOptimizationEntry(newEntry);
548 this._statSharedSnapshots++;
549 }
550 } else {
551 // It's a unshared snapshot
552 // We can extract a common shared snapshot
553 // with all common files
554 const snapshotEntries = this._get(snapshot);
555 let commonMap;
556 if (this._isSet) {
557 commonMap = new Set();
558 const set = /** @type {Set<string>} */ (snapshotEntries);
559 if (capturedFiles.size < set.size) {
560 for (const path of capturedFiles) {
561 if (set.has(path)) commonMap.add(path);
562 }
563 } else {
564 for (const path of set) {
565 if (capturedFiles.has(path)) commonMap.add(path);
566 }
567 }
568 } else {
569 commonMap = new Map();
570 const map = /** @type {Map<string, T>} */ (snapshotEntries);
571 for (const path of capturedFiles) {
572 const ts = map.get(path);
573 if (ts === undefined) continue;
574 commonMap.set(path, ts);
575 }
576 }
577
578 if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) {
579 // Common part it too small
580 checkedOptimizationEntries.add(optimizationEntry);
581 continue capturedFiles;
582 }
583 // Create and attach snapshot
584 const commonSnapshot = new Snapshot();
585 commonSnapshot.setMergedStartTime(startTime, snapshot);
586 this._set(commonSnapshot, commonMap);
587 children.add(commonSnapshot);
588 snapshot.addChild(commonSnapshot);
589 // Remove files from snapshot
590 for (const path of commonMap.keys()) snapshotEntries.delete(path);
591 const sharedCount = commonMap.size;
592 this._statItemsUnshared -= sharedCount;
593 this._statItemsShared += sharedCount;
594 // Create optimization entry
595 storeOptimizationEntry({
596 snapshot: commonSnapshot,
597 shared: 2,
598 snapshotContent: new Set(commonMap.keys()),
599 children: undefined
600 });
601 this._statSharedSnapshots++;
602 }
603 checkedOptimizationEntries.add(optimizationEntry);
604 }
605 const unshared = capturedFiles.size;
606 this._statItemsUnshared += unshared;
607 this._statItemsShared += capturedFilesSize - unshared;
608 return unsetOptimizationEntries;
609 }
610}
611
612/* istanbul ignore next */
613/**
614 * @param {number} mtime mtime
615 */
616const applyMtime = mtime => {
617 if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1;
618 else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10;
619 else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100;
620 else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000;
621};
622
623/**
624 * @template T
625 * @template K
626 * @param {Map<T, K>} a source map
627 * @param {Map<T, K>} b joining map
628 * @returns {Map<T, K>} joined map
629 */
630const mergeMaps = (a, b) => {
631 if (!b || b.size === 0) return a;
632 if (!a || a.size === 0) return b;
633 const map = new Map(a);
634 for (const [key, value] of b) {
635 map.set(key, value);
636 }
637 return map;
638};
639
640/**
641 * @template T
642 * @template K
643 * @param {Set<T, K>} a source map
644 * @param {Set<T, K>} b joining map
645 * @returns {Set<T, K>} joined map
646 */
647const mergeSets = (a, b) => {
648 if (!b || b.size === 0) return a;
649 if (!a || a.size === 0) return b;
650 const map = new Set(a);
651 for (const item of b) {
652 map.add(item);
653 }
654 return map;
655};
656
657/**
658 * Finding file or directory to manage
659 * @param {string} managedPath path that is managing by {@link FileSystemInfo}
660 * @param {string} path path to file or directory
661 * @returns {string|null} managed item
662 * @example
663 * getManagedItem(
664 * '/Users/user/my-project/node_modules/',
665 * '/Users/user/my-project/node_modules/package/index.js'
666 * ) === '/Users/user/my-project/node_modules/package'
667 * getManagedItem(
668 * '/Users/user/my-project/node_modules/',
669 * '/Users/user/my-project/node_modules/package1/node_modules/package2'
670 * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2'
671 * getManagedItem(
672 * '/Users/user/my-project/node_modules/',
673 * '/Users/user/my-project/node_modules/.bin/script.js'
674 * ) === null // hidden files are disallowed as managed items
675 * getManagedItem(
676 * '/Users/user/my-project/node_modules/',
677 * '/Users/user/my-project/node_modules/package'
678 * ) === '/Users/user/my-project/node_modules/package'
679 */
680const getManagedItem = (managedPath, path) => {
681 let i = managedPath.length;
682 let slashes = 1;
683 let startingPosition = true;
684 loop: while (i < path.length) {
685 switch (path.charCodeAt(i)) {
686 case 47: // slash
687 case 92: // backslash
688 if (--slashes === 0) break loop;
689 startingPosition = true;
690 break;
691 case 46: // .
692 // hidden files are disallowed as managed items
693 // it's probably .yarn-integrity or .cache
694 if (startingPosition) return null;
695 break;
696 case 64: // @
697 if (!startingPosition) return null;
698 slashes++;
699 break;
700 default:
701 startingPosition = false;
702 break;
703 }
704 i++;
705 }
706 if (i === path.length) slashes--;
707 // return null when path is incomplete
708 if (slashes !== 0) return null;
709 // if (path.slice(i + 1, i + 13) === "node_modules")
710 if (
711 path.length >= i + 13 &&
712 path.charCodeAt(i + 1) === 110 &&
713 path.charCodeAt(i + 2) === 111 &&
714 path.charCodeAt(i + 3) === 100 &&
715 path.charCodeAt(i + 4) === 101 &&
716 path.charCodeAt(i + 5) === 95 &&
717 path.charCodeAt(i + 6) === 109 &&
718 path.charCodeAt(i + 7) === 111 &&
719 path.charCodeAt(i + 8) === 100 &&
720 path.charCodeAt(i + 9) === 117 &&
721 path.charCodeAt(i + 10) === 108 &&
722 path.charCodeAt(i + 11) === 101 &&
723 path.charCodeAt(i + 12) === 115
724 ) {
725 // if this is the end of the path
726 if (path.length === i + 13) {
727 // return the node_modules directory
728 // it's special
729 return path;
730 }
731 const c = path.charCodeAt(i + 13);
732 // if next symbol is slash or backslash
733 if (c === 47 || c === 92) {
734 // Managed subpath
735 return getManagedItem(path.slice(0, i + 14), path);
736 }
737 }
738 return path.slice(0, i);
739};
740
741/**
742 * @param {FileSystemInfoEntry} entry file system info entry
743 * @returns {boolean} existence flag
744 */
745const toExistence = entry => {
746 return Boolean(entry);
747};
748
749/**
750 * Used to access information about the filesystem in a cached way
751 */
752class FileSystemInfo {
753 /**
754 * @param {InputFileSystem} fs file system
755 * @param {Object} options options
756 * @param {Iterable<string>=} options.managedPaths paths that are only managed by a package manager
757 * @param {Iterable<string>=} options.immutablePaths paths that are immutable
758 * @param {Logger=} options.logger logger used to log invalid snapshots
759 */
760 constructor(fs, { managedPaths = [], immutablePaths = [], logger } = {}) {
761 this.fs = fs;
762 this.logger = logger;
763 this._remainingLogs = logger ? 40 : 0;
764 this._loggedPaths = logger ? new Set() : undefined;
765 /** @type {WeakMap<Snapshot, boolean | (function(WebpackError=, boolean=): void)[]>} */
766 this._snapshotCache = new WeakMap();
767 this._fileTimestampsOptimization = new SnapshotOptimization(
768 s => s.hasFileTimestamps(),
769 s => s.fileTimestamps,
770 (s, v) => s.setFileTimestamps(v)
771 );
772 this._fileHashesOptimization = new SnapshotOptimization(
773 s => s.hasFileHashes(),
774 s => s.fileHashes,
775 (s, v) => s.setFileHashes(v)
776 );
777 this._fileTshsOptimization = new SnapshotOptimization(
778 s => s.hasFileTshs(),
779 s => s.fileTshs,
780 (s, v) => s.setFileTshs(v)
781 );
782 this._contextTimestampsOptimization = new SnapshotOptimization(
783 s => s.hasContextTimestamps(),
784 s => s.contextTimestamps,
785 (s, v) => s.setContextTimestamps(v)
786 );
787 this._contextHashesOptimization = new SnapshotOptimization(
788 s => s.hasContextHashes(),
789 s => s.contextHashes,
790 (s, v) => s.setContextHashes(v)
791 );
792 this._contextTshsOptimization = new SnapshotOptimization(
793 s => s.hasContextTshs(),
794 s => s.contextTshs,
795 (s, v) => s.setContextTshs(v)
796 );
797 this._missingExistenceOptimization = new SnapshotOptimization(
798 s => s.hasMissingExistence(),
799 s => s.missingExistence,
800 (s, v) => s.setMissingExistence(v)
801 );
802 this._managedItemInfoOptimization = new SnapshotOptimization(
803 s => s.hasManagedItemInfo(),
804 s => s.managedItemInfo,
805 (s, v) => s.setManagedItemInfo(v)
806 );
807 this._managedFilesOptimization = new SnapshotOptimization(
808 s => s.hasManagedFiles(),
809 s => s.managedFiles,
810 (s, v) => s.setManagedFiles(v),
811 true
812 );
813 this._managedContextsOptimization = new SnapshotOptimization(
814 s => s.hasManagedContexts(),
815 s => s.managedContexts,
816 (s, v) => s.setManagedContexts(v),
817 true
818 );
819 this._managedMissingOptimization = new SnapshotOptimization(
820 s => s.hasManagedMissing(),
821 s => s.managedMissing,
822 (s, v) => s.setManagedMissing(v),
823 true
824 );
825 /** @type {Map<string, FileSystemInfoEntry | "ignore" | null>} */
826 this._fileTimestamps = new Map();
827 /** @type {Map<string, string>} */
828 this._fileHashes = new Map();
829 /** @type {Map<string, TimestampAndHash | string>} */
830 this._fileTshs = new Map();
831 /** @type {Map<string, FileSystemInfoEntry | "ignore" | null>} */
832 this._contextTimestamps = new Map();
833 /** @type {Map<string, string>} */
834 this._contextHashes = new Map();
835 /** @type {Map<string, TimestampAndHash | string>} */
836 this._contextTshs = new Map();
837 /** @type {Map<string, string>} */
838 this._managedItems = new Map();
839 /** @type {AsyncQueue<string, string, FileSystemInfoEntry | null>} */
840 this.fileTimestampQueue = new AsyncQueue({
841 name: "file timestamp",
842 parallelism: 30,
843 processor: this._readFileTimestamp.bind(this)
844 });
845 /** @type {AsyncQueue<string, string, string | null>} */
846 this.fileHashQueue = new AsyncQueue({
847 name: "file hash",
848 parallelism: 10,
849 processor: this._readFileHash.bind(this)
850 });
851 /** @type {AsyncQueue<string, string, FileSystemInfoEntry | null>} */
852 this.contextTimestampQueue = new AsyncQueue({
853 name: "context timestamp",
854 parallelism: 2,
855 processor: this._readContextTimestamp.bind(this)
856 });
857 /** @type {AsyncQueue<string, string, string | null>} */
858 this.contextHashQueue = new AsyncQueue({
859 name: "context hash",
860 parallelism: 2,
861 processor: this._readContextHash.bind(this)
862 });
863 /** @type {AsyncQueue<string, string, string | null>} */
864 this.managedItemQueue = new AsyncQueue({
865 name: "managed item info",
866 parallelism: 10,
867 processor: this._getManagedItemInfo.bind(this)
868 });
869 /** @type {AsyncQueue<string, string, Set<string>>} */
870 this.managedItemDirectoryQueue = new AsyncQueue({
871 name: "managed item directory info",
872 parallelism: 10,
873 processor: this._getManagedItemDirectoryInfo.bind(this)
874 });
875 this.managedPaths = Array.from(managedPaths);
876 this.managedPathsWithSlash = this.managedPaths.map(p =>
877 join(fs, p, "_").slice(0, -1)
878 );
879 this.immutablePaths = Array.from(immutablePaths);
880 this.immutablePathsWithSlash = this.immutablePaths.map(p =>
881 join(fs, p, "_").slice(0, -1)
882 );
883
884 this._cachedDeprecatedFileTimestamps = undefined;
885 this._cachedDeprecatedContextTimestamps = undefined;
886
887 this._warnAboutExperimentalEsmTracking = false;
888
889 this._statCreatedSnapshots = 0;
890 this._statTestedSnapshotsCached = 0;
891 this._statTestedSnapshotsNotCached = 0;
892 this._statTestedChildrenCached = 0;
893 this._statTestedChildrenNotCached = 0;
894 this._statTestedEntries = 0;
895 }
896
897 logStatistics() {
898 const logWhenMessage = (header, message) => {
899 if (message) {
900 this.logger.log(`${header}: ${message}`);
901 }
902 };
903 this.logger.log(`${this._statCreatedSnapshots} new snapshots created`);
904 this.logger.log(
905 `${
906 this._statTestedSnapshotsNotCached &&
907 Math.round(
908 (this._statTestedSnapshotsNotCached * 100) /
909 (this._statTestedSnapshotsCached +
910 this._statTestedSnapshotsNotCached)
911 )
912 }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${
913 this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached
914 })`
915 );
916 this.logger.log(
917 `${
918 this._statTestedChildrenNotCached &&
919 Math.round(
920 (this._statTestedChildrenNotCached * 100) /
921 (this._statTestedChildrenCached + this._statTestedChildrenNotCached)
922 )
923 }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${
924 this._statTestedChildrenCached + this._statTestedChildrenNotCached
925 })`
926 );
927 this.logger.log(`${this._statTestedEntries} entries tested`);
928 this.logger.log(
929 `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations`
930 );
931 logWhenMessage(
932 `File timestamp snapshot optimization`,
933 this._fileTimestampsOptimization.getStatisticMessage()
934 );
935 logWhenMessage(
936 `File hash snapshot optimization`,
937 this._fileHashesOptimization.getStatisticMessage()
938 );
939 logWhenMessage(
940 `File timestamp hash combination snapshot optimization`,
941 this._fileTshsOptimization.getStatisticMessage()
942 );
943 this.logger.log(
944 `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations`
945 );
946 logWhenMessage(
947 `Directory timestamp snapshot optimization`,
948 this._contextTimestampsOptimization.getStatisticMessage()
949 );
950 logWhenMessage(
951 `Directory hash snapshot optimization`,
952 this._contextHashesOptimization.getStatisticMessage()
953 );
954 logWhenMessage(
955 `Directory timestamp hash combination snapshot optimization`,
956 this._contextTshsOptimization.getStatisticMessage()
957 );
958 logWhenMessage(
959 `Missing items snapshot optimization`,
960 this._missingExistenceOptimization.getStatisticMessage()
961 );
962 this.logger.log(
963 `Managed items info in cache: ${this._managedItems.size} items`
964 );
965 logWhenMessage(
966 `Managed items snapshot optimization`,
967 this._managedItemInfoOptimization.getStatisticMessage()
968 );
969 logWhenMessage(
970 `Managed files snapshot optimization`,
971 this._managedFilesOptimization.getStatisticMessage()
972 );
973 logWhenMessage(
974 `Managed contexts snapshot optimization`,
975 this._managedContextsOptimization.getStatisticMessage()
976 );
977 logWhenMessage(
978 `Managed missing snapshot optimization`,
979 this._managedMissingOptimization.getStatisticMessage()
980 );
981 }
982
983 _log(path, reason, ...args) {
984 const key = path + reason;
985 if (this._loggedPaths.has(key)) return;
986 this._loggedPaths.add(key);
987 this.logger.debug(`${path} invalidated because ${reason}`, ...args);
988 if (--this._remainingLogs === 0) {
989 this.logger.debug(
990 "Logging limit has been reached and no further logging will be emitted by FileSystemInfo"
991 );
992 }
993 }
994
995 clear() {
996 this._remainingLogs = this.logger ? 40 : 0;
997 if (this._loggedPaths !== undefined) this._loggedPaths.clear();
998
999 this._snapshotCache = new WeakMap();
1000 this._fileTimestampsOptimization.clear();
1001 this._fileHashesOptimization.clear();
1002 this._fileTshsOptimization.clear();
1003 this._contextTimestampsOptimization.clear();
1004 this._contextHashesOptimization.clear();
1005 this._contextTshsOptimization.clear();
1006 this._missingExistenceOptimization.clear();
1007 this._managedItemInfoOptimization.clear();
1008 this._managedFilesOptimization.clear();
1009 this._managedContextsOptimization.clear();
1010 this._managedMissingOptimization.clear();
1011 this._fileTimestamps.clear();
1012 this._fileHashes.clear();
1013 this._fileTshs.clear();
1014 this._contextTimestamps.clear();
1015 this._contextHashes.clear();
1016 this._contextTshs.clear();
1017 this._managedItems.clear();
1018 this._managedItems.clear();
1019
1020 this._cachedDeprecatedFileTimestamps = undefined;
1021 this._cachedDeprecatedContextTimestamps = undefined;
1022
1023 this._statCreatedSnapshots = 0;
1024 this._statTestedSnapshotsCached = 0;
1025 this._statTestedSnapshotsNotCached = 0;
1026 this._statTestedChildrenCached = 0;
1027 this._statTestedChildrenNotCached = 0;
1028 this._statTestedEntries = 0;
1029 }
1030
1031 /**
1032 * @param {Map<string, FileSystemInfoEntry | "ignore" | null>} map timestamps
1033 * @returns {void}
1034 */
1035 addFileTimestamps(map) {
1036 for (const [path, ts] of map) {
1037 this._fileTimestamps.set(path, ts);
1038 }
1039 this._cachedDeprecatedFileTimestamps = undefined;
1040 }
1041
1042 /**
1043 * @param {Map<string, FileSystemInfoEntry | "ignore" | null>} map timestamps
1044 * @returns {void}
1045 */
1046 addContextTimestamps(map) {
1047 for (const [path, ts] of map) {
1048 this._contextTimestamps.set(path, ts);
1049 }
1050 this._cachedDeprecatedContextTimestamps = undefined;
1051 }
1052
1053 /**
1054 * @param {string} path file path
1055 * @param {function(WebpackError=, (FileSystemInfoEntry | "ignore" | null)=): void} callback callback function
1056 * @returns {void}
1057 */
1058 getFileTimestamp(path, callback) {
1059 const cache = this._fileTimestamps.get(path);
1060 if (cache !== undefined) return callback(null, cache);
1061 this.fileTimestampQueue.add(path, callback);
1062 }
1063
1064 /**
1065 * @param {string} path context path
1066 * @param {function(WebpackError=, (FileSystemInfoEntry | "ignore" | null)=): void} callback callback function
1067 * @returns {void}
1068 */
1069 getContextTimestamp(path, callback) {
1070 const cache = this._contextTimestamps.get(path);
1071 if (cache !== undefined) return callback(null, cache);
1072 this.contextTimestampQueue.add(path, callback);
1073 }
1074
1075 /**
1076 * @param {string} path file path
1077 * @param {function(WebpackError=, string=): void} callback callback function
1078 * @returns {void}
1079 */
1080 getFileHash(path, callback) {
1081 const cache = this._fileHashes.get(path);
1082 if (cache !== undefined) return callback(null, cache);
1083 this.fileHashQueue.add(path, callback);
1084 }
1085
1086 /**
1087 * @param {string} path context path
1088 * @param {function(WebpackError=, string=): void} callback callback function
1089 * @returns {void}
1090 */
1091 getContextHash(path, callback) {
1092 const cache = this._contextHashes.get(path);
1093 if (cache !== undefined) return callback(null, cache);
1094 this.contextHashQueue.add(path, callback);
1095 }
1096
1097 _createBuildDependenciesResolvers() {
1098 const resolveContext = createResolver({
1099 resolveToContext: true,
1100 exportsFields: [],
1101 fileSystem: this.fs
1102 });
1103 const resolveCjs = createResolver({
1104 extensions: [".js", ".json", ".node"],
1105 conditionNames: ["require", "node"],
1106 fileSystem: this.fs
1107 });
1108 const resolveEsm = createResolver({
1109 extensions: [".js", ".json", ".node"],
1110 fullySpecified: true,
1111 conditionNames: ["import", "node"],
1112 fileSystem: this.fs
1113 });
1114 return { resolveContext, resolveEsm, resolveCjs };
1115 }
1116
1117 /**
1118 * @param {string} context context directory
1119 * @param {Iterable<string>} deps dependencies
1120 * @param {function(Error=, ResolveBuildDependenciesResult=): void} callback callback function
1121 * @returns {void}
1122 */
1123 resolveBuildDependencies(context, deps, callback) {
1124 const {
1125 resolveContext,
1126 resolveEsm,
1127 resolveCjs
1128 } = this._createBuildDependenciesResolvers();
1129
1130 /** @type {Set<string>} */
1131 const files = new Set();
1132 /** @type {Set<string>} */
1133 const fileSymlinks = new Set();
1134 /** @type {Set<string>} */
1135 const directories = new Set();
1136 /** @type {Set<string>} */
1137 const directorySymlinks = new Set();
1138 /** @type {Set<string>} */
1139 const missing = new Set();
1140 /** @type {Set<string>} */
1141 const resolveFiles = new Set();
1142 /** @type {Set<string>} */
1143 const resolveDirectories = new Set();
1144 /** @type {Set<string>} */
1145 const resolveMissing = new Set();
1146 /** @type {Map<string, string>} */
1147 const resolveResults = new Map();
1148 const invalidResolveResults = new Set();
1149 const resolverContext = {
1150 fileDependencies: resolveFiles,
1151 contextDependencies: resolveDirectories,
1152 missingDependencies: resolveMissing
1153 };
1154 const expectedToString = expected => {
1155 return expected ? ` (expected ${expected})` : "";
1156 };
1157 const jobToString = job => {
1158 switch (job.type) {
1159 case RBDT_RESOLVE_CJS:
1160 return `resolve commonjs ${job.path}${expectedToString(
1161 job.expected
1162 )}`;
1163 case RBDT_RESOLVE_ESM:
1164 return `resolve esm ${job.path}${expectedToString(job.expected)}`;
1165 case RBDT_RESOLVE_DIRECTORY:
1166 return `resolve directory ${job.path}`;
1167 case RBDT_RESOLVE_CJS_FILE:
1168 return `resolve commonjs file ${job.path}${expectedToString(
1169 job.expected
1170 )}`;
1171 case RBDT_RESOLVE_ESM_FILE:
1172 return `resolve esm file ${job.path}${expectedToString(
1173 job.expected
1174 )}`;
1175 case RBDT_DIRECTORY:
1176 return `directory ${job.path}`;
1177 case RBDT_FILE:
1178 return `file ${job.path}`;
1179 case RBDT_DIRECTORY_DEPENDENCIES:
1180 return `directory dependencies ${job.path}`;
1181 case RBDT_FILE_DEPENDENCIES:
1182 return `file dependencies ${job.path}`;
1183 }
1184 return `unknown ${job.type} ${job.path}`;
1185 };
1186 const pathToString = job => {
1187 let result = ` at ${jobToString(job)}`;
1188 job = job.issuer;
1189 while (job !== undefined) {
1190 result += `\n at ${jobToString(job)}`;
1191 job = job.issuer;
1192 }
1193 return result;
1194 };
1195 processAsyncTree(
1196 Array.from(deps, dep => ({
1197 type: RBDT_RESOLVE_CJS,
1198 context,
1199 path: dep,
1200 expected: undefined,
1201 issuer: undefined
1202 })),
1203 20,
1204 (job, push, callback) => {
1205 const { type, context, path, expected } = job;
1206 const resolveDirectory = path => {
1207 const key = `d\n${context}\n${path}`;
1208 if (resolveResults.has(key)) {
1209 return callback();
1210 }
1211 resolveResults.set(key, undefined);
1212 resolveContext(context, path, resolverContext, (err, result) => {
1213 if (err) {
1214 invalidResolveResults.add(key);
1215 if (
1216 err.code === "ENOENT" ||
1217 err.code === "UNDECLARED_DEPENDENCY"
1218 ) {
1219 return callback();
1220 }
1221 err.message += `\nwhile resolving '${path}' in ${context} to a directory`;
1222 return callback(err);
1223 }
1224 resolveResults.set(key, result);
1225 push({
1226 type: RBDT_DIRECTORY,
1227 context: undefined,
1228 path: result,
1229 expected: undefined,
1230 issuer: job
1231 });
1232 callback();
1233 });
1234 };
1235 const resolveFile = (path, symbol, resolve) => {
1236 const key = `${symbol}\n${context}\n${path}`;
1237 if (resolveResults.has(key)) {
1238 return callback();
1239 }
1240 resolveResults.set(key, undefined);
1241 resolve(context, path, resolverContext, (err, result) => {
1242 if (expected) {
1243 if (result === expected) {
1244 resolveResults.set(key, result);
1245 } else {
1246 invalidResolveResults.add(key);
1247 this.logger.debug(
1248 `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${result}' instead. Resolving dependencies are ignored for this path.\n${pathToString(
1249 job
1250 )}`
1251 );
1252 }
1253 } else {
1254 if (err) {
1255 invalidResolveResults.add(key);
1256 if (
1257 err.code === "ENOENT" ||
1258 err.code === "UNDECLARED_DEPENDENCY"
1259 ) {
1260 return callback();
1261 }
1262 err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString(
1263 job
1264 )}`;
1265 return callback(err);
1266 }
1267 resolveResults.set(key, result);
1268 push({
1269 type: RBDT_FILE,
1270 context: undefined,
1271 path: result,
1272 expected: undefined,
1273 issuer: job
1274 });
1275 }
1276 callback();
1277 });
1278 };
1279 switch (type) {
1280 case RBDT_RESOLVE_CJS: {
1281 const isDirectory = /[\\/]$/.test(path);
1282 if (isDirectory) {
1283 resolveDirectory(path.slice(0, path.length - 1));
1284 } else {
1285 resolveFile(path, "f", resolveCjs);
1286 }
1287 break;
1288 }
1289 case RBDT_RESOLVE_ESM: {
1290 const isDirectory = /[\\/]$/.test(path);
1291 if (isDirectory) {
1292 resolveDirectory(path.slice(0, path.length - 1));
1293 } else {
1294 resolveFile(path);
1295 }
1296 break;
1297 }
1298 case RBDT_RESOLVE_DIRECTORY: {
1299 resolveDirectory(path);
1300 break;
1301 }
1302 case RBDT_RESOLVE_CJS_FILE: {
1303 resolveFile(path, "f", resolveCjs);
1304 break;
1305 }
1306 case RBDT_RESOLVE_ESM_FILE: {
1307 resolveFile(path, "e", resolveEsm);
1308 break;
1309 }
1310 case RBDT_FILE: {
1311 if (files.has(path)) {
1312 callback();
1313 break;
1314 }
1315 files.add(path);
1316 this.fs.realpath(path, (err, _realPath) => {
1317 if (err) return callback(err);
1318 const realPath = /** @type {string} */ (_realPath);
1319 if (realPath !== path) {
1320 fileSymlinks.add(path);
1321 resolveFiles.add(path);
1322 if (files.has(realPath)) return callback();
1323 files.add(realPath);
1324 }
1325 push({
1326 type: RBDT_FILE_DEPENDENCIES,
1327 context: undefined,
1328 path: realPath,
1329 expected: undefined,
1330 issuer: job
1331 });
1332 callback();
1333 });
1334 break;
1335 }
1336 case RBDT_DIRECTORY: {
1337 if (directories.has(path)) {
1338 callback();
1339 break;
1340 }
1341 directories.add(path);
1342 this.fs.realpath(path, (err, _realPath) => {
1343 if (err) return callback(err);
1344 const realPath = /** @type {string} */ (_realPath);
1345 if (realPath !== path) {
1346 directorySymlinks.add(path);
1347 resolveFiles.add(path);
1348 if (directories.has(realPath)) return callback();
1349 directories.add(realPath);
1350 }
1351 push({
1352 type: RBDT_DIRECTORY_DEPENDENCIES,
1353 context: undefined,
1354 path: realPath,
1355 expected: undefined,
1356 issuer: job
1357 });
1358 callback();
1359 });
1360 break;
1361 }
1362 case RBDT_FILE_DEPENDENCIES: {
1363 // Check for known files without dependencies
1364 if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) {
1365 process.nextTick(callback);
1366 break;
1367 }
1368 // Check commonjs cache for the module
1369 /** @type {NodeModule} */
1370 const module = require.cache[path];
1371 if (module && Array.isArray(module.children)) {
1372 children: for (const child of module.children) {
1373 let childPath = child.filename;
1374 if (childPath) {
1375 push({
1376 type: RBDT_FILE,
1377 context: undefined,
1378 path: childPath,
1379 expected: undefined,
1380 issuer: job
1381 });
1382 const context = dirname(this.fs, path);
1383 for (const modulePath of module.paths) {
1384 if (childPath.startsWith(modulePath)) {
1385 let request = childPath.slice(modulePath.length + 1);
1386 if (request.endsWith(".js"))
1387 request = request.slice(0, -3);
1388 push({
1389 type: RBDT_RESOLVE_CJS_FILE,
1390 context,
1391 path: request,
1392 expected: child.filename,
1393 issuer: job
1394 });
1395 continue children;
1396 }
1397 }
1398 let request = relative(this.fs, context, childPath);
1399 if (request.endsWith(".js")) request = request.slice(0, -3);
1400 request = request.replace(/\\/g, "/");
1401 if (!request.startsWith("../")) request = `./${request}`;
1402 push({
1403 type: RBDT_RESOLVE_CJS_FILE,
1404 context,
1405 path: request,
1406 expected: child.filename,
1407 issuer: job
1408 });
1409 }
1410 }
1411 } else if (supportsEsm && /\.m?js$/.test(path)) {
1412 if (!this._warnAboutExperimentalEsmTracking) {
1413 this.logger.info(
1414 "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" +
1415 "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" +
1416 "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking."
1417 );
1418 this._warnAboutExperimentalEsmTracking = true;
1419 }
1420 const lexer = require("es-module-lexer");
1421 lexer.init.then(() => {
1422 this.fs.readFile(path, (err, content) => {
1423 if (err) return callback(err);
1424 try {
1425 const context = dirname(this.fs, path);
1426 const source = content.toString();
1427 const [imports] = lexer.parse(source);
1428 for (const imp of imports) {
1429 try {
1430 let dependency;
1431 if (imp.d === -1) {
1432 // import ... from "..."
1433 dependency = JSON.parse(
1434 source.substring(imp.s - 1, imp.e + 1)
1435 );
1436 } else if (imp.d > -1) {
1437 // import()
1438 let expr = source.substring(imp.s, imp.e).trim();
1439 if (expr[0] === "'")
1440 expr = `"${expr
1441 .slice(1, -1)
1442 .replace(/"/g, '\\"')}"`;
1443 dependency = JSON.parse(expr);
1444 } else {
1445 // e.g. import.meta
1446 continue;
1447 }
1448 push({
1449 type: RBDT_RESOLVE_ESM_FILE,
1450 context,
1451 path: dependency,
1452 expected: undefined,
1453 issuer: job
1454 });
1455 } catch (e) {
1456 this.logger.warn(
1457 `Parsing of ${path} for build dependencies failed at 'import(${source.substring(
1458 imp.s,
1459 imp.e
1460 )})'.\n` +
1461 "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation."
1462 );
1463 this.logger.debug(pathToString(job));
1464 this.logger.debug(e.stack);
1465 }
1466 }
1467 } catch (e) {
1468 this.logger.warn(
1469 `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..`
1470 );
1471 this.logger.debug(pathToString(job));
1472 this.logger.debug(e.stack);
1473 }
1474 process.nextTick(callback);
1475 });
1476 }, callback);
1477 break;
1478 } else {
1479 this.logger.log(
1480 `Assuming ${path} has no dependencies as we were unable to assign it to any module system.`
1481 );
1482 this.logger.debug(pathToString(job));
1483 }
1484 process.nextTick(callback);
1485 break;
1486 }
1487 case RBDT_DIRECTORY_DEPENDENCIES: {
1488 const match = /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(
1489 path
1490 );
1491 const packagePath = match ? match[1] : path;
1492 const packageJson = join(this.fs, packagePath, "package.json");
1493 this.fs.readFile(packageJson, (err, content) => {
1494 if (err) {
1495 if (err.code === "ENOENT") {
1496 resolveMissing.add(packageJson);
1497 const parent = dirname(this.fs, packagePath);
1498 if (parent !== packagePath) {
1499 push({
1500 type: RBDT_DIRECTORY_DEPENDENCIES,
1501 context: undefined,
1502 path: parent,
1503 expected: undefined,
1504 issuer: job
1505 });
1506 }
1507 callback();
1508 return;
1509 }
1510 return callback(err);
1511 }
1512 resolveFiles.add(packageJson);
1513 let packageData;
1514 try {
1515 packageData = JSON.parse(content.toString("utf-8"));
1516 } catch (e) {
1517 return callback(e);
1518 }
1519 const depsObject = packageData.dependencies;
1520 if (typeof depsObject === "object" && depsObject) {
1521 for (const dep of Object.keys(depsObject)) {
1522 push({
1523 type: RBDT_RESOLVE_DIRECTORY,
1524 context: packagePath,
1525 path: dep,
1526 expected: undefined,
1527 issuer: job
1528 });
1529 }
1530 }
1531 callback();
1532 });
1533 break;
1534 }
1535 }
1536 },
1537 err => {
1538 if (err) return callback(err);
1539 for (const l of fileSymlinks) files.delete(l);
1540 for (const l of directorySymlinks) directories.delete(l);
1541 for (const k of invalidResolveResults) resolveResults.delete(k);
1542 callback(null, {
1543 files,
1544 directories,
1545 missing,
1546 resolveResults,
1547 resolveDependencies: {
1548 files: resolveFiles,
1549 directories: resolveDirectories,
1550 missing: resolveMissing
1551 }
1552 });
1553 }
1554 );
1555 }
1556
1557 /**
1558 * @param {Map<string, string>} resolveResults results from resolving
1559 * @param {function(Error=, boolean=): void} callback callback with true when resolveResults resolve the same way
1560 * @returns {void}
1561 */
1562 checkResolveResultsValid(resolveResults, callback) {
1563 const {
1564 resolveCjs,
1565 resolveEsm,
1566 resolveContext
1567 } = this._createBuildDependenciesResolvers();
1568 asyncLib.eachLimit(
1569 resolveResults,
1570 20,
1571 ([key, expectedResult], callback) => {
1572 const [type, context, path] = key.split("\n");
1573 switch (type) {
1574 case "d":
1575 resolveContext(context, path, {}, (err, result) => {
1576 if (err) return callback(err);
1577 if (result !== expectedResult) return callback(INVALID);
1578 callback();
1579 });
1580 break;
1581 case "f":
1582 resolveCjs(context, path, {}, (err, result) => {
1583 if (err) return callback(err);
1584 if (result !== expectedResult) return callback(INVALID);
1585 callback();
1586 });
1587 break;
1588 case "e":
1589 resolveEsm(context, path, {}, (err, result) => {
1590 if (err) return callback(err);
1591 if (result !== expectedResult) return callback(INVALID);
1592 callback();
1593 });
1594 break;
1595 default:
1596 callback(new Error("Unexpected type in resolve result key"));
1597 break;
1598 }
1599 },
1600 /**
1601 * @param {Error | typeof INVALID=} err error or invalid flag
1602 * @returns {void}
1603 */
1604 err => {
1605 if (err === INVALID) {
1606 return callback(null, false);
1607 }
1608 if (err) {
1609 return callback(err);
1610 }
1611 return callback(null, true);
1612 }
1613 );
1614 }
1615
1616 /**
1617 *
1618 * @param {number} startTime when processing the files has started
1619 * @param {Iterable<string>} files all files
1620 * @param {Iterable<string>} directories all directories
1621 * @param {Iterable<string>} missing all missing files or directories
1622 * @param {Object} options options object (for future extensions)
1623 * @param {boolean=} options.hash should use hash to snapshot
1624 * @param {boolean=} options.timestamp should use timestamp to snapshot
1625 * @param {function(WebpackError=, Snapshot=): void} callback callback function
1626 * @returns {void}
1627 */
1628 createSnapshot(startTime, files, directories, missing, options, callback) {
1629 /** @type {Map<string, FileSystemInfoEntry>} */
1630 const fileTimestamps = new Map();
1631 /** @type {Map<string, string>} */
1632 const fileHashes = new Map();
1633 /** @type {Map<string, TimestampAndHash | string>} */
1634 const fileTshs = new Map();
1635 /** @type {Map<string, FileSystemInfoEntry>} */
1636 const contextTimestamps = new Map();
1637 /** @type {Map<string, string>} */
1638 const contextHashes = new Map();
1639 /** @type {Map<string, TimestampAndHash | string>} */
1640 const contextTshs = new Map();
1641 /** @type {Map<string, boolean>} */
1642 const missingExistence = new Map();
1643 /** @type {Map<string, string>} */
1644 const managedItemInfo = new Map();
1645 /** @type {Set<string>} */
1646 const managedFiles = new Set();
1647 /** @type {Set<string>} */
1648 const managedContexts = new Set();
1649 /** @type {Set<string>} */
1650 const managedMissing = new Set();
1651 /** @type {Set<Snapshot>} */
1652 const children = new Set();
1653
1654 /** @type {Set<string>} */
1655 let unsharedFileTimestamps;
1656 /** @type {Set<string>} */
1657 let unsharedFileHashes;
1658 /** @type {Set<string>} */
1659 let unsharedFileTshs;
1660 /** @type {Set<string>} */
1661 let unsharedContextTimestamps;
1662 /** @type {Set<string>} */
1663 let unsharedContextHashes;
1664 /** @type {Set<string>} */
1665 let unsharedContextTshs;
1666 /** @type {Set<string>} */
1667 let unsharedMissingExistence;
1668 /** @type {Set<string>} */
1669 let unsharedManagedItemInfo;
1670
1671 /** @type {Set<string>} */
1672 const managedItems = new Set();
1673
1674 /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */
1675 const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1;
1676
1677 let jobs = 1;
1678 const jobDone = () => {
1679 if (--jobs === 0) {
1680 const snapshot = new Snapshot();
1681 if (startTime) snapshot.setStartTime(startTime);
1682 if (fileTimestamps.size !== 0) {
1683 snapshot.setFileTimestamps(fileTimestamps);
1684 this._fileTimestampsOptimization.storeUnsharedSnapshot(
1685 snapshot,
1686 unsharedFileTimestamps
1687 );
1688 }
1689 if (fileHashes.size !== 0) {
1690 snapshot.setFileHashes(fileHashes);
1691 this._fileHashesOptimization.storeUnsharedSnapshot(
1692 snapshot,
1693 unsharedFileHashes
1694 );
1695 }
1696 if (fileTshs.size !== 0) {
1697 snapshot.setFileTshs(fileTshs);
1698 this._fileTshsOptimization.storeUnsharedSnapshot(
1699 snapshot,
1700 unsharedFileTshs
1701 );
1702 }
1703 if (contextTimestamps.size !== 0) {
1704 snapshot.setContextTimestamps(contextTimestamps);
1705 this._contextTimestampsOptimization.storeUnsharedSnapshot(
1706 snapshot,
1707 unsharedContextTimestamps
1708 );
1709 }
1710 if (contextHashes.size !== 0) {
1711 snapshot.setContextHashes(contextHashes);
1712 this._contextHashesOptimization.storeUnsharedSnapshot(
1713 snapshot,
1714 unsharedContextHashes
1715 );
1716 }
1717 if (contextTshs.size !== 0) {
1718 snapshot.setContextTshs(contextTshs);
1719 this._contextTshsOptimization.storeUnsharedSnapshot(
1720 snapshot,
1721 unsharedContextTshs
1722 );
1723 }
1724 if (missingExistence.size !== 0) {
1725 snapshot.setMissingExistence(missingExistence);
1726 this._missingExistenceOptimization.storeUnsharedSnapshot(
1727 snapshot,
1728 unsharedMissingExistence
1729 );
1730 }
1731 if (managedItemInfo.size !== 0) {
1732 snapshot.setManagedItemInfo(managedItemInfo);
1733 this._managedItemInfoOptimization.storeUnsharedSnapshot(
1734 snapshot,
1735 unsharedManagedItemInfo
1736 );
1737 }
1738 const unsharedManagedFiles = this._managedFilesOptimization.optimize(
1739 managedFiles,
1740 undefined,
1741 children
1742 );
1743 if (managedFiles.size !== 0) {
1744 snapshot.setManagedFiles(managedFiles);
1745 this._managedFilesOptimization.storeUnsharedSnapshot(
1746 snapshot,
1747 unsharedManagedFiles
1748 );
1749 }
1750 const unsharedManagedContexts = this._managedContextsOptimization.optimize(
1751 managedContexts,
1752 undefined,
1753 children
1754 );
1755 if (managedContexts.size !== 0) {
1756 snapshot.setManagedContexts(managedContexts);
1757 this._managedContextsOptimization.storeUnsharedSnapshot(
1758 snapshot,
1759 unsharedManagedContexts
1760 );
1761 }
1762 const unsharedManagedMissing = this._managedMissingOptimization.optimize(
1763 managedMissing,
1764 undefined,
1765 children
1766 );
1767 if (managedMissing.size !== 0) {
1768 snapshot.setManagedMissing(managedMissing);
1769 this._managedMissingOptimization.storeUnsharedSnapshot(
1770 snapshot,
1771 unsharedManagedMissing
1772 );
1773 }
1774 if (children.size !== 0) {
1775 snapshot.setChildren(children);
1776 }
1777 this._snapshotCache.set(snapshot, true);
1778 this._statCreatedSnapshots++;
1779
1780 callback(null, snapshot);
1781 }
1782 };
1783 const jobError = () => {
1784 if (jobs > 0) {
1785 // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
1786 jobs = -100000000;
1787 callback(null, null);
1788 }
1789 };
1790 const checkManaged = (path, managedSet) => {
1791 for (const immutablePath of this.immutablePathsWithSlash) {
1792 if (path.startsWith(immutablePath)) {
1793 managedSet.add(path);
1794 return true;
1795 }
1796 }
1797 for (const managedPath of this.managedPathsWithSlash) {
1798 if (path.startsWith(managedPath)) {
1799 const managedItem = getManagedItem(managedPath, path);
1800 if (managedItem) {
1801 managedItems.add(managedItem);
1802 managedSet.add(path);
1803 return true;
1804 }
1805 }
1806 }
1807 return false;
1808 };
1809 const captureNonManaged = (items, managedSet) => {
1810 const capturedItems = new Set();
1811 for (const path of items) {
1812 if (!checkManaged(path, managedSet)) capturedItems.add(path);
1813 }
1814 return capturedItems;
1815 };
1816 if (files) {
1817 const capturedFiles = captureNonManaged(files, managedFiles);
1818 switch (mode) {
1819 case 3:
1820 unsharedFileTshs = this._fileTshsOptimization.optimize(
1821 capturedFiles,
1822 undefined,
1823 children
1824 );
1825 for (const path of capturedFiles) {
1826 const cache = this._fileTshs.get(path);
1827 if (cache !== undefined) {
1828 fileTshs.set(path, cache);
1829 } else {
1830 jobs++;
1831 this._getFileTimestampAndHash(path, (err, entry) => {
1832 if (err) {
1833 if (this.logger) {
1834 this.logger.debug(
1835 `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}`
1836 );
1837 }
1838 jobError();
1839 } else {
1840 fileTshs.set(path, entry);
1841 jobDone();
1842 }
1843 });
1844 }
1845 }
1846 break;
1847 case 2:
1848 unsharedFileHashes = this._fileHashesOptimization.optimize(
1849 capturedFiles,
1850 undefined,
1851 children
1852 );
1853 for (const path of capturedFiles) {
1854 const cache = this._fileHashes.get(path);
1855 if (cache !== undefined) {
1856 fileHashes.set(path, cache);
1857 } else {
1858 jobs++;
1859 this.fileHashQueue.add(path, (err, entry) => {
1860 if (err) {
1861 if (this.logger) {
1862 this.logger.debug(
1863 `Error snapshotting file hash of ${path}: ${err.stack}`
1864 );
1865 }
1866 jobError();
1867 } else {
1868 fileHashes.set(path, entry);
1869 jobDone();
1870 }
1871 });
1872 }
1873 }
1874 break;
1875 case 1:
1876 unsharedFileTimestamps = this._fileTimestampsOptimization.optimize(
1877 capturedFiles,
1878 startTime,
1879 children
1880 );
1881 for (const path of capturedFiles) {
1882 const cache = this._fileTimestamps.get(path);
1883 if (cache !== undefined) {
1884 if (cache !== "ignore") {
1885 fileTimestamps.set(path, cache);
1886 }
1887 } else {
1888 jobs++;
1889 this.fileTimestampQueue.add(path, (err, entry) => {
1890 if (err) {
1891 if (this.logger) {
1892 this.logger.debug(
1893 `Error snapshotting file timestamp of ${path}: ${err.stack}`
1894 );
1895 }
1896 jobError();
1897 } else {
1898 fileTimestamps.set(path, entry);
1899 jobDone();
1900 }
1901 });
1902 }
1903 }
1904 break;
1905 }
1906 }
1907 if (directories) {
1908 const capturedDirectories = captureNonManaged(
1909 directories,
1910 managedContexts
1911 );
1912 switch (mode) {
1913 case 3:
1914 unsharedContextTshs = this._contextTshsOptimization.optimize(
1915 capturedDirectories,
1916 undefined,
1917 children
1918 );
1919 for (const path of capturedDirectories) {
1920 const cache = this._contextTshs.get(path);
1921 if (cache !== undefined) {
1922 contextTshs.set(path, cache);
1923 } else {
1924 jobs++;
1925 this._getContextTimestampAndHash(path, (err, entry) => {
1926 if (err) {
1927 if (this.logger) {
1928 this.logger.debug(
1929 `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}`
1930 );
1931 }
1932 jobError();
1933 } else {
1934 contextTshs.set(path, entry);
1935 jobDone();
1936 }
1937 });
1938 }
1939 }
1940 break;
1941 case 2:
1942 unsharedContextHashes = this._contextHashesOptimization.optimize(
1943 capturedDirectories,
1944 undefined,
1945 children
1946 );
1947 for (const path of capturedDirectories) {
1948 const cache = this._contextHashes.get(path);
1949 if (cache !== undefined) {
1950 contextHashes.set(path, cache);
1951 } else {
1952 jobs++;
1953 this.contextHashQueue.add(path, (err, entry) => {
1954 if (err) {
1955 if (this.logger) {
1956 this.logger.debug(
1957 `Error snapshotting context hash of ${path}: ${err.stack}`
1958 );
1959 }
1960 jobError();
1961 } else {
1962 contextHashes.set(path, entry);
1963 jobDone();
1964 }
1965 });
1966 }
1967 }
1968 break;
1969 case 1:
1970 unsharedContextTimestamps = this._contextTimestampsOptimization.optimize(
1971 capturedDirectories,
1972 startTime,
1973 children
1974 );
1975 for (const path of capturedDirectories) {
1976 const cache = this._contextTimestamps.get(path);
1977 if (cache !== undefined) {
1978 if (cache !== "ignore") {
1979 contextTimestamps.set(path, cache);
1980 }
1981 } else {
1982 jobs++;
1983 this.contextTimestampQueue.add(path, (err, entry) => {
1984 if (err) {
1985 if (this.logger) {
1986 this.logger.debug(
1987 `Error snapshotting context timestamp of ${path}: ${err.stack}`
1988 );
1989 }
1990 jobError();
1991 } else {
1992 contextTimestamps.set(path, entry);
1993 jobDone();
1994 }
1995 });
1996 }
1997 }
1998 break;
1999 }
2000 }
2001 if (missing) {
2002 const capturedMissing = captureNonManaged(missing, managedMissing);
2003 unsharedMissingExistence = this._missingExistenceOptimization.optimize(
2004 capturedMissing,
2005 startTime,
2006 children
2007 );
2008 for (const path of capturedMissing) {
2009 const cache = this._fileTimestamps.get(path);
2010 if (cache !== undefined) {
2011 if (cache !== "ignore") {
2012 missingExistence.set(path, toExistence(cache));
2013 }
2014 } else {
2015 jobs++;
2016 this.fileTimestampQueue.add(path, (err, entry) => {
2017 if (err) {
2018 if (this.logger) {
2019 this.logger.debug(
2020 `Error snapshotting missing timestamp of ${path}: ${err.stack}`
2021 );
2022 }
2023 jobError();
2024 } else {
2025 missingExistence.set(path, toExistence(entry));
2026 jobDone();
2027 }
2028 });
2029 }
2030 }
2031 }
2032 unsharedManagedItemInfo = this._managedItemInfoOptimization.optimize(
2033 managedItems,
2034 undefined,
2035 children
2036 );
2037 for (const path of managedItems) {
2038 const cache = this._managedItems.get(path);
2039 if (cache !== undefined) {
2040 managedItemInfo.set(path, cache);
2041 } else {
2042 jobs++;
2043 this.managedItemQueue.add(path, (err, entry) => {
2044 if (err) {
2045 if (this.logger) {
2046 this.logger.debug(
2047 `Error snapshotting managed item ${path}: ${err.stack}`
2048 );
2049 }
2050 jobError();
2051 } else {
2052 managedItemInfo.set(path, entry);
2053 jobDone();
2054 }
2055 });
2056 }
2057 }
2058 jobDone();
2059 }
2060
2061 /**
2062 * @param {Snapshot} snapshot1 a snapshot
2063 * @param {Snapshot} snapshot2 a snapshot
2064 * @returns {Snapshot} merged snapshot
2065 */
2066 mergeSnapshots(snapshot1, snapshot2) {
2067 const snapshot = new Snapshot();
2068 if (snapshot1.hasStartTime() && snapshot2.hasStartTime())
2069 snapshot.setStartTime(Math.min(snapshot1.startTime, snapshot2.startTime));
2070 else if (snapshot2.hasStartTime()) snapshot.startTime = snapshot2.startTime;
2071 else if (snapshot1.hasStartTime()) snapshot.startTime = snapshot1.startTime;
2072 if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) {
2073 snapshot.setFileTimestamps(
2074 mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps)
2075 );
2076 }
2077 if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) {
2078 snapshot.setFileHashes(
2079 mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes)
2080 );
2081 }
2082 if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) {
2083 snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs));
2084 }
2085 if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) {
2086 snapshot.setContextTimestamps(
2087 mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps)
2088 );
2089 }
2090 if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) {
2091 snapshot.setContextHashes(
2092 mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes)
2093 );
2094 }
2095 if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) {
2096 snapshot.setContextTshs(
2097 mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs)
2098 );
2099 }
2100 if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) {
2101 snapshot.setMissingExistence(
2102 mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence)
2103 );
2104 }
2105 if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) {
2106 snapshot.setManagedItemInfo(
2107 mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo)
2108 );
2109 }
2110 if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) {
2111 snapshot.setManagedFiles(
2112 mergeSets(snapshot1.managedFiles, snapshot2.managedFiles)
2113 );
2114 }
2115 if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) {
2116 snapshot.setManagedContexts(
2117 mergeSets(snapshot1.managedContexts, snapshot2.managedContexts)
2118 );
2119 }
2120 if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) {
2121 snapshot.setManagedMissing(
2122 mergeSets(snapshot1.managedMissing, snapshot2.managedMissing)
2123 );
2124 }
2125 if (snapshot1.hasChildren() || snapshot2.hasChildren()) {
2126 snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children));
2127 }
2128 if (
2129 this._snapshotCache.get(snapshot1) === true &&
2130 this._snapshotCache.get(snapshot2) === true
2131 ) {
2132 this._snapshotCache.set(snapshot, true);
2133 }
2134 return snapshot;
2135 }
2136
2137 /**
2138 * @param {Snapshot} snapshot the snapshot made
2139 * @param {function(WebpackError=, boolean=): void} callback callback function
2140 * @returns {void}
2141 */
2142 checkSnapshotValid(snapshot, callback) {
2143 const cachedResult = this._snapshotCache.get(snapshot);
2144 if (cachedResult !== undefined) {
2145 this._statTestedSnapshotsCached++;
2146 if (typeof cachedResult === "boolean") {
2147 callback(null, cachedResult);
2148 } else {
2149 cachedResult.push(callback);
2150 }
2151 return;
2152 }
2153 this._statTestedSnapshotsNotCached++;
2154 this._checkSnapshotValidNoCache(snapshot, callback);
2155 }
2156
2157 /**
2158 * @param {Snapshot} snapshot the snapshot made
2159 * @param {function(WebpackError=, boolean=): void} callback callback function
2160 * @returns {void}
2161 */
2162 _checkSnapshotValidNoCache(snapshot, callback) {
2163 /** @type {number | undefined} */
2164 let startTime = undefined;
2165 if (snapshot.hasStartTime()) {
2166 startTime = snapshot.startTime;
2167 }
2168 let jobs = 1;
2169 const jobDone = () => {
2170 if (--jobs === 0) {
2171 this._snapshotCache.set(snapshot, true);
2172 callback(null, true);
2173 }
2174 };
2175 const invalid = () => {
2176 if (jobs > 0) {
2177 // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
2178 jobs = -100000000;
2179 this._snapshotCache.set(snapshot, false);
2180 callback(null, false);
2181 }
2182 };
2183 const invalidWithError = (path, err) => {
2184 if (this._remainingLogs > 0) {
2185 this._log(path, `error occurred: %s`, err);
2186 }
2187 invalid();
2188 };
2189 /**
2190 * @param {string} path file path
2191 * @param {string} current current hash
2192 * @param {string} snap snapshot hash
2193 * @returns {boolean} true, if ok
2194 */
2195 const checkHash = (path, current, snap) => {
2196 if (current !== snap) {
2197 // If hash differ it's invalid
2198 if (this._remainingLogs > 0) {
2199 this._log(path, `hashes differ (%s != %s)`, current, snap);
2200 }
2201 return false;
2202 }
2203 return true;
2204 };
2205 /**
2206 * @param {string} path file path
2207 * @param {boolean} current current entry
2208 * @param {boolean} snap entry from snapshot
2209 * @returns {boolean} true, if ok
2210 */
2211 const checkExistence = (path, current, snap) => {
2212 if (!current !== !snap) {
2213 // If existence of item differs
2214 // it's invalid
2215 if (this._remainingLogs > 0) {
2216 this._log(
2217 path,
2218 current ? "it didn't exist before" : "it does no longer exist"
2219 );
2220 }
2221 return false;
2222 }
2223 return true;
2224 };
2225 /**
2226 * @param {string} path file path
2227 * @param {FileSystemInfoEntry} current current entry
2228 * @param {FileSystemInfoEntry} snap entry from snapshot
2229 * @param {boolean} log log reason
2230 * @returns {boolean} true, if ok
2231 */
2232 const checkFile = (path, current, snap, log = true) => {
2233 if (current === snap) return true;
2234 if (!current !== !snap) {
2235 // If existence of item differs
2236 // it's invalid
2237 if (log && this._remainingLogs > 0) {
2238 this._log(
2239 path,
2240 current ? "it didn't exist before" : "it does no longer exist"
2241 );
2242 }
2243 return false;
2244 }
2245 if (current) {
2246 // For existing items only
2247 if (typeof startTime === "number" && current.safeTime > startTime) {
2248 // If a change happened after starting reading the item
2249 // this may no longer be valid
2250 if (log && this._remainingLogs > 0) {
2251 this._log(
2252 path,
2253 `it may have changed (%d) after the start time of the snapshot (%d)`,
2254 current.safeTime,
2255 startTime
2256 );
2257 }
2258 return false;
2259 }
2260 if (
2261 snap.timestamp !== undefined &&
2262 current.timestamp !== snap.timestamp
2263 ) {
2264 // If we have a timestamp (it was a file or symlink) and it differs from current timestamp
2265 // it's invalid
2266 if (log && this._remainingLogs > 0) {
2267 this._log(
2268 path,
2269 `timestamps differ (%d != %d)`,
2270 current.timestamp,
2271 snap.timestamp
2272 );
2273 }
2274 return false;
2275 }
2276 if (
2277 snap.timestampHash !== undefined &&
2278 current.timestampHash !== snap.timestampHash
2279 ) {
2280 // If we have a timestampHash (it was a directory) and it differs from current timestampHash
2281 // it's invalid
2282 if (log && this._remainingLogs > 0) {
2283 this._log(
2284 path,
2285 `timestamps hashes differ (%s != %s)`,
2286 current.timestampHash,
2287 snap.timestampHash
2288 );
2289 }
2290 return false;
2291 }
2292 }
2293 return true;
2294 };
2295 if (snapshot.hasChildren()) {
2296 const childCallback = (err, result) => {
2297 if (err || !result) return invalid();
2298 else jobDone();
2299 };
2300 for (const child of snapshot.children) {
2301 const cache = this._snapshotCache.get(child);
2302 if (cache !== undefined) {
2303 this._statTestedChildrenCached++;
2304 /* istanbul ignore else */
2305 if (typeof cache === "boolean") {
2306 if (cache === false) {
2307 invalid();
2308 return;
2309 }
2310 } else {
2311 jobs++;
2312 cache.push(childCallback);
2313 }
2314 } else {
2315 this._statTestedChildrenNotCached++;
2316 jobs++;
2317 this._checkSnapshotValidNoCache(child, childCallback);
2318 }
2319 }
2320 }
2321 if (snapshot.hasFileTimestamps()) {
2322 const { fileTimestamps } = snapshot;
2323 this._statTestedEntries += fileTimestamps.size;
2324 for (const [path, ts] of fileTimestamps) {
2325 const cache = this._fileTimestamps.get(path);
2326 if (cache !== undefined) {
2327 if (cache !== "ignore" && !checkFile(path, cache, ts)) {
2328 invalid();
2329 return;
2330 }
2331 } else {
2332 jobs++;
2333 this.fileTimestampQueue.add(path, (err, entry) => {
2334 if (err) return invalidWithError(path, err);
2335 if (!checkFile(path, entry, ts)) {
2336 invalid();
2337 } else {
2338 jobDone();
2339 }
2340 });
2341 }
2342 }
2343 }
2344 const processFileHashSnapshot = (path, hash) => {
2345 const cache = this._fileHashes.get(path);
2346 if (cache !== undefined) {
2347 if (cache !== "ignore" && !checkHash(path, cache, hash)) {
2348 invalid();
2349 return;
2350 }
2351 } else {
2352 jobs++;
2353 this.fileHashQueue.add(path, (err, entry) => {
2354 if (err) return invalidWithError(path, err);
2355 if (!checkHash(path, entry, hash)) {
2356 invalid();
2357 } else {
2358 jobDone();
2359 }
2360 });
2361 }
2362 };
2363 if (snapshot.hasFileHashes()) {
2364 const { fileHashes } = snapshot;
2365 this._statTestedEntries += fileHashes.size;
2366 for (const [path, hash] of fileHashes) {
2367 processFileHashSnapshot(path, hash);
2368 }
2369 }
2370 if (snapshot.hasFileTshs()) {
2371 const { fileTshs } = snapshot;
2372 this._statTestedEntries += fileTshs.size;
2373 for (const [path, tsh] of fileTshs) {
2374 if (typeof tsh === "string") {
2375 processFileHashSnapshot(path, tsh);
2376 } else {
2377 const cache = this._fileTimestamps.get(path);
2378 if (cache !== undefined) {
2379 if (cache === "ignore" || !checkFile(path, cache, tsh, false)) {
2380 processFileHashSnapshot(path, tsh.hash);
2381 }
2382 } else {
2383 jobs++;
2384 this.fileTimestampQueue.add(path, (err, entry) => {
2385 if (err) return invalidWithError(path, err);
2386 if (!checkFile(path, entry, tsh, false)) {
2387 processFileHashSnapshot(path, tsh.hash);
2388 }
2389 jobDone();
2390 });
2391 }
2392 }
2393 }
2394 }
2395 if (snapshot.hasContextTimestamps()) {
2396 const { contextTimestamps } = snapshot;
2397 this._statTestedEntries += contextTimestamps.size;
2398 for (const [path, ts] of contextTimestamps) {
2399 const cache = this._contextTimestamps.get(path);
2400 if (cache !== undefined) {
2401 if (cache !== "ignore" && !checkFile(path, cache, ts)) {
2402 invalid();
2403 return;
2404 }
2405 } else {
2406 jobs++;
2407 this.contextTimestampQueue.add(path, (err, entry) => {
2408 if (err) return invalidWithError(path, err);
2409 if (!checkFile(path, entry, ts)) {
2410 invalid();
2411 } else {
2412 jobDone();
2413 }
2414 });
2415 }
2416 }
2417 }
2418 const processContextHashSnapshot = (path, hash) => {
2419 const cache = this._contextHashes.get(path);
2420 if (cache !== undefined) {
2421 if (cache !== "ignore" && !checkHash(path, cache, hash)) {
2422 invalid();
2423 return;
2424 }
2425 } else {
2426 jobs++;
2427 this.contextHashQueue.add(path, (err, entry) => {
2428 if (err) return invalidWithError(path, err);
2429 if (!checkHash(path, entry, hash)) {
2430 invalid();
2431 } else {
2432 jobDone();
2433 }
2434 });
2435 }
2436 };
2437 if (snapshot.hasContextHashes()) {
2438 const { contextHashes } = snapshot;
2439 this._statTestedEntries += contextHashes.size;
2440 for (const [path, hash] of contextHashes) {
2441 processContextHashSnapshot(path, hash);
2442 }
2443 }
2444 if (snapshot.hasContextTshs()) {
2445 const { contextTshs } = snapshot;
2446 this._statTestedEntries += contextTshs.size;
2447 for (const [path, tsh] of contextTshs) {
2448 if (typeof tsh === "string") {
2449 processContextHashSnapshot(path, tsh);
2450 } else {
2451 const cache = this._contextTimestamps.get(path);
2452 if (cache !== undefined) {
2453 if (cache === "ignore" || !checkFile(path, cache, tsh, false)) {
2454 processContextHashSnapshot(path, tsh.hash);
2455 }
2456 } else {
2457 jobs++;
2458 this.contextTimestampQueue.add(path, (err, entry) => {
2459 if (err) return invalidWithError(path, err);
2460 if (!checkFile(path, entry, tsh, false)) {
2461 processContextHashSnapshot(path, tsh.hash);
2462 }
2463 jobDone();
2464 });
2465 }
2466 }
2467 }
2468 }
2469 if (snapshot.hasMissingExistence()) {
2470 const { missingExistence } = snapshot;
2471 this._statTestedEntries += missingExistence.size;
2472 for (const [path, existence] of missingExistence) {
2473 const cache = this._fileTimestamps.get(path);
2474 if (cache !== undefined) {
2475 if (
2476 cache !== "ignore" &&
2477 !checkExistence(path, toExistence(cache), existence)
2478 ) {
2479 invalid();
2480 return;
2481 }
2482 } else {
2483 jobs++;
2484 this.fileTimestampQueue.add(path, (err, entry) => {
2485 if (err) return invalidWithError(path, err);
2486 if (!checkExistence(path, toExistence(entry), existence)) {
2487 invalid();
2488 } else {
2489 jobDone();
2490 }
2491 });
2492 }
2493 }
2494 }
2495 if (snapshot.hasManagedItemInfo()) {
2496 const { managedItemInfo } = snapshot;
2497 this._statTestedEntries += managedItemInfo.size;
2498 for (const [path, info] of managedItemInfo) {
2499 const cache = this._managedItems.get(path);
2500 if (cache !== undefined) {
2501 if (!checkHash(path, cache, info)) {
2502 invalid();
2503 return;
2504 }
2505 } else {
2506 jobs++;
2507 this.managedItemQueue.add(path, (err, entry) => {
2508 if (err) return invalidWithError(path, err);
2509 if (!checkHash(path, entry, info)) {
2510 invalid();
2511 } else {
2512 jobDone();
2513 }
2514 });
2515 }
2516 }
2517 }
2518 jobDone();
2519
2520 // if there was an async action
2521 // try to join multiple concurrent request for this snapshot
2522 if (jobs > 0) {
2523 const callbacks = [callback];
2524 callback = (err, result) => {
2525 for (const callback of callbacks) callback(err, result);
2526 };
2527 this._snapshotCache.set(snapshot, callbacks);
2528 }
2529 }
2530
2531 _readFileTimestamp(path, callback) {
2532 this.fs.stat(path, (err, stat) => {
2533 if (err) {
2534 if (err.code === "ENOENT") {
2535 this._fileTimestamps.set(path, null);
2536 this._cachedDeprecatedFileTimestamps = undefined;
2537 return callback(null, null);
2538 }
2539 return callback(err);
2540 }
2541
2542 let ts;
2543 if (stat.isDirectory()) {
2544 ts = {
2545 safeTime: 0,
2546 timestamp: undefined
2547 };
2548 } else {
2549 const mtime = +stat.mtime;
2550
2551 if (mtime) applyMtime(mtime);
2552
2553 ts = {
2554 safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
2555 timestamp: mtime
2556 };
2557 }
2558
2559 this._fileTimestamps.set(path, ts);
2560 this._cachedDeprecatedFileTimestamps = undefined;
2561
2562 callback(null, ts);
2563 });
2564 }
2565
2566 _readFileHash(path, callback) {
2567 this.fs.readFile(path, (err, content) => {
2568 if (err) {
2569 if (err.code === "EISDIR") {
2570 this._fileHashes.set(path, "directory");
2571 return callback(null, "directory");
2572 }
2573 if (err.code === "ENOENT") {
2574 this._fileHashes.set(path, null);
2575 return callback(null, null);
2576 }
2577 if (err.code === "ERR_FS_FILE_TOO_LARGE") {
2578 this.logger.warn(`Ignoring ${path} for hashing as it's very large`);
2579 this._fileHashes.set(path, "too large");
2580 return callback(null, "too large");
2581 }
2582 return callback(err);
2583 }
2584
2585 const hash = createHash("md4");
2586
2587 hash.update(content);
2588
2589 const digest = /** @type {string} */ (hash.digest("hex"));
2590
2591 this._fileHashes.set(path, digest);
2592
2593 callback(null, digest);
2594 });
2595 }
2596
2597 _getFileTimestampAndHash(path, callback) {
2598 const continueWithHash = hash => {
2599 const cache = this._fileTimestamps.get(path);
2600 if (cache !== undefined) {
2601 if (cache !== "ignore") {
2602 const result = {
2603 ...cache,
2604 hash
2605 };
2606 this._fileTshs.set(path, result);
2607 return callback(null, result);
2608 } else {
2609 this._fileTshs.set(path, hash);
2610 return callback(null, hash);
2611 }
2612 } else {
2613 this.fileTimestampQueue.add(path, (err, entry) => {
2614 if (err) {
2615 return callback(err);
2616 }
2617 const result = {
2618 ...entry,
2619 hash
2620 };
2621 this._fileTshs.set(path, result);
2622 return callback(null, result);
2623 });
2624 }
2625 };
2626
2627 const cache = this._fileHashes.get(path);
2628 if (cache !== undefined) {
2629 continueWithHash(cache);
2630 } else {
2631 this.fileHashQueue.add(path, (err, entry) => {
2632 if (err) {
2633 return callback(err);
2634 }
2635 continueWithHash(entry);
2636 });
2637 }
2638 }
2639
2640 _readContextTimestamp(path, callback) {
2641 this.fs.readdir(path, (err, _files) => {
2642 if (err) {
2643 if (err.code === "ENOENT") {
2644 this._contextTimestamps.set(path, null);
2645 this._cachedDeprecatedContextTimestamps = undefined;
2646 return callback(null, null);
2647 }
2648 return callback(err);
2649 }
2650 const files = /** @type {string[]} */ (_files)
2651 .map(file => file.normalize("NFC"))
2652 .filter(file => !/^\./.test(file))
2653 .sort();
2654 asyncLib.map(
2655 files,
2656 (file, callback) => {
2657 const child = join(this.fs, path, file);
2658 this.fs.stat(child, (err, stat) => {
2659 if (err) return callback(err);
2660
2661 for (const immutablePath of this.immutablePathsWithSlash) {
2662 if (path.startsWith(immutablePath)) {
2663 // ignore any immutable path for timestamping
2664 return callback(null, null);
2665 }
2666 }
2667 for (const managedPath of this.managedPathsWithSlash) {
2668 if (path.startsWith(managedPath)) {
2669 const managedItem = getManagedItem(managedPath, child);
2670 if (managedItem) {
2671 // construct timestampHash from managed info
2672 return this.managedItemQueue.add(managedItem, (err, info) => {
2673 if (err) return callback(err);
2674 return callback(null, {
2675 safeTime: 0,
2676 timestampHash: info
2677 });
2678 });
2679 }
2680 }
2681 }
2682
2683 if (stat.isFile()) {
2684 return this.getFileTimestamp(child, callback);
2685 }
2686 if (stat.isDirectory()) {
2687 this.contextTimestampQueue.increaseParallelism();
2688 this.getContextTimestamp(child, (err, tsEntry) => {
2689 this.contextTimestampQueue.decreaseParallelism();
2690 callback(err, tsEntry);
2691 });
2692 return;
2693 }
2694 callback(null, null);
2695 });
2696 },
2697 (err, tsEntries) => {
2698 if (err) return callback(err);
2699 const hash = createHash("md4");
2700
2701 for (const file of files) hash.update(file);
2702 let safeTime = 0;
2703 for (const entry of tsEntries) {
2704 if (!entry) {
2705 hash.update("n");
2706 continue;
2707 }
2708 if (entry.timestamp) {
2709 hash.update("f");
2710 hash.update(`${entry.timestamp}`);
2711 } else if (entry.timestampHash) {
2712 hash.update("d");
2713 hash.update(`${entry.timestampHash}`);
2714 }
2715 if (entry.safeTime) {
2716 safeTime = Math.max(safeTime, entry.safeTime);
2717 }
2718 }
2719
2720 const digest = /** @type {string} */ (hash.digest("hex"));
2721
2722 const result = {
2723 safeTime,
2724 timestampHash: digest
2725 };
2726
2727 this._contextTimestamps.set(path, result);
2728 this._cachedDeprecatedContextTimestamps = undefined;
2729
2730 callback(null, result);
2731 }
2732 );
2733 });
2734 }
2735
2736 _readContextHash(path, callback) {
2737 this.fs.readdir(path, (err, _files) => {
2738 if (err) {
2739 if (err.code === "ENOENT") {
2740 this._contextHashes.set(path, null);
2741 return callback(null, null);
2742 }
2743 return callback(err);
2744 }
2745 const files = /** @type {string[]} */ (_files)
2746 .map(file => file.normalize("NFC"))
2747 .filter(file => !/^\./.test(file))
2748 .sort();
2749 asyncLib.map(
2750 files,
2751 (file, callback) => {
2752 const child = join(this.fs, path, file);
2753 this.fs.stat(child, (err, stat) => {
2754 if (err) return callback(err);
2755
2756 for (const immutablePath of this.immutablePathsWithSlash) {
2757 if (path.startsWith(immutablePath)) {
2758 // ignore any immutable path for hashing
2759 return callback(null, "");
2760 }
2761 }
2762 for (const managedPath of this.managedPathsWithSlash) {
2763 if (path.startsWith(managedPath)) {
2764 const managedItem = getManagedItem(managedPath, child);
2765 if (managedItem) {
2766 // construct hash from managed info
2767 return this.managedItemQueue.add(managedItem, (err, info) => {
2768 if (err) return callback(err);
2769 callback(null, info || "");
2770 });
2771 }
2772 }
2773 }
2774
2775 if (stat.isFile()) {
2776 return this.getFileHash(child, (err, hash) => {
2777 callback(err, hash || "");
2778 });
2779 }
2780 if (stat.isDirectory()) {
2781 this.contextHashQueue.increaseParallelism();
2782 this.getContextHash(child, (err, hash) => {
2783 this.contextHashQueue.decreaseParallelism();
2784 callback(err, hash || "");
2785 });
2786 return;
2787 }
2788 callback(null, "");
2789 });
2790 },
2791 (err, fileHashes) => {
2792 if (err) return callback(err);
2793 const hash = createHash("md4");
2794
2795 for (const file of files) hash.update(file);
2796 for (const h of fileHashes) hash.update(h);
2797
2798 const digest = /** @type {string} */ (hash.digest("hex"));
2799
2800 this._contextHashes.set(path, digest);
2801
2802 callback(null, digest);
2803 }
2804 );
2805 });
2806 }
2807
2808 _getContextTimestampAndHash(path, callback) {
2809 const continueWithHash = hash => {
2810 const cache = this._contextTimestamps.get(path);
2811 if (cache !== undefined) {
2812 if (cache !== "ignore") {
2813 const result = {
2814 ...cache,
2815 hash
2816 };
2817 this._contextTshs.set(path, result);
2818 return callback(null, result);
2819 } else {
2820 this._contextTshs.set(path, hash);
2821 return callback(null, hash);
2822 }
2823 } else {
2824 this.contextTimestampQueue.add(path, (err, entry) => {
2825 if (err) {
2826 return callback(err);
2827 }
2828 const result = {
2829 ...entry,
2830 hash
2831 };
2832 this._contextTshs.set(path, result);
2833 return callback(null, result);
2834 });
2835 }
2836 };
2837
2838 const cache = this._contextHashes.get(path);
2839 if (cache !== undefined) {
2840 continueWithHash(cache);
2841 } else {
2842 this.contextHashQueue.add(path, (err, entry) => {
2843 if (err) {
2844 return callback(err);
2845 }
2846 continueWithHash(entry);
2847 });
2848 }
2849 }
2850
2851 _getManagedItemDirectoryInfo(path, callback) {
2852 this.fs.readdir(path, (err, elements) => {
2853 if (err) {
2854 if (err.code === "ENOENT" || err.code === "ENOTDIR") {
2855 return callback(null, EMPTY_SET);
2856 }
2857 return callback(err);
2858 }
2859 const set = new Set(
2860 /** @type {string[]} */ (elements).map(element =>
2861 join(this.fs, path, element)
2862 )
2863 );
2864 callback(null, set);
2865 });
2866 }
2867
2868 _getManagedItemInfo(path, callback) {
2869 const dir = dirname(this.fs, path);
2870 this.managedItemDirectoryQueue.add(dir, (err, elements) => {
2871 if (err) {
2872 return callback(err);
2873 }
2874 if (!elements.has(path)) {
2875 // file or directory doesn't exist
2876 this._managedItems.set(path, "missing");
2877 return callback(null, "missing");
2878 }
2879 // something exists
2880 // it may be a file or directory
2881 if (
2882 path.endsWith("node_modules") &&
2883 (path.endsWith("/node_modules") || path.endsWith("\\node_modules"))
2884 ) {
2885 // we are only interested in existence of this special directory
2886 this._managedItems.set(path, "exists");
2887 return callback(null, "exists");
2888 }
2889
2890 // we assume it's a directory, as files shouldn't occur in managed paths
2891 const packageJsonPath = join(this.fs, path, "package.json");
2892 this.fs.readFile(packageJsonPath, (err, content) => {
2893 if (err) {
2894 if (err.code === "ENOENT" || err.code === "ENOTDIR") {
2895 // no package.json or path is not a directory
2896 this.fs.readdir(path, (err, elements) => {
2897 if (
2898 !err &&
2899 elements.length === 1 &&
2900 elements[0] === "node_modules"
2901 ) {
2902 // This is only a grouping folder e. g. used by yarn
2903 // we are only interested in existence of this special directory
2904 this._managedItems.set(path, "nested");
2905 return callback(null, "nested");
2906 }
2907 const problem = `Managed item ${path} isn't a directory or doesn't contain a package.json`;
2908 this.logger.warn(problem);
2909 return callback(new Error(problem));
2910 });
2911 return;
2912 }
2913 return callback(err);
2914 }
2915 let data;
2916 try {
2917 data = JSON.parse(content.toString("utf-8"));
2918 } catch (e) {
2919 return callback(e);
2920 }
2921 const info = `${data.name || ""}@${data.version || ""}`;
2922 this._managedItems.set(path, info);
2923 callback(null, info);
2924 });
2925 });
2926 }
2927
2928 getDeprecatedFileTimestamps() {
2929 if (this._cachedDeprecatedFileTimestamps !== undefined)
2930 return this._cachedDeprecatedFileTimestamps;
2931 const map = new Map();
2932 for (const [path, info] of this._fileTimestamps) {
2933 if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
2934 }
2935 return (this._cachedDeprecatedFileTimestamps = map);
2936 }
2937
2938 getDeprecatedContextTimestamps() {
2939 if (this._cachedDeprecatedContextTimestamps !== undefined)
2940 return this._cachedDeprecatedContextTimestamps;
2941 const map = new Map();
2942 for (const [path, info] of this._contextTimestamps) {
2943 if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
2944 }
2945 return (this._cachedDeprecatedContextTimestamps = map);
2946 }
2947}
2948
2949module.exports = FileSystemInfo;
2950module.exports.Snapshot = Snapshot;