diff --git a/declarations/LoaderContext.d.ts b/declarations/LoaderContext.d.ts index 46db6d268a5..5e740a2f697 100644 --- a/declarations/LoaderContext.d.ts +++ b/declarations/LoaderContext.d.ts @@ -41,7 +41,7 @@ export interface NormalModuleLoaderContext { utils: { absolutify: (context: string, request: string) => string; contextify: (context: string, request: string) => string; - createHash: (algorithm?: string) => Hash; + createHash: (algorithm?: string | typeof Hash) => Hash; }; rootContext: string; fs: InputFileSystem; diff --git a/lib/ContextModule.js b/lib/ContextModule.js index d39f8f88098..1bcf0099319 100644 --- a/lib/ContextModule.js +++ b/lib/ContextModule.js @@ -38,6 +38,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ @@ -144,7 +145,7 @@ class ContextModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/CssModule.js b/lib/CssModule.js index 39f9d7b5a01..53a9129a2e2 100644 --- a/lib/CssModule.js +++ b/lib/CssModule.js @@ -151,9 +151,6 @@ class CssModule extends NormalModule { return obj; } - /** - * @param {ObjectDeserializerContext} context context - */ deserialize(context) { const { read } = context; this.cssLayer = read(); diff --git a/lib/DelegatedModule.js b/lib/DelegatedModule.js index f75b66cd0f3..9f669db6783 100644 --- a/lib/DelegatedModule.js +++ b/lib/DelegatedModule.js @@ -25,6 +25,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").SourceContext} SourceContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ @@ -66,7 +67,7 @@ class DelegatedModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/DllModule.js b/lib/DllModule.js index a46b5e38b18..baa0a995940 100644 --- a/lib/DllModule.js +++ b/lib/DllModule.js @@ -22,6 +22,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").SourceContext} SourceContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ @@ -52,7 +53,7 @@ class DllModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/ExternalModule.js b/lib/ExternalModule.js index a8fb263bf0c..6e5f8f9a475 100644 --- a/lib/ExternalModule.js +++ b/lib/ExternalModule.js @@ -34,6 +34,7 @@ const { register } = require("./util/serialization"); /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ @@ -415,7 +416,7 @@ class ExternalModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return this.externalType === "css-import" ? CSS_TYPES : TYPES; diff --git a/lib/Module.js b/lib/Module.js index 5f05a848545..1f61baa3df2 100644 --- a/lib/Module.js +++ b/lib/Module.js @@ -21,12 +21,14 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./ChunkGroup")} ChunkGroup */ /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ /** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ /** @typedef {import("./ConcatenationScope")} ConcatenationScope */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */ /** @typedef {import("./FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */ /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ /** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ @@ -100,6 +102,21 @@ const makeSerializable = require("./util/makeSerializable"); * @property {boolean=} sideEffectFree */ +/** + * @typedef {Object} KnownBuildInfo + * @property {boolean=} cacheable + * @property {boolean=} parsed + * @property {LazySet=} fileDependencies + * @property {LazySet=} contextDependencies + * @property {LazySet=} missingDependencies + * @property {LazySet=} buildDependencies + * @property {(Map>)=} valueDependencies + * @property {TODO=} hash + * @property {Record=} assets + * @property {Map=} assetsInfo + * @property {(Snapshot | null)=} snapshot + */ + /** * @typedef {Object} NeedBuildContext * @property {Compilation} compilation @@ -108,13 +125,17 @@ const makeSerializable = require("./util/makeSerializable"); */ /** @typedef {KnownBuildMeta & Record} BuildMeta */ -/** @typedef {Record} BuildInfo */ +/** @typedef {KnownBuildInfo & Record} BuildInfo */ /** * @typedef {Object} FactoryMeta * @property {boolean=} sideEffectFree */ +/** @typedef {Set} SourceTypes */ + +/** @typedef {{ factoryMeta: FactoryMeta | undefined, resolveOptions: ResolveOptions | undefined }} UnsafeCacheData */ + const EMPTY_RESOLVE_OPTIONS = {}; let debugId = 1000; @@ -812,7 +833,7 @@ class Module extends DependenciesBlock { /** * @abstract - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { // Better override this method to return the correct types @@ -956,7 +977,7 @@ class Module extends DependenciesBlock { /** * Module should be unsafe cached. Get data that's needed for that. * This data will be passed to restoreFromUnsafeCache later. - * @returns {object} cached data + * @returns {UnsafeCacheData} cached data */ getUnsafeCacheData() { return { diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js index 80468380171..fd01bd8c1c8 100644 --- a/lib/MultiCompiler.js +++ b/lib/MultiCompiler.js @@ -19,6 +19,7 @@ const ArrayQueue = require("./util/ArrayQueue"); /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Stats")} Stats */ /** @typedef {import("./Watching")} Watching */ +/** @typedef {import("./logging/Logger").Logger} Logger */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ @@ -80,7 +81,7 @@ module.exports = class MultiCompiler { this.dependencies = new WeakMap(); this.running = false; - /** @type {Stats[]} */ + /** @type {(Stats | null)[]} */ const compilerStats = this.compilers.map(() => null); let doneCompilers = 0; for (let index = 0; index < this.compilers.length; index++) { @@ -94,7 +95,9 @@ module.exports = class MultiCompiler { } compilerStats[compilerIndex] = stats; if (doneCompilers === this.compilers.length) { - this.hooks.done.call(new MultiStats(compilerStats)); + this.hooks.done.call( + new MultiStats(/** @type {Stats[]} */ (compilerStats)) + ); } }); compiler.hooks.invalid.tap("MultiCompiler", () => { @@ -180,6 +183,10 @@ module.exports = class MultiCompiler { } } + /** + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ getInfrastructureLogger(name) { return this.compilers[0].getInfrastructureLogger(name); } @@ -202,6 +209,10 @@ module.exports = class MultiCompiler { const edges = new Set(); /** @type {string[]} */ const missing = []; + /** + * @param {Compiler} compiler compiler + * @returns {boolean} target was found + */ const targetFound = compiler => { for (const edge of edges) { if (edge.target === compiler) { @@ -274,6 +285,10 @@ module.exports = class MultiCompiler { runWithDependencies(compilers, fn, callback) { const fulfilledNames = new Set(); let remainingCompilers = compilers; + /** + * @param {string} d dependency + * @returns {boolean} when dependency was fulfilled + */ const isDependencyFulfilled = d => fulfilledNames.has(d); const getReadyCompilers = () => { let readyCompilers = []; @@ -291,6 +306,10 @@ module.exports = class MultiCompiler { } return readyCompilers; }; + /** + * @param {Callback} callback callback + * @returns {void} + */ const runCompilers = callback => { if (remainingCompilers.length === 0) return callback(); asyncLib.map( @@ -302,7 +321,7 @@ module.exports = class MultiCompiler { runCompilers(callback); }); }, - callback + /** @type {Callback} */ (callback) ); }; runCompilers(callback); @@ -316,7 +335,7 @@ module.exports = class MultiCompiler { * @returns {SetupResult[]} result of setup */ _runGraph(setup, run, callback) { - /** @typedef {{ compiler: Compiler, setupResult: SetupResult, result: Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ + /** @typedef {{ compiler: Compiler, setupResult: undefined | SetupResult, result: undefined | Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ // State transitions for nodes: // -> blocked (initial) @@ -341,12 +360,14 @@ module.exports = class MultiCompiler { })); /** @type {Map} */ const compilerToNode = new Map(); - for (const node of nodes) compilerToNode.set(node.compiler.name, node); + for (const node of nodes) { + compilerToNode.set(/** @type {string} */ (node.compiler.name), node); + } for (const node of nodes) { const dependencies = this.dependencies.get(node.compiler); if (!dependencies) continue; for (const dep of dependencies) { - const parent = compilerToNode.get(dep); + const parent = /** @type {Node} */ (compilerToNode.get(dep)); node.parents.push(parent); parent.children.push(node); } @@ -361,10 +382,10 @@ module.exports = class MultiCompiler { } let errored = false; let running = 0; - const parallelism = this._options.parallelism; + const parallelism = /** @type {number} */ (this._options.parallelism); /** * @param {Node} node node - * @param {Error=} err error + * @param {(Error | null)=} err error * @param {Stats=} stats result * @returns {void} */ @@ -440,6 +461,7 @@ module.exports = class MultiCompiler { } }; + /** @type {SetupResult[]} */ const setupResults = []; nodes.forEach((node, i) => { setupResults.push( @@ -461,7 +483,7 @@ module.exports = class MultiCompiler { }; const processQueueWorker = () => { while (running < parallelism && queue.length > 0 && !errored) { - const node = queue.dequeue(); + const node = /** @type {Node} */ (queue.dequeue()); if ( node.state === "queued" || (node.state === "blocked" && @@ -469,7 +491,11 @@ module.exports = class MultiCompiler { ) { running++; node.state = "starting"; - run(node.compiler, node.setupResult, nodeDone.bind(null, node)); + run( + node.compiler, + /** @type {SetupResult} */ (node.setupResult), + nodeDone.bind(null, node) + ); node.state = "running"; } } diff --git a/lib/NormalModule.js b/lib/NormalModule.js index fa0cc1fac1f..f7fce88149e 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -49,7 +49,6 @@ const makeSerializable = require("./util/makeSerializable"); const memoize = require("./util/memoize"); /** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */ /** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ @@ -58,17 +57,23 @@ const memoize = require("./util/memoize"); /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./Generator")} Generator */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ /** @typedef {import("./ModuleTypeConstants").JavaScriptModuleTypes} JavaScriptModuleTypes */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ /** @typedef {import("./Parser")} Parser */ /** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("./logging/Logger").Logger} WebpackLogger */ @@ -78,6 +83,11 @@ const memoize = require("./util/memoize"); /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {{[k: string]: any}} ParserOptions */ +/** @typedef {{[k: string]: any}} GeneratorOptions */ + +/** @typedef {UnsafeCacheData & { parser: undefined | Parser, parserOptions: undefined | ParserOptions, generator: undefined | Generator, generatorOptions: undefined | GeneratorOptions }} NormalModuleUnsafeCacheData */ + /** * @typedef {Object} SourceMap * @property {number} version @@ -212,9 +222,9 @@ makeSerializable( * @property {string} context context directory for resolving * @property {string=} matchResource path + query of the matched resource (virtual) * @property {Parser} parser the parser used - * @property {Record=} parserOptions the options of the parser used + * @property {ParserOptions=} parserOptions the options of the parser used * @property {Generator} generator the generator used - * @property {Record=} generatorOptions the options of the generator used + * @property {GeneratorOptions=} generatorOptions the options of the generator used * @property {ResolveOptions=} resolveOptions options used for resolving requests from this module */ @@ -264,9 +274,12 @@ class NormalModule extends Module { ), needBuild: new AsyncSeriesBailHook(["module", "context"]) }; - compilationHooksMap.set(compilation, hooks); + compilationHooksMap.set( + compilation, + /** @type {NormalModuleCompilationHooks} */ (hooks) + ); } - return hooks; + return /** @type {NormalModuleCompilationHooks} */ (hooks); } /** @@ -300,11 +313,13 @@ class NormalModule extends Module { this.rawRequest = rawRequest; /** @type {boolean} */ this.binary = /^(asset|webassembly)\b/.test(type); - /** @type {Parser} */ + /** @type {undefined | Parser} */ this.parser = parser; + /** @type {undefined | ParserOptions} */ this.parserOptions = parserOptions; - /** @type {Generator} */ + /** @type {undefined | Generator} */ this.generator = generator; + /** @type {undefined | GeneratorOptions} */ this.generatorOptions = generatorOptions; /** @type {string} */ this.resource = resource; @@ -319,13 +334,22 @@ class NormalModule extends Module { } // Info from Build - /** @type {(WebpackError | null)=} */ + /** @type {WebpackError | null} */ this.error = null; - /** @private @type {Source=} */ + /** + * @private + * @type {Source | null} + */ this._source = null; - /** @private @type {Map | undefined} **/ + /** + * @private + * @type {Map | undefined} + **/ this._sourceSizes = undefined; - /** @private @type {Set} */ + /** + * @private + * @type {undefined | SourceTypes} + **/ this._sourceTypes = undefined; // Cache @@ -419,7 +443,7 @@ class NormalModule extends Module { // TODO reconsider this for webpack 6 if (this.buildInfo) { if (this._sourceTypes === undefined) this.getSourceTypes(); - for (const type of this._sourceTypes) { + for (const type of /** @type {SourceTypes} */ (this._sourceTypes)) { this.size(type); } } @@ -433,15 +457,22 @@ class NormalModule extends Module { /** * Module should be unsafe cached. Get data that's needed for that. * This data will be passed to restoreFromUnsafeCache later. - * @returns {object} cached data + * @returns {UnsafeCacheData} cached data */ getUnsafeCacheData() { - const data = super.getUnsafeCacheData(); + const data = + /** @type {NormalModuleUnsafeCacheData} */ + (super.getUnsafeCacheData()); data.parserOptions = this.parserOptions; data.generatorOptions = this.generatorOptions; return data; } + /** + * restore unsafe cache data + * @param {NormalModuleUnsafeCacheData} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); } @@ -466,8 +497,8 @@ class NormalModule extends Module { /** * @param {string} context the compilation context * @param {string} name the asset name - * @param {string} content the content - * @param {string | TODO} sourceMap an optional source map + * @param {string | Buffer} content the content + * @param {(string | SourceMap)=} sourceMap an optional source map * @param {Object=} associatedObjectForCache object for caching * @returns {Source} the created source */ @@ -493,7 +524,11 @@ class NormalModule extends Module { return new SourceMapSource( content, name, - contextifySourceMap(context, sourceMap, associatedObjectForCache) + contextifySourceMap( + context, + /** @type {SourceMap} */ (sourceMap), + associatedObjectForCache + ) ); } } @@ -502,12 +537,14 @@ class NormalModule extends Module { } /** + * @private + * @template T * @param {ResolverWithOptions} resolver a resolver * @param {WebpackOptions} options webpack options * @param {Compilation} compilation the compilation * @param {InputFileSystem} fs file system from reading * @param {NormalModuleCompilationHooks} hooks the hooks - * @returns {NormalModuleLoaderContext} loader context + * @returns {import("../declarations/LoaderContext").NormalModuleLoaderContext} loader context */ _createLoaderContext(resolver, options, compilation, fs, hooks) { const { requestShortener } = compilation.runtimeTemplate; @@ -516,16 +553,19 @@ class NormalModule extends Module { if (!currentLoader) return "(not in loader scope)"; return requestShortener.shorten(currentLoader.loader); }; + /** + * @returns {ResolveContext} resolve context + */ const getResolveContext = () => { return { fileDependencies: { - add: d => loaderContext.addDependency(d) + add: d => /** @type {TODO} */ (loaderContext).addDependency(d) }, contextDependencies: { - add: d => loaderContext.addContextDependency(d) + add: d => /** @type {TODO} */ (loaderContext).addContextDependency(d) }, missingDependencies: { - add: d => loaderContext.addMissingDependency(d) + add: d => /** @type {TODO} */ (loaderContext).addMissingDependency(d) } }; }; @@ -542,26 +582,41 @@ class NormalModule extends Module { contextify.bindContextCache(this.context, compilation.compiler.root) ); const utils = { + /** + * @param {string} context context + * @param {string} request request + * @returns {string} result + */ absolutify: (context, request) => { return context === this.context ? getAbsolutifyInContext()(request) : getAbsolutify()(context, request); }, + /** + * @param {string} context context + * @param {string} request request + * @returns {string} result + */ contextify: (context, request) => { return context === this.context ? getContextifyInContext()(request) : getContextify()(context, request); }, + /** + * @param {(string | typeof import("./util/Hash"))=} type type + * @returns {Hash} hash + */ createHash: type => { return createHash(type || compilation.outputOptions.hashFunction); } }; + /** @type {import("../declarations/LoaderContext").NormalModuleLoaderContext} */ const loaderContext = { version: 2, getOptions: schema => { const loader = this.getCurrentLoader(loaderContext); - let { options } = loader; + let { options } = /** @type {LoaderItem} */ (loader); if (typeof options === "string") { if (options.startsWith("{") && options.endsWith("}")) { @@ -649,27 +704,39 @@ class NormalModule extends Module { }; }, emitFile: (name, content, sourceMap, assetInfo) => { - if (!this.buildInfo.assets) { - this.buildInfo.assets = Object.create(null); - this.buildInfo.assetsInfo = new Map(); + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + if (!buildInfo.assets) { + buildInfo.assets = Object.create(null); + buildInfo.assetsInfo = new Map(); } - this.buildInfo.assets[name] = this.createSourceForAsset( - options.context, + + const assets = + /** @type {NonNullable} */ + (buildInfo.assets); + const assetsInfo = + /** @type {NonNullable} */ + (buildInfo.assetsInfo); + + assets[name] = this.createSourceForAsset( + /** @type {string} */ (options.context), name, content, sourceMap, compilation.compiler.root ); - this.buildInfo.assetsInfo.set(name, assetInfo); + assetsInfo.set(name, assetInfo); }, addBuildDependency: dep => { - if (this.buildInfo.buildDependencies === undefined) { - this.buildInfo.buildDependencies = new LazySet(); + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + if (buildInfo.buildDependencies === undefined) { + buildInfo.buildDependencies = new LazySet(); } - this.buildInfo.buildDependencies.add(dep); + buildInfo.buildDependencies.add(dep); }, utils, - rootContext: options.context, + rootContext: /** @type {string} */ (options.context), webpack: true, sourceMap: !!this.useSourceMap, mode: options.mode || "production", @@ -686,6 +753,12 @@ class NormalModule extends Module { return loaderContext; } + // TODO remove `loaderContext` in webpack@6 + /** + * @param {TODO} loaderContext loader context + * @param {number} index index + * @returns {LoaderItem | null} loader + */ getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { if ( this.loaders && @@ -702,7 +775,7 @@ class NormalModule extends Module { /** * @param {string} context the compilation context * @param {string | Buffer} content the content - * @param {string | TODO} sourceMap an optional source map + * @param {(string | SourceMapSource)=} sourceMap an optional source map * @param {Object=} associatedObjectForCache object for caching * @returns {Source} the created source */ @@ -723,7 +796,11 @@ class NormalModule extends Module { return new SourceMapSource( content, contextifySourceUrl(context, identifier, associatedObjectForCache), - contextifySourceMap(context, sourceMap, associatedObjectForCache) + contextifySourceMap( + context, + /** @type {TODO} */ (sourceMap), + associatedObjectForCache + ) ); } @@ -791,7 +868,7 @@ class NormalModule extends Module { } this._source = this.createSource( - options.context, + /** @type {string} */ (options.context), this.binary ? asBuffer(source) : asString(source), sourceMap, compilation.compiler.root @@ -806,10 +883,12 @@ class NormalModule extends Module { return callback(); }; - this.buildInfo.fileDependencies = new LazySet(); - this.buildInfo.contextDependencies = new LazySet(); - this.buildInfo.missingDependencies = new LazySet(); - this.buildInfo.cacheable = true; + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + buildInfo.fileDependencies = new LazySet(); + buildInfo.contextDependencies = new LazySet(); + buildInfo.missingDependencies = new LazySet(); + buildInfo.cacheable = true; try { hooks.beforeLoaders.call(this.loaders, this, loaderContext); @@ -819,7 +898,8 @@ class NormalModule extends Module { } if (this.loaders.length > 0) { - this.buildInfo.buildDependencies = new LazySet(); + /** @type {BuildInfo} */ + (this.buildInfo).buildDependencies = new LazySet(); } runLoaders( @@ -850,19 +930,37 @@ class NormalModule extends Module { undefined; if (!result) { - this.buildInfo.cacheable = false; + /** @type {BuildInfo} */ + (this.buildInfo).cacheable = false; return processResult( err || new Error("No result from loader-runner processing"), null ); } - this.buildInfo.fileDependencies.addAll(result.fileDependencies); - this.buildInfo.contextDependencies.addAll(result.contextDependencies); - this.buildInfo.missingDependencies.addAll(result.missingDependencies); + + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + const fileDependencies = + /** @type {NonNullable} */ + (buildInfo.fileDependencies); + const contextDependencies = + /** @type {NonNullable} */ + (buildInfo.contextDependencies); + const missingDependencies = + /** @type {NonNullable} */ + (buildInfo.missingDependencies); + + fileDependencies.addAll(result.fileDependencies); + contextDependencies.addAll(result.contextDependencies); + missingDependencies.addAll(result.missingDependencies); for (const loader of this.loaders) { - this.buildInfo.buildDependencies.add(loader.loader); + const buildDependencies = + /** @type {NonNullable} */ + (buildInfo.buildDependencies); + + buildDependencies.add(loader.loader); } - this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable; + buildInfo.cacheable = buildInfo.cacheable && result.cacheable; processResult(err, result.result); } ); @@ -879,6 +977,11 @@ class NormalModule extends Module { this.addError(error); } + /** + * @param {TODO} rule rule + * @param {string} content content + * @returns {boolean} result + */ applyNoParseRule(rule, content) { // must start with "rule" if rule is a string if (typeof rule === "string") { @@ -892,9 +995,11 @@ class NormalModule extends Module { return rule.test(content); } - // check if module should not be parsed - // returns "true" if the module should !not! be parsed - // returns "false" if the module !must! be parsed + /** + * @param {TODO} noParseRule no parse rule + * @param {string} request request + * @returns {boolean} check if module should not be parsed, returns "true" if the module should !not! be parsed, returns "false" if the module !must! be parsed + */ shouldPreventParsing(noParseRule, request) { // if no noParseRule exists, return false // the module !must! be parsed. @@ -920,6 +1025,10 @@ class NormalModule extends Module { return false; } + /** + * @param {Compilation} compilation compilation + * @private + */ _initBuildHash(compilation) { const hash = createHash(compilation.outputOptions.hashFunction); if (this._source) { @@ -928,7 +1037,8 @@ class NormalModule extends Module { } hash.update("meta"); hash.update(JSON.stringify(this.buildMeta)); - this.buildInfo.hash = /** @type {string} */ (hash.digest("hex")); + /** @type {BuildInfo} */ + (this.buildInfo).hash = /** @type {string} */ (hash.digest("hex")); } /** @@ -974,10 +1084,18 @@ class NormalModule extends Module { return callback(); } + /** + * @param {Error} e error + * @returns {void} + */ const handleParseError = e => { - const source = this._source.source(); + const source = /** @type {Source} */ (this._source).source(); const loaders = this.loaders.map(item => - contextify(options.context, item.loader, compilation.compiler.root) + contextify( + /** @type {string} */ (options.context), + item.loader, + compilation.compiler.root + ) ); const error = new ModuleParseError(source, e, loaders, this.type); this.markModuleAsErrored(error); @@ -985,7 +1103,7 @@ class NormalModule extends Module { return callback(); }; - const handleParseResult = result => { + const handleParseResult = () => { this.dependencies.sort( concatComparators( compareSelect(a => a.loc, compareLocations), @@ -993,7 +1111,9 @@ class NormalModule extends Module { ) ); this._initBuildHash(compilation); - this._lastSuccessfulBuildMeta = this.buildMeta; + this._lastSuccessfulBuildMeta = + /** @type {BuildMeta} */ + (this.buildMeta); return handleBuildDone(); }; @@ -1006,12 +1126,17 @@ class NormalModule extends Module { } const snapshotOptions = compilation.options.snapshot.module; - if (!this.buildInfo.cacheable || !snapshotOptions) { + const { cacheable } = /** @type {BuildInfo} */ (this.buildInfo); + if (!cacheable || !snapshotOptions) { return callback(); } // add warning for all non-absolute paths in fileDependencies, etc // This makes it easier to find problems with watching and/or caching + /** @type {undefined | Set} */ let nonAbsoluteDependencies = undefined; + /** + * @param {LazySet} deps deps + */ const checkDependencies = deps => { for (const dep of deps) { if (!ABSOLUTE_PATH_REGEX.test(dep)) { @@ -1028,7 +1153,11 @@ class NormalModule extends Module { ); if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { (depWithoutGlob !== dep - ? this.buildInfo.contextDependencies + ? /** @type {NonNullable} */ + ( + /** @type {BuildInfo} */ (this.buildInfo) + .contextDependencies + ) : deps ).add(absolute); } @@ -1038,9 +1167,19 @@ class NormalModule extends Module { } } }; - checkDependencies(this.buildInfo.fileDependencies); - checkDependencies(this.buildInfo.missingDependencies); - checkDependencies(this.buildInfo.contextDependencies); + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + const fileDependencies = + /** @type {NonNullable} */ + (buildInfo.fileDependencies); + const contextDependencies = + /** @type {NonNullable} */ + (buildInfo.contextDependencies); + const missingDependencies = + /** @type {NonNullable} */ + (buildInfo.missingDependencies); + checkDependencies(fileDependencies); + checkDependencies(missingDependencies); + checkDependencies(contextDependencies); if (nonAbsoluteDependencies !== undefined) { const InvalidDependenciesModuleWarning = getInvalidDependenciesModuleWarning(); @@ -1051,19 +1190,19 @@ class NormalModule extends Module { // convert file/context/missingDependencies into filesystem snapshot compilation.fileSystemInfo.createSnapshot( startTime, - this.buildInfo.fileDependencies, - this.buildInfo.contextDependencies, - this.buildInfo.missingDependencies, + fileDependencies, + contextDependencies, + missingDependencies, snapshotOptions, (err, snapshot) => { if (err) { this.markModuleAsErrored(err); return; } - this.buildInfo.fileDependencies = undefined; - this.buildInfo.contextDependencies = undefined; - this.buildInfo.missingDependencies = undefined; - this.buildInfo.snapshot = snapshot; + buildInfo.fileDependencies = undefined; + buildInfo.contextDependencies = undefined; + buildInfo.missingDependencies = undefined; + buildInfo.snapshot = snapshot; return callback(); } ); @@ -1082,15 +1221,16 @@ class NormalModule extends Module { const noParseRule = options.module && options.module.noParse; if (this.shouldPreventParsing(noParseRule, this.request)) { // We assume that we need module and exports - this.buildInfo.parsed = false; + /** @type {BuildInfo} */ + (this.buildInfo).parsed = false; this._initBuildHash(compilation); return handleBuildDone(); } - let result; try { - const source = this._source.source(); - result = this.parser.parse(this._ast || source, { + const source = /** @type {Source} */ (this._source).source(); + /** @type {Parser} */ + (this.parser).parse(this._ast || source, { source, current: this, module: this, @@ -1098,10 +1238,10 @@ class NormalModule extends Module { options: options }); } catch (e) { - handleParseError(e); + handleParseError(/** @type {Error} */ (e)); return; } - handleParseResult(result); + handleParseResult(); }); } @@ -1110,7 +1250,9 @@ class NormalModule extends Module { * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated */ getConcatenationBailoutReason(context) { - return this.generator.getConcatenationBailoutReason(this, context); + return /** @type {Generator} */ ( + this.generator + ).getConcatenationBailoutReason(this, context); } /** @@ -1162,11 +1304,13 @@ class NormalModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { if (this._sourceTypes === undefined) { - this._sourceTypes = this.generator.getTypes(this); + this._sourceTypes = /** @type {Generator} */ (this.generator).getTypes( + this + ); } return this._sourceTypes; } @@ -1189,7 +1333,9 @@ class NormalModule extends Module { /** @type {Set} */ const runtimeRequirements = new Set(); - if (!this.buildInfo.parsed) { + const { parsed } = /** @type {BuildInfo} */ (this.buildInfo); + + if (!parsed) { runtimeRequirements.add(RuntimeGlobals.module); runtimeRequirements.add(RuntimeGlobals.exports); runtimeRequirements.add(RuntimeGlobals.thisAsExports); @@ -1261,15 +1407,16 @@ class NormalModule extends Module { // always try to build in case of an error if (this.error) return callback(null, true); + const { cacheable, snapshot, valueDependencies } = + /** @type {BuildInfo} */ (this.buildInfo); + // always build when module is not cacheable - if (!this.buildInfo.cacheable) return callback(null, true); + if (!cacheable) return callback(null, true); // build when there is no snapshot to check - if (!this.buildInfo.snapshot) return callback(null, true); + if (!snapshot) return callback(null, true); // build when valueDependencies have changed - /** @type {Map>} */ - const valueDependencies = this.buildInfo.valueDependencies; if (valueDependencies) { if (!valueCacheVersions) return callback(null, true); for (const [key, value] of valueDependencies) { @@ -1288,7 +1435,7 @@ class NormalModule extends Module { } // check snapshot for validity - fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { + fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => { if (err) return callback(err); if (!valid) return callback(null, true); const hooks = NormalModule.getCompilationHooks(compilation); @@ -1316,7 +1463,10 @@ class NormalModule extends Module { if (cachedSize !== undefined) { return cachedSize; } - const size = Math.max(1, this.generator.getSize(this, type)); + const size = Math.max( + 1, + /** @type {Generator} */ (this.generator).getSize(this, type) + ); if (this._sourceSizes === undefined) { this._sourceSizes = new Map(); } @@ -1336,7 +1486,8 @@ class NormalModule extends Module { missingDependencies, buildDependencies ) { - const { snapshot, buildDependencies: buildDeps } = this.buildInfo; + const { snapshot, buildDependencies: buildDeps } = + /** @type {BuildInfo} */ (this.buildInfo); if (snapshot) { fileDependencies.addAll(snapshot.getFileIterable()); contextDependencies.addAll(snapshot.getContextIterable()); @@ -1346,7 +1497,7 @@ class NormalModule extends Module { fileDependencies: fileDeps, contextDependencies: contextDeps, missingDependencies: missingDeps - } = this.buildInfo; + } = /** @type {BuildInfo} */ (this.buildInfo); if (fileDeps !== undefined) fileDependencies.addAll(fileDeps); if (contextDeps !== undefined) contextDependencies.addAll(contextDeps); if (missingDeps !== undefined) missingDependencies.addAll(missingDeps); @@ -1362,7 +1513,7 @@ class NormalModule extends Module { * @returns {void} */ updateHash(hash, context) { - hash.update(this.buildInfo.hash); + hash.update(/** @type {BuildInfo} */ (this.buildInfo).hash); this.generator.updateHash(hash, { module: this, ...context diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index 9b28c778c38..ce377134eb7 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -38,10 +38,17 @@ const { /** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ /** @typedef {import("./Generator")} Generator */ /** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ /** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./NormalModule").GeneratorOptions} GeneratorOptions */ +/** @typedef {import("./NormalModule").LoaderItem} LoaderItem */ /** @typedef {import("./NormalModule").NormalModuleCreateData} NormalModuleCreateData */ +/** @typedef {import("./NormalModule").ParserOptions} ParserOptions */ /** @typedef {import("./Parser")} Parser */ /** @typedef {import("./ResolverFactory")} ResolverFactory */ +/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */ +/** @typedef {import("./ResolverFactory").ResolveRequest} ResolveRequest */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ @@ -67,27 +74,43 @@ const { /** * @typedef {Object} ResourceData * @property {string} resource - * @property {string} path - * @property {string} query - * @property {string} fragment + * @property {string=} path + * @property {string=} query + * @property {string=} fragment * @property {string=} context */ /** @typedef {ResourceData & { data: Record }} ResourceDataWithData */ -/** @typedef {Object} ParsedLoaderRequest +/** + * @typedef {Object} ParsedLoaderRequest * @property {string} loader loader * @property {string|undefined} options options */ +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} stats + * @returns {void} + */ + const EMPTY_RESOLVE_OPTIONS = {}; +/** @type {ParserOptions} */ const EMPTY_PARSER_OPTIONS = {}; +/** @type {GeneratorOptions} */ const EMPTY_GENERATOR_OPTIONS = {}; +/** @type {ParsedLoaderRequest[]} */ const EMPTY_ELEMENTS = []; const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; const LEADING_DOT_EXTENSION_REGEX = /^[^.]/; +/** + * @param {LoaderItem} data data + * @returns {string} ident + */ const loaderToIdent = data => { if (!data.options) { return data.loader; @@ -104,6 +127,11 @@ const loaderToIdent = data => { return data.loader + "?" + JSON.stringify(data.options); }; +/** + * @param {LoaderItem[]} loaders loaders + * @param {string} resource resource + * @returns {string} stringified loaders and resource + */ const stringifyLoadersAndResource = (loaders, resource) => { let str = ""; for (const loader of loaders) { @@ -112,6 +140,11 @@ const stringifyLoadersAndResource = (loaders, resource) => { return str + resource; }; +/** + * @param {number} times times + * @param {(err?: null | Error) => void} callback callback + * @returns {(err?: null | Error) => void} callback + */ const needCalls = (times, callback) => { return err => { if (--times === 0) { @@ -124,6 +157,14 @@ const needCalls = (times, callback) => { }; }; +/** + * @template T + * @template O + * @param {T} globalOptions global options + * @param {string} type type + * @param {O} localOptions local options + * @returns {T & O | T | O} result + */ const mergeGlobalOptions = (globalOptions, type, localOptions) => { const parts = type.split("/"); let result; @@ -147,11 +188,22 @@ const mergeGlobalOptions = (globalOptions, type, localOptions) => { }; // TODO webpack 6 remove +/** + * @param {string} name name + * @param {TODO} hook hook + * @returns {string} result + */ const deprecationChangedHookMessage = (name, hook) => { const names = hook.taps - .map(tapped => { - return tapped.name; - }) + .map( + /** + * @param {TODO} tapped tapped + * @returns {string} name + */ + tapped => { + return tapped.name; + } + ) .join(", "); return ( @@ -226,14 +278,19 @@ class NormalModuleFactory extends ModuleFactory { createModule: new AsyncSeriesBailHook(["createData", "resolveData"]), /** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData], Module>} */ module: new SyncWaterfallHook(["module", "createData", "resolveData"]), + /** @type {HookMap>} */ createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + /** @type {HookMap>} */ parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + /** @type {HookMap>} */ createGenerator: new HookMap( () => new SyncBailHook(["generatorOptions"]) ), + /** @type {HookMap>} */ generator: new HookMap( () => new SyncHook(["generator", "generatorOptions"]) ), + /** @type {HookMap>} */ createModuleClass: new HookMap( () => new SyncBailHook(["createData", "resolveData"]) ) @@ -251,7 +308,7 @@ class NormalModuleFactory extends ModuleFactory { this.fs = fs; this._globalParserOptions = options.parser; this._globalGeneratorOptions = options.generator; - /** @type {Map>} */ + /** @type {Map>} */ this.parserCache = new Map(); /** @type {Map>} */ this.generatorCache = new Map(); @@ -313,7 +370,9 @@ class NormalModuleFactory extends ModuleFactory { // TODO webpack 6 make it required and move javascript/wasm/asset properties to own module createdModule = this.hooks.createModuleClass - .for(createData.settings.type) + .for( + /** @type {ModuleSettings} */ (createData.settings).type + ) .call(createData, resolveData); if (!createdModule) { @@ -415,7 +474,7 @@ class NormalModuleFactory extends ModuleFactory { : 0 ) .split(/!+/); - unresolvedResource = rawElements.pop(); + unresolvedResource = /** @type {string} */ (rawElements.pop()); elements = rawElements.map(el => { const { path, query } = cachedParseResourceWithoutFragment(el); return { @@ -433,6 +492,7 @@ class NormalModuleFactory extends ModuleFactory { elements = EMPTY_ELEMENTS; } + /** @type {ResolveContext} */ const resolveContext = { fileDependencies, missingDependencies, @@ -442,6 +502,7 @@ class NormalModuleFactory extends ModuleFactory { /** @type {ResourceDataWithData} */ let resourceData; + /** @type {undefined | LoaderItem[]} */ let loaders; const continueCallback = needCalls(2, err => { @@ -449,7 +510,7 @@ class NormalModuleFactory extends ModuleFactory { // translate option idents try { - for (const item of loaders) { + for (const item of /** @type {LoaderItem[]} */ (loaders)) { if (typeof item.options === "string" && item.options[0] === "?") { const ident = item.options.slice(1); if (ident === "[[missing ident]]") { @@ -469,7 +530,7 @@ class NormalModuleFactory extends ModuleFactory { } } } catch (e) { - return callback(e); + return callback(/** @type {Error} */ (e)); } if (!resourceData) { @@ -481,8 +542,12 @@ class NormalModuleFactory extends ModuleFactory { (matchResourceData !== undefined ? `${matchResourceData.resource}!=!` : "") + - stringifyLoadersAndResource(loaders, resourceData.resource); + stringifyLoadersAndResource( + /** @type {LoaderItem[]} */ (loaders), + resourceData.resource + ); + /** @type {ModuleSettings} */ const settings = {}; const useLoadersPost = []; const useLoaders = []; @@ -553,22 +618,32 @@ class NormalModuleFactory extends ModuleFactory { } } - let postLoaders, normalLoaders, preLoaders; + /** @type {undefined | LoaderItem[]} */ + let postLoaders; + /** @type {undefined | LoaderItem[]} */ + let normalLoaders; + /** @type {undefined | LoaderItem[]} */ + let preLoaders; const continueCallback = needCalls(3, err => { if (err) { return callback(err); } - const allLoaders = postLoaders; + const allLoaders = /** @type {LoaderItem[]} */ (postLoaders); if (matchResourceData === undefined) { - for (const loader of loaders) allLoaders.push(loader); - for (const loader of normalLoaders) allLoaders.push(loader); + for (const loader of /** @type {LoaderItem[]} */ (loaders)) + allLoaders.push(loader); + for (const loader of /** @type {LoaderItem[]} */ (normalLoaders)) + allLoaders.push(loader); } else { - for (const loader of normalLoaders) allLoaders.push(loader); - for (const loader of loaders) allLoaders.push(loader); + for (const loader of /** @type {LoaderItem[]} */ (normalLoaders)) + allLoaders.push(loader); + for (const loader of /** @type {LoaderItem[]} */ (loaders)) + allLoaders.push(loader); } - for (const loader of preLoaders) allLoaders.push(loader); - let type = settings.type; + for (const loader of /** @type {LoaderItem[]} */ (preLoaders)) + allLoaders.push(loader); + let type = /** @type {string} */ (settings.type); const resolveOptions = settings.resolve; const layer = settings.layer; if (layer !== undefined && !layers) { @@ -605,7 +680,7 @@ class NormalModuleFactory extends ModuleFactory { resolveOptions }); } catch (e) { - return callback(e); + return callback(/** @type {Error} */ (e)); } callback(); }); @@ -647,7 +722,7 @@ class NormalModuleFactory extends ModuleFactory { this.resolveRequestArray( contextInfo, contextScheme ? this.context : context, - elements, + /** @type {LoaderItem[]} */ (elements), loaderResolver, resolveContext, (err, result) => { @@ -657,6 +732,9 @@ class NormalModuleFactory extends ModuleFactory { } ); + /** + * @param {string} context context + */ const defaultResolve = context => { if (/^($|\?)/.test(unresolvedResource)) { resourceData = { @@ -835,6 +913,14 @@ class NormalModuleFactory extends ModuleFactory { }); } + /** + * @param {ModuleFactoryCreateDataContextInfo} contextInfo context info + * @param {string} context context + * @param {string} unresolvedResource unresolved resource + * @param {ResolverWithOptions} resolver resolver + * @param {ResolveContext} resolveContext resolver context + * @param {(err: null | Error, res?: string | false, req?: ResolveRequest) => void} callback callback + */ resolveResource( contextInfo, context, @@ -899,6 +985,16 @@ ${hints.join("\n\n")}`; ); } + /** + * @param {Error} error error + * @param {ModuleFactoryCreateDataContextInfo} contextInfo context info + * @param {string} context context + * @param {string} unresolvedResource unresolved resource + * @param {ResolverWithOptions} resolver resolver + * @param {ResolveContext} resolveContext resolver context + * @param {Callback} callback callback + * @private + */ _resolveResourceErrorHints( error, contextInfo, @@ -1010,11 +1106,20 @@ If changing the source code is not an option there is also a resolve options cal ], (err, hints) => { if (err) return callback(err); - callback(null, hints.filter(Boolean)); + callback(null, /** @type {string[]} */ (hints).filter(Boolean)); } ); } + /** + * @param {ModuleFactoryCreateDataContextInfo} contextInfo context info + * @param {string} context context + * @param {LoaderItem[]} array array + * @param {ResolverWithOptions} resolver resolver + * @param {ResolveContext} resolveContext resolve context + * @param {Callback} callback callback + * @returns {void} result + */ resolveRequestArray( contextInfo, context, @@ -1023,6 +1128,7 @@ If changing the source code is not an option there is also a resolve options cal resolveContext, callback ) { + // LoaderItem if (array.length === 0) return callback(null, array); asyncLib.map( array, @@ -1064,10 +1170,11 @@ If changing the source code is not an option there is also a resolve options cal ? "module" : /\.cjs$/i.test(parsedResult.path) ? "commonjs" - : resolveRequest.descriptionFileData === undefined + : /** @type {ResolveRequest} */ + (resolveRequest).descriptionFileData === undefined ? undefined - : resolveRequest.descriptionFileData.type; - + : /** @type {ResolveRequest} */ + (resolveRequest).descriptionFileData.type; const resolved = { loader: parsedResult.path, type, @@ -1077,16 +1184,25 @@ If changing the source code is not an option there is also a resolve options cal ? parsedResult.query.slice(1) : undefined : item.options, - ident: item.options === undefined ? undefined : item.ident + ident: + item.options === undefined + ? undefined + : /** @type {string} */ (item.ident) }; - return callback(null, resolved); + + return callback(null, /** @type {LoaderItem} */ (resolved)); } ); }, - callback + /** @type {Callback} */ (callback) ); } + /** + * @param {string} type type + * @param {ParserOptions} parserOptions parser options + * @returns {Parser} parser + */ getParser(type, parserOptions = EMPTY_PARSER_OPTIONS) { let cache = this.parserCache.get(type); @@ -1107,7 +1223,7 @@ If changing the source code is not an option there is also a resolve options cal /** * @param {string} type type - * @param {{[k: string]: any}} parserOptions parser options + * @param {ParserOptions} parserOptions parser options * @returns {Parser} parser */ createParser(type, parserOptions = {}) { @@ -1124,6 +1240,11 @@ If changing the source code is not an option there is also a resolve options cal return parser; } + /** + * @param {string} type type of generator + * @param {GeneratorOptions} generatorOptions generator options + * @returns {Generator} generator + */ getGenerator(type, generatorOptions = EMPTY_GENERATOR_OPTIONS) { let cache = this.generatorCache.get(type); @@ -1142,6 +1263,11 @@ If changing the source code is not an option there is also a resolve options cal return generator; } + /** + * @param {string} type type of generator + * @param {GeneratorOptions} generatorOptions generator options + * @returns {Generator} generator + */ createGenerator(type, generatorOptions = {}) { generatorOptions = mergeGlobalOptions( this._globalGeneratorOptions, @@ -1158,6 +1284,11 @@ If changing the source code is not an option there is also a resolve options cal return generator; } + /** + * @param {Parameters[0]} type type of resolver + * @param {Parameters[1]=} resolveOptions options + * @returns {ReturnType} the resolver + */ getResolver(type, resolveOptions) { return this.resolverFactory.get(type, resolveOptions); } diff --git a/lib/RawModule.js b/lib/RawModule.js index 58efbabd083..db8792db1f4 100644 --- a/lib/RawModule.js +++ b/lib/RawModule.js @@ -19,6 +19,7 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ @@ -46,7 +47,7 @@ class RawModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/ResolverFactory.js b/lib/ResolverFactory.js index da36fd38214..6e034434108 100644 --- a/lib/ResolverFactory.js +++ b/lib/ResolverFactory.js @@ -13,7 +13,9 @@ const { resolveByProperty } = require("./util/cleverMerge"); +/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */ /** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ +/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */ /** @typedef {import("enhanced-resolve").Resolver} Resolver */ /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ /** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ diff --git a/lib/RuntimeModule.js b/lib/RuntimeModule.js index ee4f8a87f78..3dce5a8dc8f 100644 --- a/lib/RuntimeModule.js +++ b/lib/RuntimeModule.js @@ -19,6 +19,7 @@ const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants"); /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./WebpackError")} WebpackError */ @@ -123,7 +124,7 @@ class RuntimeModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/asset/RawDataUrlModule.js b/lib/asset/RawDataUrlModule.js index 278b3c86aa6..789a612e59e 100644 --- a/lib/asset/RawDataUrlModule.js +++ b/lib/asset/RawDataUrlModule.js @@ -17,6 +17,7 @@ const makeSerializable = require("../util/makeSerializable"); /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../WebpackError")} WebpackError */ @@ -42,7 +43,7 @@ class RawDataUrlModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/container/ContainerEntryModule.js b/lib/container/ContainerEntryModule.js index af80550301c..7bbbdc9b164 100644 --- a/lib/container/ContainerEntryModule.js +++ b/lib/container/ContainerEntryModule.js @@ -23,6 +23,7 @@ const ContainerExposedDependency = require("./ContainerExposedDependency"); /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../WebpackError")} WebpackError */ @@ -54,7 +55,7 @@ class ContainerEntryModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return SOURCE_TYPES; diff --git a/lib/container/FallbackModule.js b/lib/container/FallbackModule.js index b2ed81b0779..e766cefa74d 100644 --- a/lib/container/FallbackModule.js +++ b/lib/container/FallbackModule.js @@ -22,6 +22,7 @@ const FallbackItemDependency = require("./FallbackItemDependency"); /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../WebpackError")} WebpackError */ @@ -116,7 +117,7 @@ class FallbackModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/container/RemoteModule.js b/lib/container/RemoteModule.js index ade329b997a..86e4acc2b7e 100644 --- a/lib/container/RemoteModule.js +++ b/lib/container/RemoteModule.js @@ -21,6 +21,7 @@ const RemoteToExternalDependency = require("./RemoteToExternalDependency"); /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../WebpackError")} WebpackError */ @@ -119,7 +120,7 @@ class RemoteModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/dependencies/WorkerDependency.js b/lib/dependencies/WorkerDependency.js index 812653d8471..d96afadd9ae 100644 --- a/lib/dependencies/WorkerDependency.js +++ b/lib/dependencies/WorkerDependency.js @@ -29,7 +29,7 @@ class WorkerDependency extends ModuleDependency { * @param {string} request request * @param {Range} range range * @param {Object} workerDependencyOptions options - * @param {string} workerDependencyOptions.publicPath public path for the worker + * @param {string=} workerDependencyOptions.publicPath public path for the worker */ constructor(request, range, workerDependencyOptions) { super(request); diff --git a/lib/dependencies/WorkerPlugin.js b/lib/dependencies/WorkerPlugin.js index d36d76d966f..f141f11041b 100644 --- a/lib/dependencies/WorkerPlugin.js +++ b/lib/dependencies/WorkerPlugin.js @@ -71,10 +71,10 @@ const PLUGIN_NAME = "WorkerPlugin"; class WorkerPlugin { /** - * @param {ChunkLoading} chunkLoading chunk loading - * @param {WasmLoading} wasmLoading wasm loading - * @param {OutputModule} module output module - * @param {WorkerPublicPath} workerPublicPath worker public path + * @param {ChunkLoading=} chunkLoading chunk loading + * @param {WasmLoading=} wasmLoading wasm loading + * @param {OutputModule=} module output module + * @param {WorkerPublicPath=} workerPublicPath worker public path */ constructor(chunkLoading, wasmLoading, module, workerPublicPath) { this._chunkLoading = chunkLoading; diff --git a/lib/hmr/LazyCompilationPlugin.js b/lib/hmr/LazyCompilationPlugin.js index 7789a37b968..f92d69a44a3 100644 --- a/lib/hmr/LazyCompilationPlugin.js +++ b/lib/hmr/LazyCompilationPlugin.js @@ -27,6 +27,7 @@ const { registerNotSerializable } = require("../util/serialization"); /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ /** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ /** @typedef {import("../RequestShortener")} RequestShortener */ @@ -190,7 +191,7 @@ class LazyCompilationProxyModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/optimize/ConcatenatedModule.js b/lib/optimize/ConcatenatedModule.js index 87466ae9085..35abf0209cd 100644 --- a/lib/optimize/ConcatenatedModule.js +++ b/lib/optimize/ConcatenatedModule.js @@ -52,6 +52,7 @@ const { /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ @@ -710,7 +711,7 @@ class ConcatenatedModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/sharing/ConsumeSharedModule.js b/lib/sharing/ConsumeSharedModule.js index 0ad41d31396..08e52fb9c43 100644 --- a/lib/sharing/ConsumeSharedModule.js +++ b/lib/sharing/ConsumeSharedModule.js @@ -25,6 +25,7 @@ const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependen /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../WebpackError")} WebpackError */ @@ -147,7 +148,7 @@ class ConsumeSharedModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/sharing/ProvideSharedModule.js b/lib/sharing/ProvideSharedModule.js index 40796dd7bf7..22848391eb2 100644 --- a/lib/sharing/ProvideSharedModule.js +++ b/lib/sharing/ProvideSharedModule.js @@ -21,6 +21,7 @@ const ProvideForSharedDependency = require("./ProvideForSharedDependency"); /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../WebpackError")} WebpackError */ @@ -120,7 +121,7 @@ class ProvideSharedModule extends Module { } /** - * @returns {Set} types available (do not mutate) + * @returns {SourceTypes} types available (do not mutate) */ getSourceTypes() { return TYPES; diff --git a/lib/util/memoize.js b/lib/util/memoize.js index 5a73ee75ce3..e208cbbaa0d 100644 --- a/lib/util/memoize.js +++ b/lib/util/memoize.js @@ -23,6 +23,8 @@ const memoize = fn => { cache = true; // Allow to clean up memory for fn // and all dependent resources + // eslint-disable-next-line no-warning-comments + // @ts-ignore fn = undefined; return /** @type {T} */ (result); } diff --git a/lib/wasm-sync/WebAssemblyJavascriptGenerator.js b/lib/wasm-sync/WebAssemblyJavascriptGenerator.js index 1b5ca88dfb4..8a87a1319dd 100644 --- a/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +++ b/lib/wasm-sync/WebAssemblyJavascriptGenerator.js @@ -19,6 +19,7 @@ const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDe /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ /** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ /** @typedef {import("../NormalModule")} NormalModule */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ @@ -127,7 +128,7 @@ class WebAssemblyJavascriptGenerator extends Generator { const defineStatement = Template.asString([ `${exportProp} = ${runtimeTemplate.exportFromImport({ moduleGraph, - module: moduleGraph.getModule(dep), + module: /** @type {Module} */ (moduleGraph.getModule(dep)), request: dep.request, importVar: importData.importVar, originModule: module, diff --git a/lib/webpack.js b/lib/webpack.js index ec718b62721..4a6424d440a 100644 --- a/lib/webpack.js +++ b/lib/webpack.js @@ -20,6 +20,7 @@ const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin"); const memoize = require("./util/memoize"); /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ /** @typedef {import("./Compiler").WatchOptions} WatchOptions */ /** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ /** @typedef {import("./MultiStats")} MultiStats */ @@ -30,7 +31,7 @@ const getValidateSchema = memoize(() => require("./validateSchema")); /** * @template T * @callback Callback - * @param {Error=} err + * @param {(Error | null)=} err * @param {T=} stats * @returns {void} */ @@ -71,7 +72,8 @@ const createCompiler = rawOptions => { if (Array.isArray(options.plugins)) { for (const plugin of options.plugins) { if (typeof plugin === "function") { - plugin.call(compiler, compiler); + /** @type {WebpackPluginFunction} */ + (plugin).call(compiler, compiler); } else if (plugin) { plugin.apply(compiler); } @@ -160,7 +162,7 @@ const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( } return compiler; } catch (err) { - process.nextTick(() => callback(err)); + process.nextTick(() => callback(/** @type {Error} */ (err))); return null; } } else { diff --git a/types.d.ts b/types.d.ts index 41123366a5c..f17a4711e84 100644 --- a/types.d.ts +++ b/types.d.ts @@ -817,9 +817,7 @@ declare abstract class BasicEvaluatedExpression { | TemplateElement ): BasicEvaluatedExpression; } -declare interface BuildInfo { - [index: string]: any; -} +type BuildInfo = KnownBuildInfo & Record; type BuildMeta = KnownBuildMeta & Record; declare abstract class ByTypeGenerator extends Generator { map: Record; @@ -958,15 +956,15 @@ declare interface CallbackAsyncQueue { declare interface CallbackCache { (err?: null | WebpackError, result?: T): void; } -declare interface CallbackFunction { +declare interface CallbackFunction_1 { (err?: null | Error, result?: T): any; } +declare interface CallbackFunction_2 { + (err?: null | Error, stats?: T): void; +} declare interface CallbackNormalErrorCache { (err?: null | Error, result?: T): void; } -declare interface CallbackWebpack { - (err?: Error, stats?: T): void; -} type Cell = undefined | T; declare class Chunk { constructor(name?: string, backCompat?: boolean); @@ -2278,8 +2276,11 @@ declare class Compiler { watchMode: boolean; getCache(name: string): CacheFacade; getInfrastructureLogger(name: string | (() => string)): WebpackLogger; - watch(watchOptions: WatchOptions, handler: CallbackFunction): Watching; - run(callback: CallbackFunction): void; + watch( + watchOptions: WatchOptions, + handler: CallbackFunction_1 + ): Watching; + run(callback: CallbackFunction_1): void; runAsChild( callback: ( err?: null | Error, @@ -2288,9 +2289,12 @@ declare class Compiler { ) => any ): void; purgeInputFileSystem(): void; - emitAssets(compilation: Compilation, callback: CallbackFunction): void; - emitRecords(callback: CallbackFunction): void; - readRecords(callback: CallbackFunction): void; + emitAssets( + compilation: Compilation, + callback: CallbackFunction_1 + ): void; + emitRecords(callback: CallbackFunction_1): void; + readRecords(callback: CallbackFunction_1): void; createChildCompiler( compilation: Compilation, compilerName: string, @@ -2307,8 +2311,8 @@ declare class Compiler { normalModuleFactory: NormalModuleFactory; contextModuleFactory: ContextModuleFactory; }; - compile(callback: CallbackFunction): void; - close(callback: CallbackFunction): void; + compile(callback: CallbackFunction_1): void; + close(callback: CallbackFunction_1): void; } declare class ConcatSource extends Source { constructor(...args: (string | Source)[]); @@ -4822,6 +4826,9 @@ declare class Generator { updateHash(hash: Hash, __1: UpdateHashContextGenerator): void; static byType(map: Record): ByTypeGenerator; } +declare interface GeneratorOptions { + [index: string]: any; +} type GeneratorOptionsByModuleType = GeneratorOptionsByModuleTypeKnown & GeneratorOptionsByModuleTypeUnknown; @@ -6588,6 +6595,19 @@ declare interface KnownAssetInfo { */ related?: Record; } +declare interface KnownBuildInfo { + cacheable?: boolean; + parsed?: boolean; + fileDependencies?: LazySet; + contextDependencies?: LazySet; + missingDependencies?: LazySet; + buildDependencies?: LazySet; + valueDependencies?: Map>; + hash?: any; + assets?: Record; + assetsInfo?: Map; + snapshot?: null | Snapshot; +} declare interface KnownBuildMeta { moduleArgument?: string; exportsArgument?: string; @@ -7717,7 +7737,7 @@ declare class Module extends DependenciesBlock { * Module should be unsafe cached. Get data that's needed for that. * This data will be passed to restoreFromUnsafeCache later. */ - getUnsafeCacheData(): object; + getUnsafeCacheData(): UnsafeCacheData; /** * Assuming this module is in the cache. Remove internal references to allow freeing some memory. @@ -8283,21 +8303,21 @@ declare class MultiCompiler { outputFileSystem: OutputFileSystem; watchFileSystem: WatchFileSystem; intermediateFileSystem: IntermediateFileSystem; - getInfrastructureLogger(name?: any): WebpackLogger; + getInfrastructureLogger(name: string | (() => string)): WebpackLogger; setDependencies(compiler: Compiler, dependencies: string[]): void; - validateDependencies(callback: CallbackFunction): boolean; + validateDependencies(callback: CallbackFunction_1): boolean; runWithDependencies( compilers: Compiler[], - fn: (compiler: Compiler, callback: CallbackFunction) => any, - callback: CallbackFunction + fn: (compiler: Compiler, callback: CallbackFunction_1) => any, + callback: CallbackFunction_1 ): void; watch( watchOptions: WatchOptions | WatchOptions[], - handler: CallbackFunction + handler: CallbackFunction_1 ): MultiWatching; - run(callback: CallbackFunction): void; + run(callback: CallbackFunction_1): void; purgeInputFileSystem(): void; - close(callback: CallbackFunction): void; + close(callback: CallbackFunction_1): void; } declare interface MultiCompilerOptions { /** @@ -8316,10 +8336,10 @@ declare abstract class MultiStats { declare abstract class MultiWatching { watchings: Watching[]; compiler: MultiCompiler; - invalidate(callback?: CallbackFunction): void; + invalidate(callback?: CallbackFunction_1): void; suspend(): void; resume(): void; - close(callback: CallbackFunction): void; + close(callback: CallbackFunction_1): void; } declare class NamedChunkIdsPlugin { constructor(options?: NamedChunkIdsPluginOptions); @@ -8454,36 +8474,40 @@ declare class NormalModule extends Module { userRequest: string; rawRequest: string; binary: boolean; - parser: Parser; - parserOptions?: Record; - generator: Generator; - generatorOptions?: Record; + parser?: Parser; + parserOptions?: ParserOptions; + generator?: Generator; + generatorOptions?: GeneratorOptions; resource: string; resourceResolveData?: Record; matchResource?: string; loaders: LoaderItem[]; - error?: null | WebpackError; + error: null | WebpackError; + + /** + * restore unsafe cache data + */ restoreFromUnsafeCache( - unsafeCacheData?: any, - normalModuleFactory?: any + unsafeCacheData: NormalModuleUnsafeCacheData, + normalModuleFactory: NormalModuleFactory ): void; createSourceForAsset( context: string, name: string, - content: string, - sourceMap?: any, + content: string | Buffer, + sourceMap?: string | SourceMap, associatedObjectForCache?: Object ): Source; - getCurrentLoader(loaderContext?: any, index?: any): null | LoaderItem; + getCurrentLoader(loaderContext?: any, index?: number): null | LoaderItem; createSource( context: string, content: string | Buffer, - sourceMap?: any, + sourceMap?: string | SourceMapSource, associatedObjectForCache?: Object ): Source; markModuleAsErrored(error: WebpackError): void; - applyNoParseRule(rule?: any, content?: any): any; - shouldPreventParsing(noParseRule?: any, request?: any): any; + applyNoParseRule(rule: any, content: string): boolean; + shouldPreventParsing(noParseRule: any, request: string): boolean; static getCompilationHooks( compilation: Compilation ): NormalModuleCompilationHooks; @@ -8559,7 +8583,7 @@ declare interface NormalModuleCreateData { /** * the options of the parser used */ - parserOptions?: Record; + parserOptions?: ParserOptions; /** * the generator used @@ -8569,7 +8593,7 @@ declare interface NormalModuleCreateData { /** * the options of the generator used */ - generatorOptions?: Record; + generatorOptions?: GeneratorOptions; /** * options used for resolving requests from this module @@ -8603,40 +8627,47 @@ declare abstract class NormalModuleFactory extends ModuleFactory { ], Module >; - createParser: HookMap>; - parser: HookMap>; - createGenerator: HookMap>; - generator: HookMap>; - createModuleClass: HookMap>; + createParser: HookMap>; + parser: HookMap>; + createGenerator: HookMap>; + generator: HookMap>; + createModuleClass: HookMap>; }>; resolverFactory: ResolverFactory; ruleSet: RuleSet; context: string; fs: InputFileSystem; - parserCache: Map>; + parserCache: Map>; generatorCache: Map>; cleanupForCache(): void; resolveResource( - contextInfo?: any, - context?: any, - unresolvedResource?: any, - resolver?: any, - resolveContext?: any, - callback?: any + contextInfo: ModuleFactoryCreateDataContextInfo, + context: string, + unresolvedResource: string, + resolver: ResolverWithOptions, + resolveContext: ResolveContext, + callback: ( + err: null | Error, + res?: string | false, + req?: ResolveRequest + ) => void ): void; resolveRequestArray( - contextInfo?: any, - context?: any, - array?: any, - resolver?: any, - resolveContext?: any, - callback?: any - ): any; - getParser(type?: any, parserOptions?: object): any; - createParser(type: string, parserOptions?: { [index: string]: any }): Parser; - getGenerator(type?: any, generatorOptions?: object): undefined | Generator; - createGenerator(type?: any, generatorOptions?: object): any; - getResolver(type?: any, resolveOptions?: any): ResolverWithOptions; + contextInfo: ModuleFactoryCreateDataContextInfo, + context: string, + array: LoaderItem[], + resolver: ResolverWithOptions, + resolveContext: ResolveContext, + callback: CallbackFunction_2 + ): void; + getParser(type: string, parserOptions?: ParserOptions): Parser; + createParser(type: string, parserOptions?: ParserOptions): Parser; + getGenerator(type: string, generatorOptions?: GeneratorOptions): Generator; + createGenerator(type: string, generatorOptions?: GeneratorOptions): Generator; + getResolver( + type: string, + resolveOptions?: ResolveOptionsWithDependencyType + ): ResolverWithOptions; } /** @@ -8680,7 +8711,7 @@ declare interface NormalModuleLoaderContext { utils: { absolutify: (context: string, request: string) => string; contextify: (context: string, request: string) => string; - createHash: (algorithm?: string) => Hash; + createHash: (algorithm?: string | typeof Hash) => Hash; }; rootContext: string; fs: InputFileSystem; @@ -8707,6 +8738,12 @@ declare class NormalModuleReplacementPlugin { */ apply(compiler: Compiler): void; } +type NormalModuleUnsafeCacheData = UnsafeCacheData & { + parser?: Parser; + parserOptions?: ParserOptions; + generator?: Generator; + generatorOptions?: GeneratorOptions; +}; type NormalizedStatsOptions = KnownNormalizedStatsOptions & Omit< StatsOptions, @@ -9820,6 +9857,9 @@ declare class Parser { state: ParserState ): ParserState; } +declare interface ParserOptions { + [index: string]: any; +} type ParserOptionsByModuleType = ParserOptionsByModuleTypeKnown & ParserOptionsByModuleTypeUnknown; @@ -10854,9 +10894,9 @@ type ResolverWithOptions = Resolver & WithOptions; declare interface ResourceDataWithData { resource: string; - path: string; - query: string; - fragment: string; + path?: string; + query?: string; + fragment?: string; context?: string; data: Record; } @@ -12989,6 +13029,10 @@ declare interface TrustedTypes { policyName?: string; } declare const UNDEFINED_MARKER: unique symbol; +declare interface UnsafeCacheData { + factoryMeta?: FactoryMeta; + resolveOptions?: ResolveOptionsWebpackOptions; +} declare interface UpdateHashContextDependency { chunkGraph: ChunkGraph; runtime: RuntimeSpec; @@ -13285,8 +13329,8 @@ declare interface WatcherInfo { declare abstract class Watching { startTime: null | number; invalid: boolean; - handler: CallbackFunction; - callbacks: CallbackFunction[]; + handler: CallbackFunction_1; + callbacks: CallbackFunction_1[]; closed: boolean; suspended: boolean; blocked: boolean; @@ -13322,10 +13366,10 @@ declare abstract class Watching { dirs: Iterable, missing: Iterable ): void; - invalidate(callback?: CallbackFunction): void; + invalidate(callback?: CallbackFunction_1): void; suspend(): void; resume(): void; - close(callback: CallbackFunction): void; + close(callback: CallbackFunction_1): void; } declare abstract class WeakTupleMap { set(...args: [T, ...V[]]): void; @@ -13725,18 +13769,18 @@ type __Type_2 = | __Type_2[]); declare function exports( options: Configuration, - callback?: CallbackWebpack + callback?: CallbackFunction_2 ): Compiler; declare function exports( options: ReadonlyArray & MultiCompilerOptions, - callback?: CallbackWebpack + callback?: CallbackFunction_2 ): MultiCompiler; declare namespace exports { export const webpack: { - (options: Configuration, callback?: CallbackWebpack): Compiler; + (options: Configuration, callback?: CallbackFunction_2): Compiler; ( options: ReadonlyArray & MultiCompilerOptions, - callback?: CallbackWebpack + callback?: CallbackFunction_2 ): MultiCompiler; }; export const validate: (options?: any) => void;