GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — webpack/lib/Compiler.js at 531b92573505670a12498e59ec0e6157bb2e5e5f · webpack/webpack Expand file tree/ Copy pathCompiler.jsMore file actions 1709 lines (1542 loc) · 49.4 KB / Copy pathCompiler.jsFile metadata and controls1709 lines (1542 loc) · 49.4 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { AsyncParallelHook, AsyncSeriesHook, SyncBailHook, SyncHook } = require("tapable"); const { SizeOnlySource } = require("webpack-sources"); const Compilation = require("./Compilation"); const Cache = require("./cache/Cache"); const CacheFacade = require("./cache/CacheFacade"); const ContextModuleFactory = require("./context/ContextModuleFactory"); const WebpackError = require("./errors/WebpackError"); const { PERMISSIONS_MASK, dirname, join, mkdirp } = require("./fs/fs"); const ChunkGraph = require("./graph/ChunkGraph"); const ModuleGraph = require("./graph/ModuleGraph"); const { Logger } = require("./logging/Logger"); const NormalModuleFactory = require("./module/NormalModuleFactory"); const ResolverFactory = require("./resolve/ResolverFactory"); const Stats = require("./stats/Stats"); const RequestShortener = require("./util/RequestShortener"); const asyncLib = require("./util/async"); const { WINDOWS_ABS_PATH_REGEXP, makePathsRelative } = require("./util/identifier"); const memoize = require("./util/memoize"); const parseJson = require("./util/parseJson"); const { isSourceEqual } = require("./util/source"); const webpack = require("."); const getWatching = memoize(() => require("./watch/Watching")); const getValidate = memoize(() => require("schema-utils").validate); const getConcurrentCompilationError = memoize(() => require("./errors/ConcurrentCompilationError") ); /** @import { Source } from "webpack-sources" */ /** @import { AssetInfo, AssetSymlink } from "./Compilation" */ /** * @import { * EntryNormalized as Entry, * OutputNormalized as OutputOptions, * WatchOptions, * WebpackOptionsNormalized as WebpackOptions, * Plugins * } from "../declarations/WebpackOptions" */ /** @import { WebpackPluginFunction, ErrorCallback } from "./webpack" */ /** @import Chunk from "./graph/Chunk" */ /** @import Dependency from "./graph/Dependency" */ /** * @import { * ChunkHashes, * ChunkModuleHashes, * ChunkModuleIds, * ChunkRuntime, * FullHashChunkModuleHashes, * HotIndex * } from "./hmr/HotModuleReplacementPlugin" */ /** @import Module, { BuildInfo } from "./module/Module" */ /** @import Watching from "./watch/Watching" */ /** @import { RecordsChunks, RecordsModules } from "./ids/RecordIdsPlugin" */ /** @import { PlatformTargetProperties } from "./config/target" */ /** @import { LoggingFunction } from "./logging/createConsoleLogger" */ /** @import { SplitData } from "./optimize/AggressiveSplittingPlugin" */ /** * @import { * IStats, * InputFileSystem, * IntermediateFileSystem, * OutputFileSystem, * TimeInfoEntries, * WatchFileSystem * } from "./fs/fs" */ /** @import { Schema, ValidationErrorConfiguration } from "schema-utils" */ /** * Defines the compilation params type used by this module. * @typedef {object} CompilationParams * @property {NormalModuleFactory} normalModuleFactory * @property {ContextModuleFactory} contextModuleFactory */ /** * Defines the callback type used by this module. * @template T * @template [R=void] * @typedef {import("./webpack").Callback<T, R>} Callback */ /** * Defines the run as child callback callback. * @callback RunAsChildCallback * @param {Error | null} err * @param {Chunk[]=} entries * @param {Compilation=} compilation * @returns {void} */ /** * Defines the known records type used by this module. * @typedef {object} KnownRecords * @property {SplitData[]=} aggressiveSplits * @property {RecordsChunks=} chunks * @property {RecordsModules=} modules * @property {string=} hash * @property {HotIndex=} hotIndex * @property {FullHashChunkModuleHashes=} fullHashChunkModuleHashes * @property {ChunkModuleHashes=} chunkModuleHashes * @property {ChunkHashes=} chunkHashes * @property {ChunkRuntime=} chunkRuntime * @property {ChunkModuleIds=} chunkModuleIds */ /** @typedef {KnownRecords & Record<string, KnownRecords[]> & Record<string, EXPECTED_ANY>} Records */ /** * Defines the asset emitted info type used by this module. * @typedef {object} AssetEmittedInfo * @property {Buffer} content * @property {Source} source * @property {Compilation} compilation * @property {string} outputPath * @property {string} targetPath */ /** @typedef {{ sizeOnlySource: SizeOnlySource | undefined, writtenTo: Map<string, number> }} CacheEntry */ /** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: CacheEntry, file: string }[] | undefined) }} SimilarEntry */ /** @typedef {WeakMap<Dependency, Module>} WeakReferences */ /** @typedef {import("./util/WeakTupleMap")<EXPECTED_ANY[], EXPECTED_ANY>} MemCache */ /** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, lazyRequests: string | undefined, memCache: MemCache }} ModuleMemCachesItem */ /** * Checks whether this object is sorted. * @template T * @param {T[]} array an array * @returns {boolean} true, if the array is sorted */ const isSorted = (array) => { for (let i = 1; i < array.length; i++) { if (array[i - 1] > array[i]) return false; } return true; }; /** * Returns the object with properties sorted by property name. * @template {object} T * @param {T} obj an object * @param {(keyof T)[]} keys the keys of the object * @returns {T} the object with properties sorted by property name */ const sortObject = (obj, keys) => { const o = /** @type {T} */ ({}); for (const k of keys.sort()) { o[k] = obj[k]; } return o; }; /** * Returns true, if the filename contains any hash. * @param {string} filename filename * @param {string | string[] | undefined} hashes list of hashes * @returns {boolean} true, if the filename contains any hash */ const includesHash = (filename, hashes) => { if (!hashes) return false; if (Array.isArray(hashes)) { return hashes.some((hash) => filename.includes(hash)); } return filename.includes(hashes); }; // only reached by `watch()`, so a one-shot build never loads the watcher class Compiler { /** * Creates an instance of Compiler. * @param {string} context the compilation path * @param {WebpackOptions} options options */ constructor(context, options = /** @type {WebpackOptions} */ ({})) { this.hooks = Object.freeze({ /** @type {SyncHook<[]>} */ initialize: new SyncHook([]), /** @type {SyncBailHook<[Compilation], boolean | void>} */ shouldEmit: new SyncBailHook(["compilation"]), /** @type {AsyncSeriesHook<[Stats]>} */ done: new AsyncSeriesHook(["stats"]), /** @type {SyncHook<[Stats]>} */ afterDone: new SyncHook(["stats"]), /** @type {AsyncSeriesHook<[]>} */ additionalPass: new AsyncSeriesHook([]), /** @type {AsyncSeriesHook<[Compiler]>} */ beforeRun: new AsyncSeriesHook(["compiler"]), /** @type {AsyncSeriesHook<[Compiler]>} */ run: new AsyncSeriesHook(["compiler"]), /** @type {AsyncSeriesHook<[Compilation]>} */ emit: new AsyncSeriesHook(["compilation"]), /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */ assetEmitted: new AsyncSeriesHook(["file", "info"]), /** @type {AsyncSeriesHook<[Compilation]>} */ afterEmit: new AsyncSeriesHook(["compilation"]), /** @type {SyncHook<[Compilation, CompilationParams]>} */ thisCompilation: new SyncHook(["compilation", "params"]), /** @type {SyncHook<[Compilation, CompilationParams]>} */ compilation: new SyncHook(["compilation", "params"]), /** @type {SyncHook<[NormalModuleFactory]>} */ normalModuleFactory: new SyncHook(["normalModuleFactory"]), /** @type {SyncHook<[ContextModuleFactory]>} */ contextModuleFactory: new SyncHook(["contextModuleFactory"]), /** @type {AsyncSeriesHook<[CompilationParams]>} */ beforeCompile: new AsyncSeriesHook(["params"]), /** @type {SyncHook<[CompilationParams]>} */ compile: new SyncHook(["params"]), /** @type {AsyncParallelHook<[Compilation]>} */ make: new AsyncParallelHook(["compilation"]), /** @type {AsyncParallelHook<[Compilation]>} */ finishMake: new AsyncSeriesHook(["compilation"]), /** @type {AsyncSeriesHook<[Compilation]>} */ afterCompile: new AsyncSeriesHook(["compilation"]), /** * @type {AsyncSeriesHook<[]>} * @since 5.67.0 */ readRecords: new AsyncSeriesHook([]), /** * @type {AsyncSeriesHook<[]>} * @since 5.67.0 */ emitRecords: new AsyncSeriesHook([]), /** @type {AsyncSeriesHook<[Compiler]>} */ watchRun: new AsyncSeriesHook(["compiler"]), /** @type {SyncHook<[Error]>} */ failed: new SyncHook(["error"]), /** @type {SyncHook<[string | null, number]>} */ invalid: new SyncHook(["filename", "changeTime"]), /** @type {SyncHook<[]>} */ watchClose: new SyncHook([]), /** * @type {AsyncSeriesHook<[]>} * @since 5.17.0 */ shutdown: new AsyncSeriesHook([]), /** @type {SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>} */ infrastructureLog: new SyncBailHook(["origin", "type", "args"]), // TODO the following hooks are weirdly located here // TODO move them for webpack 5 /** * @type {SyncHook<[]>} * @since 5.106.0 */ validate: new SyncHook([]), /** @type {SyncHook<[]>} */ environment: new SyncHook([]), /** @type {SyncHook<[]>} */ afterEnvironment: new SyncHook([]), /** @type {SyncHook<[Compiler]>} */ afterPlugins: new SyncHook(["compiler"]), /** @type {SyncHook<[Compiler]>} */ afterResolvers: new SyncHook(["compiler"]), /** @type {SyncBailHook<[string, Entry], boolean | void>} */ entryOption: new SyncBailHook(["context", "entry"]) }); this.webpack = webpack; /** @type {string | undefined} */ this.name = undefined; /** @type {Compilation | undefined} */ this.parentCompilation = undefined; /** @type {Compiler} */ this.root = this; /** @type {string} */ this.outputPath = ""; /** @type {Watching | undefined} */ this.watching = undefined; /** @type {OutputFileSystem | null} */ this.outputFileSystem = null; /** @type {IntermediateFileSystem | null} */ this.intermediateFileSystem = null; /** @type {InputFileSystem | null} */ this.inputFileSystem = null; /** @type {WatchFileSystem | null} */ this.watchFileSystem = null; /** @type {string | null} */ this.recordsInputPath = null; /** @type {string | null} */ this.recordsOutputPath = null; /** @type {Records} */ this.records = {}; /** @type {Set<string | RegExp>} */ this.managedPaths = new Set(); /** @type {Set<string | RegExp>} */ this.unmanagedPaths = new Set(); /** @type {Set<string | RegExp>} */ this.immutablePaths = new Set(); /** @type {ReadonlySet<string> | undefined} */ this.modifiedFiles = undefined; /** @type {ReadonlySet<string> | undefined} */ this.removedFiles = undefined; /** @type {TimeInfoEntries | undefined} */ this.fileTimestamps = undefined; /** @type {TimeInfoEntries | undefined} */ this.contextTimestamps = undefined; /** @type {number | undefined} */ this.fsStartTime = undefined; /** @type {ResolverFactory} */ this.resolverFactory = new ResolverFactory(); /** @type {LoggingFunction | undefined} */ this.infrastructureLogger = undefined; /** @type {Readonly<PlatformTargetProperties>} */ this.platform = { web: null, browser: null, webworker: null, node: null, deno: null, bun: null, nwjs: null, electron: null, universal: null }; this.options = options; /** @type {string} */ this.context = context; /** @type {RequestShortener} */ this.requestShortener = new RequestShortener(context, this.root); /** @type {Cache} */ this.cache = new Cache(); /** @type {Map<Module, ModuleMemCachesItem> | undefined} */ this.moduleMemCaches = undefined; /** @type {string} */ this.compilerPath = ""; /** @type {boolean} */ this.running = false; /** @type {boolean} */ this.idle = false; /** @type {boolean} */ this.watchMode = false; /** @type {boolean} */ this._backCompat = this.options.experiments.backCompat !== false; /** @type {Compilation | undefined} */ this._lastCompilation = undefined; /** @type {NormalModuleFactory | undefined} */ this._lastNormalModuleFactory = undefined; /** * @private * @type {WeakMap<Source, CacheEntry>} */ this._assetEmittingSourceCache = new WeakMap(); /** * @private * @type {Map<string, number>} */ this._assetEmittingWrittenFiles = new Map(); /** * @private * @type {Set<string>} */ this._assetEmittingPreviousFiles = new Set(); } /** * Returns the cache facade instance. * @param {string} name cache name * @returns {CacheFacade} the cache facade instance */ getCache(name) { return new CacheFacade( this.cache, `${this.compilerPath}${name}`, this.options.output.hashFunction ); } /** * Gets infrastructure logger. * @param {string | (() => string)} name name of the logger, or function called once to get the logger name * @returns {Logger} a logger with that name */ getInfrastructureLogger(name) { if (!name) { throw new TypeError( "Compiler.getInfrastructureLogger(name) called without a name" ); } return new Logger( (type, args) => { if (typeof name === "function") { name = name(); if (!name) { throw new TypeError( "Compiler.getInfrastructureLogger(name) called with a function not returning a name" ); } } if ( this.hooks.infrastructureLog.call(name, type, args) === undefined && this.infrastructureLogger !== undefined ) { this.infrastructureLogger(name, type, args); } }, (childName) => { if (typeof name === "function") { if (typeof childName === "function") { return this.getInfrastructureLogger(() => { if (typeof name === "function") { name = name(); if (!name) { throw new TypeError( "Compiler.getInfrastructureLogger(name) called with a function not returning a name" ); } } if (typeof childName === "function") { childName = childName(); if (!childName) { throw new TypeError( "Logger.getChildLogger(name) called with a function not returning a name" ); } } return `${name}/${childName}`; }); } return this.getInfrastructureLogger(() => { if (typeof name === "function") { name = name(); if (!name) { throw new TypeError( "Compiler.getInfrastructureLogger(name) called with a function not returning a name" ); } } return `${name}/${childName}`; }); } if (typeof childName === "function") { return this.getInfrastructureLogger(() => { if (typeof childName === "function") { childName = childName(); if (!childName) { throw new TypeError( "Logger.getChildLogger(name) called with a function not returning a name" ); } } return `${name}/${childName}`; }); } return this.getInfrastructureLogger(`${name}/${childName}`); } ); } // TODO in the next major release: solve this in a better way // e.g. move compilation specific info from Modules into ModuleGraph _cleanupLastCompilation() { if (this._lastCompilation !== undefined) { this._cleanupCompilationForCache(this._lastCompilation); this._lastCompilation = undefined; } } /** * Drops the graph references a finished compilation left on its modules and * chunks. Recurses, because child compilations nest: a module only reached * below the first level keeps its parser, generator and memoized * `ModuleGraph`, which pins the whole stale compilation. * @param {Compilation} compilation compilation to clean up * @returns {void} */ _cleanupCompilationForCache(compilation) { for (const childCompilation of compilation.children) { this._cleanupCompilationForCache(childCompilation); } for (const module of compilation.modules) { ChunkGraph.clearChunkGraphForModule(module); ModuleGraph.clearModuleGraphForModule(module); module.cleanupForCache(); } for (const chunk of compilation.chunks) { ChunkGraph.clearChunkGraphForChunk(chunk); } } // TODO in the next major release: solve this in a better way _cleanupLastNormalModuleFactory() { if (this._lastNormalModuleFactory !== undefined) { this._lastNormalModuleFactory.cleanupForCache(); this._lastNormalModuleFactory = undefined; } } /** * Release fields on a finished compilation that nothing reads after emit, * so the heap can shrink while user code still holds the Stats reference. * Recurses into child compilations. Stats output is preserved — only * codeGen byproducts are dropped. * @param {Compilation} compilation finished compilation to slim down * @returns {void} */ _releaseUnusedCompilationData(compilation) { for (const child of compilation.children) { this._releaseUnusedCompilationData(child); } // Rendered source per (module × runtime) — used only during seal/emit, // never read by Stats, and not serialized to the persistent cache. if (compilation.codeGenerationResults !== undefined) { compilation.codeGenerationResults.map.clear(); } } /** * Returns a compiler watcher. * @param {WatchOptions} watchOptions the watcher's options * @param {Callback<Stats>} handler signals when the call finishes * @returns {Watching | undefined} a compiler watcher */ watch(watchOptions, handler) { if (this.running) { handler(new (getConcurrentCompilationError())()); return; } this.running = true; this.watchMode = true; const Watching = getWatching(); this.watching = new Watching(this, watchOptions, handler); return this.watching; } /** * Processes the provided stat. * @param {Callback<Stats>} callback signals when the call finishes * @returns {void} */ run(callback) { if (this.running) { callback(new (getConcurrentCompilationError())()); return; } /** @type {Logger | undefined} */ let logger; /** * Processes the provided err. * @param {Error | null} err error * @param {Stats=} stats stats */ const finalCallback = (err, stats) => { if (logger) logger.time("beginIdle"); this.idle = true; this.cache.beginIdle(); if (logger) logger.timeEnd("beginIdle"); this.running = false; if (err) { this.hooks.failed.call(err); } if (callback !== undefined) callback(err, stats); this.hooks.afterDone.call(/** @type {Stats} */ (stats)); }; const startTime = Date.now(); this.running = true; /** * Processes the provided err. * @param {Error | null} err error * @param {Compilation=} _compilation compilation * @returns {void} */ const onCompiled = (err, _compilation) => { if (err) return finalCallback(err); const compilation = /** @type {Compilation} */ (_compilation); if (this.hooks.shouldEmit.call(compilation) === false) { compilation.startTime = startTime; compilation.endTime = Date.now(); const stats = new Stats(compilation); this.hooks.done.callAsync(stats, (err) => { if (err) return finalCallback(err); return finalCallback(null, stats); }); return; } process.nextTick(() => { logger = compilation.getLogger("webpack.Compiler"); logger.time("emitAssets"); this.emitAssets(compilation, (err) => { /** @type {Logger} */ (logger).timeEnd("emitAssets"); if (err) return finalCallback(err); if (compilation.hooks.needAdditionalPass.call()) { compilation.needAdditionalPass = true; compilation.startTime = startTime; compilation.endTime = Date.now(); /** @type {Logger} */ (logger).time("done hook"); const stats = new Stats(compilation); this.hooks.done.callAsync(stats, (err) => { /** @type {Logger} */ (logger).timeEnd("done hook"); if (err) return finalCallback(err); this.hooks.additionalPass.callAsync((err) => { if (err) return finalCallback(err); this.compile(onCompiled); }); }); return; } /** @type {Logger} */ (logger).time("emitRecords"); this.emitRecords((err) => { /** @type {Logger} */ (logger).timeEnd("emitRecords"); if (err) return finalCallback(err); compilation.startTime = startTime; compilation.endTime = Date.now(); /** @type {Logger} */ (logger).time("done hook"); const stats = new Stats(compilation); this.hooks.done.callAsync(stats, (err) => { /** @type {Logger} */ (logger).timeEnd("done hook"); if (err) return finalCallback(err); this.cache.storeBuildDependencies( compilation.buildDependencies, compilation.optionalBuildDependencies, (err) => { if (err) return finalCallback(err); return finalCallback(null, stats); } ); }); }); }); }); }; const run = () => { this.hooks.beforeRun.callAsync(this, (err) => { if (err) return finalCallback(err); this.hooks.run.callAsync(this, (err) => { if (err) return finalCallback(err); this.readRecords((err) => { if (err) return finalCallback(err); this.compile(onCompiled); }); }); }); }; if (this.idle) { this.cache.endIdle((err) => { if (err) return finalCallback(err); this.idle = false; run(); }); } else { run(); } } /** * Processes the provided run as child callback. * @param {RunAsChildCallback} callback signals when the call finishes * @returns {void} */ runAsChild(callback) { const startTime = Date.now(); /** * Processes the provided err. * @param {Error | null} err error * @param {Chunk[]=} entries entries * @param {Compilation=} compilation compilation */ const finalCallback = (err, entries, compilation) => { try { callback(err, entries, compilation); } catch (runAsChildErr) { const err = new WebpackError( `compiler.runAsChild callback error: ${runAsChildErr}`, { cause: runAsChildErr } ); err.details = /** @type {Error} */ (runAsChildErr).stack; /** @type {Compilation} */ (this.parentCompilation).errors.push(err); } }; this.compile((err, _compilation) => { if (err) return finalCallback(err); const compilation = /** @type {Compilation} */ (_compilation); const parentCompilation = /** @type {Compilation} */ ( this.parentCompilation ); parentCompilation.children.push(compilation); for (const { name, source, info } of compilation.getAssets()) { parentCompilation.emitAsset(name, source, info); } /** @type {Chunk[]} */ const entries = []; for (const ep of compilation.entrypoints.values()) { entries.push(...ep.chunks); } compilation.startTime = startTime; compilation.endTime = Date.now(); return finalCallback(null, entries, compilation); }); } purgeInputFileSystem() { if (this.inputFileSystem && this.inputFileSystem.purge) { this.inputFileSystem.purge(); } } /** * Processes the provided compilation. * @param {Compilation} compilation the compilation * @param {ErrorCallback} callback signals when the assets are emitted * @returns {void} */ emitAssets(compilation, callback) { /** @type {string} */ let outputPath; /** * Processes the provided err. * @param {Error=} err error * @returns {void} */ const emitFiles = (err) => { if (err) return callback(err); const assets = compilation.getAssets(); compilation.assets = { ...compilation.assets }; /** @type {Map<string, SimilarEntry>} */ const caseInsensitiveMap = new Map(); /** @type {Set<string>} */ const allTargetPaths = new Set(); asyncLib.eachLimit( assets, 15, ({ name: file, source, info }, callback) => { let targetFile = file; let immutable = info.immutable; const queryOrHashStringIdx = targetFile.search(/[?#]/); if (queryOrHashStringIdx >= 0) { targetFile = targetFile.slice(0, queryOrHashStringIdx); // We may remove the hash, which is in the query string // So we recheck if the file is immutable // This doesn't cover all cases, but immutable is only a performance optimization anyway immutable = immutable && (includesHash(targetFile, info.contenthash) || includesHash(targetFile, info.chunkhash) || includesHash(targetFile, info.modulehash) || includesHash(targetFile, info.fullhash)); } const fs = /** @type {OutputFileSystem} */ (this.outputFileSystem); // A Windows drive-absolute targetFile is written as-is; joining it onto // outputPath would produce an invalid path (e.g. C:\out\D:\file). A // leading "/" stays relative to outputPath (e.g. entry name "/dir/x"). const targetPath = WINDOWS_ABS_PATH_REGEXP.test(targetFile) ? targetFile : join(fs, outputPath, targetFile); /** * Processes the provided err. * @param {Error=} err error * @returns {void} */ const writeOut = (err) => { if (err) return callback(err); allTargetPaths.add(targetPath); // a link is created rather than written, and none of the content // caching below applies to one if (info.symlink) { return this._emitSymlink( compilation, { file, source, outputPath, targetPath }, info.symlink, callback ); } // check if the target file has already been written by this Compiler const targetFileGeneration = this._assetEmittingWrittenFiles.get(targetPath); // create an cache entry for this Source if not already existing let cacheEntry = this._assetEmittingSourceCache.get(source); if (cacheEntry === undefined) { cacheEntry = { sizeOnlySource: undefined, /** @type {CacheEntry["writtenTo"]} */ writtenTo: new Map() }; this._assetEmittingSourceCache.set(source, cacheEntry); } /** @type {SimilarEntry | undefined} */ let similarEntry; const checkSimilarFile = () => { const caseInsensitiveTargetPath = targetPath.toLowerCase(); similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath); if (similarEntry !== undefined) { const { path: other, source: otherSource } = similarEntry; if (isSourceEqual(otherSource, source)) { // Size may or may not be available at this point. // If it's not available add to "waiting" list and it will be updated once available if (similarEntry.size !== undefined) { updateWithReplacementSource(similarEntry.size); } else { if (!similarEntry.waiting) similarEntry.waiting = []; similarEntry.waiting.push({ file, cacheEntry }); } alreadyWritten(); } else { const err = new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file. This will lead to a race-condition and corrupted files on case-insensitive file systems. ${targetPath} ${other}`); err.file = file; callback(err); } return true; } caseInsensitiveMap.set( caseInsensitiveTargetPath, (similarEntry = /** @type {SimilarEntry} */ ({ path: targetPath, source, size: undefined, waiting: undefined })) ); return false; }; /** * get the binary (Buffer) content from the Source * @returns {Buffer} content for the source */ const getContent = () => { if (typeof source.buffer === "function") { return source.buffer(); } const bufferOrString = source.source(); if (Buffer.isBuffer(bufferOrString)) { return bufferOrString; } return Buffer.from(bufferOrString, "utf8"); }; const alreadyWritten = () => { // cache the information that the Source has been already been written to that location if (targetFileGeneration === undefined) { const newGeneration = 1; this._assetEmittingWrittenFiles.set(targetPath, newGeneration); cacheEntry.writtenTo.set(targetPath, newGeneration); } else { cacheEntry.writtenTo.set(targetPath, targetFileGeneration); } callback(); }; /** * Write the file to output file system * @param {Buffer} content content to be written * @returns {void} */ const doWrite = (content) => { /** @type {OutputFileSystem} */ (this.outputFileSystem).writeFile(targetPath, content, (err) => { if (err) return callback(err); // set on what was just written, so a file the comparison above // left alone keeps what it already carries this._setAssetFileAttributes(targetPath, info, (err) => { if (err) return callback(err); // information marker that the asset has been emitted compilation.emittedAssets.add(file); // cache the information that the Source has been written to that location const newGeneration = targetFileGeneration === undefined ? 1 : targetFileGeneration + 1; cacheEntry.writtenTo.set(targetPath, newGeneration); this._assetEmittingWrittenFiles.set( targetPath, newGeneration ); this.hooks.assetEmitted.callAsync( file, { content, source, outputPath, compilation, targetPath }, callback ); }); }); }; /** * Updates with replacement source. * @param {number} size size */ const updateWithReplacementSource = (size) => { updateFileWithReplacementSource(file, cacheEntry, size); /** @type {SimilarEntry} */ (similarEntry).size = size; if ( /** @type {SimilarEntry} */ (similarEntry).waiting !== undefined ) { for (const { file, cacheEntry } of /** @type {SimilarEntry} */ ( similarEntry ).waiting) { updateFileWithReplacementSource(file, cacheEntry, size); } } }; /** * Updates file with replacement source. * @param {string} file file * @param {CacheEntry} cacheEntry cache entry |
| You are visitor 01402809 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |