From 6589de0b6323752344c7b587050f44a7d13325ec Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Thu, 24 Oct 2024 21:13:59 +0300 Subject: [PATCH] fix: types --- declarations.d.ts | 5 + lib/AsyncDependenciesBlock.js | 2 +- lib/ChunkGraph.js | 5 +- lib/ChunkGroup.js | 4 +- lib/CleanPlugin.js | 6 +- lib/Compilation.js | 90 +++-- lib/Compiler.js | 4 +- lib/ConcatenationScope.js | 19 +- lib/ContextModule.js | 8 +- lib/DefinePlugin.js | 22 +- lib/HotModuleReplacementPlugin.js | 4 +- lib/Module.js | 7 +- lib/NormalModuleFactory.js | 5 +- lib/RuntimeTemplate.js | 2 +- lib/cache/PackFileCacheStrategy.js | 69 ++-- lib/config/defaults.js | 6 +- lib/css/CssGenerator.js | 6 +- lib/css/CssParser.js | 2 +- lib/debug/ProfilingPlugin.js | 5 + ...armonyExportImportedSpecifierDependency.js | 22 +- .../HarmonyImportDependencyParserPlugin.js | 14 +- lib/javascript/JavascriptGenerator.js | 6 +- lib/javascript/JavascriptParser.js | 32 +- lib/logging/Logger.js | 22 +- lib/logging/createConsoleLogger.js | 28 +- lib/logging/truncateArgs.js | 2 +- lib/node/nodeConsole.js | 2 +- lib/optimize/ConcatenatedModule.js | 13 +- lib/optimize/LimitChunkCountPlugin.js | 6 +- lib/stats/DefaultStatsFactoryPlugin.js | 35 +- lib/stats/StatsFactory.js | 2 +- lib/stats/StatsPrinter.js | 4 +- lib/util/create-schema-validation.js | 4 +- lib/util/fs.js | 8 +- types.d.ts | 329 +++++++++++++----- 35 files changed, 518 insertions(+), 282 deletions(-) diff --git a/declarations.d.ts b/declarations.d.ts index d901322bc4f..60d62d98e16 100644 --- a/declarations.d.ts +++ b/declarations.d.ts @@ -436,3 +436,8 @@ declare module "watchpack" { } export = Watchpack; } + +declare module "eslint-scope/lib/referencer" { + class Referencer {} + export = Referencer; +} diff --git a/lib/AsyncDependenciesBlock.js b/lib/AsyncDependenciesBlock.js index 539c20cb35d..a5a346b9a21 100644 --- a/lib/AsyncDependenciesBlock.js +++ b/lib/AsyncDependenciesBlock.js @@ -39,7 +39,7 @@ class AsyncDependenciesBlock extends DependenciesBlock { } /** - * @returns {string | undefined} The name of the chunk + * @returns {string | null | undefined} The name of the chunk */ get chunkName() { return this.groupOptions.name; diff --git a/lib/ChunkGraph.js b/lib/ChunkGraph.js index 462ec9f38af..9439a4c50a3 100644 --- a/lib/ChunkGraph.js +++ b/lib/ChunkGraph.js @@ -119,7 +119,10 @@ const modulesBySourceType = sourceTypesByModule => set => { }; const defaultModulesBySourceType = modulesBySourceType(undefined); -/** @type {WeakMap} */ +/** + * @template T + * @type {WeakMap} + */ const createOrderedArrayFunctionMap = new WeakMap(); /** diff --git a/lib/ChunkGroup.js b/lib/ChunkGroup.js index 9b899dd214f..2fcb71d1d9b 100644 --- a/lib/ChunkGroup.js +++ b/lib/ChunkGroup.js @@ -31,7 +31,7 @@ const { * @property {("low" | "high" | "auto")=} fetchPriority */ -/** @typedef {RawChunkGroupOptions & { name?: string }} ChunkGroupOptions */ +/** @typedef {RawChunkGroupOptions & { name?: string | null }} ChunkGroupOptions */ let debugId = 5000; @@ -137,7 +137,7 @@ class ChunkGroup { /** * returns the name of current ChunkGroup - * @returns {string | undefined} returns the ChunkGroup name + * @returns {string | null | undefined} returns the ChunkGroup name */ get name() { return this.options.name; diff --git a/lib/CleanPlugin.js b/lib/CleanPlugin.js index a4a7185a04f..2e8fe9bac65 100644 --- a/lib/CleanPlugin.js +++ b/lib/CleanPlugin.js @@ -31,7 +31,7 @@ const processAsyncTree = require("./util/processAsyncTree"); /** * @callback KeepFn * @param {string} path path - * @returns {boolean} true, if the path should be kept + * @returns {boolean | void} true, if the path should be kept */ const validate = createSchemaValidation( @@ -149,7 +149,7 @@ const doStat = (fs, filename, callback) => { * @param {boolean} dry only log instead of fs modification * @param {Logger} logger logger * @param {Set} diff filenames of the assets that shouldn't be there - * @param {function(string): boolean} isKept check if the entry is ignored + * @param {function(string): boolean | void} isKept check if the entry is ignored * @param {function(Error=, Assets=): void} callback callback * @returns {void} */ @@ -392,7 +392,7 @@ class CleanPlugin { /** * @param {string} path path - * @returns {boolean} true, if needs to be kept + * @returns {boolean | void} true, if needs to be kept */ const isKept = path => { const result = hooks.keep.call(path); diff --git a/lib/Compilation.js b/lib/Compilation.js index c098372783e..3dc2775f53d 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -98,15 +98,18 @@ const { isSourceEqual } = require("./util/source"); /** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler").CompilationParams} CompilationParams */ +/** @typedef {import("./Compiler").ModuleMemCachesItem} ModuleMemCachesItem */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("./DependencyTemplate")} DependencyTemplate */ /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ /** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */ /** @typedef {import("./NormalModule").NormalModuleCompilationHooks} NormalModuleCompilationHooks */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./ModuleFactory")} ModuleFactory */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ /** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ /** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ /** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ @@ -119,6 +122,7 @@ const { isSourceEqual } = require("./util/source"); /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ /** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/createHash").Algorithm} Algorithm */ /** * @template T * @typedef {import("./util/deprecation").FakeHook} FakeHook @@ -366,8 +370,6 @@ const { isSourceEqual } = require("./util/source"); /** @typedef {Set} NotCodeGeneratedModules */ -/** @typedef {string | Set | undefined} ValueCacheVersion */ - /** @type {AssetInfo} */ const EMPTY_ASSET_INFO = Object.freeze({}); @@ -925,7 +927,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si true ); } - /** @type {Map} */ + /** @type {ValueCacheVersions} */ this.valueCacheVersions = new Map(); this.requestShortener = compiler.requestShortener; this.compilerPath = compiler.compilerPath; @@ -1078,11 +1080,6 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si this.codeGeneratedModules = new WeakSet(); /** @type {WeakSet} */ this.buildTimeExecutedModules = new WeakSet(); - /** - * @private - * @type {Map} - */ - this._rebuildingModules = new Map(); /** @type {Set} */ this.emittedAssets = new Set(); /** @type {Set} */ @@ -1508,7 +1505,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si let factoryCacheKey; /** @type {ModuleFactory} */ let factoryCacheKey2; - /** @type {Map} */ + /** @typedef {Map} FactoryCacheValue */ + /** @type {FactoryCacheValue | undefined} */ let factoryCacheValue; /** @type {string} */ let listCacheKey1; @@ -1712,7 +1710,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si if (factoryCacheKey2 !== undefined) { // Archive last cache entry if (dependencies === undefined) dependencies = new Map(); - dependencies.set(factoryCacheKey2, factoryCacheValue); + dependencies.set( + factoryCacheKey2, + /** @type {FactoryCacheValue} */ (factoryCacheValue) + ); factoryCacheValue = dependencies.get(factory); if (factoryCacheValue === undefined) { factoryCacheValue = new Map(); @@ -1731,9 +1732,12 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si category === esmDependencyCategory ? resourceIdent : `${category}${resourceIdent}`; - let list = factoryCacheValue.get(cacheKey); + let list = /** @type {FactoryCacheValue} */ (factoryCacheValue).get( + cacheKey + ); if (list === undefined) { - factoryCacheValue.set(cacheKey, (list = [])); + /** @type {FactoryCacheValue} */ + (factoryCacheValue).set(cacheKey, (list = [])); sortedDependencies.push({ factory: factoryCacheKey2, dependencies: list, @@ -1763,7 +1767,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si } } while (queue.length !== 0); } catch (err) { - return callback(err); + return callback(/** @type {WebpackError} */ (err)); } if (--inProgressSorting === 0) onDependenciesSorted(); @@ -1859,7 +1863,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si (err, factoryResult) => { const applyFactoryResultDependencies = () => { const { fileDependencies, contextDependencies, missingDependencies } = - factoryResult; + /** @type {ModuleFactoryResult} */ (factoryResult); if (fileDependencies) { this.fileDependencies.addAll(fileDependencies); } @@ -1880,7 +1884,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si return callback(err); } - const newModule = factoryResult.module; + const newModule = + /** @type {ModuleFactoryResult} */ + (factoryResult).module; if (!newModule) { applyFactoryResultDependencies(); @@ -1908,7 +1914,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si if ( this._unsafeCache && - factoryResult.cacheable !== false && + /** @type {ModuleFactoryResult} */ + (factoryResult).cacheable !== false && module.restoreFromUnsafeCache && this._unsafeCachePredicate(module) ) { @@ -2116,7 +2123,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si const notFoundError = new ModuleNotFoundError( originModule, err, - dependencies.map(d => d.loc).find(Boolean) + /** @type {DependencyLocation} */ + (dependencies.map(d => d.loc).find(Boolean)) ); return callback(notFoundError, factoryResult ? result : undefined); } @@ -2515,7 +2523,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si affectedModules.add(referencingModule); } const memCache = new WeakTupleMap(); - const cache = moduleMemCacheCache.get(referencingModule); + const cache = + /** @type {ModuleMemCachesItem} */ + (moduleMemCacheCache.get(referencingModule)); cache.memCache = memCache; moduleMemCaches.set(referencingModule, memCache); } @@ -2544,10 +2554,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si let statNew = 0; /** * @param {Module} module module - * @returns {{ id: string | number, modules?: Map, blocks?: (string | number | null)[] }} references + * @returns {{ id: ModuleId, modules?: Map, blocks?: (string | number | null)[] }} references */ const computeReferences = module => { - const id = chunkGraph.getModuleId(module); + const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); /** @type {Map | undefined} */ let modules; /** @type {(string | number | null)[] | undefined} */ @@ -2557,7 +2567,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si for (const m of outgoing.keys()) { if (!m) continue; if (modules === undefined) modules = new Map(); - modules.set(m, chunkGraph.getModuleId(m)); + modules.set(m, /** @type {ModuleId} */ (chunkGraph.getModuleId(m))); } } if (module.blocks.length > 0) { @@ -3746,7 +3756,6 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o if (name) { const chunkGroup = this.namedChunkGroups.get(name); if (chunkGroup !== undefined) { - chunkGroup.addOptions(groupOptions); if (module) { chunkGroup.addOrigin( module, @@ -4017,10 +4026,13 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o assignRuntimeIds() { const { chunkGraph } = this; + /** + * @param {Entrypoint} ep an entrypoint + */ const processEntrypoint = ep => { - const runtime = ep.options.runtime || ep.name; - const chunk = ep.getRuntimeChunk(); - chunkGraph.setRuntimeId(runtime, chunk.id); + const runtime = /** @type {string} */ (ep.options.runtime || ep.name); + const chunk = /** @type {Chunk} */ (ep.getRuntimeChunk()); + chunkGraph.setRuntimeId(runtime, /** @type {ChunkId} */ (chunk.id)); }; for (const ep of this.entrypoints.values()) { processEntrypoint(ep); @@ -4142,7 +4154,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o ) { let moduleHashDigest; try { - const moduleHash = createHash(hashFunction); + const moduleHash = createHash(/** @type {Algorithm} */ (hashFunction)); module.updateHash(moduleHash, { chunkGraph, runtime, @@ -4170,7 +4182,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; - const hash = createHash(hashFunction); + const hash = createHash(/** @type {Algorithm} */ (hashFunction)); if (outputOptions.hashSalt) { hash.update(outputOptions.hashSalt); } @@ -4178,7 +4190,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o if (this.children.length > 0) { this.logger.time("hashing: hash child compilations"); for (const child of this.children) { - hash.update(child.hash); + hash.update(/** @type {string} */ (child.hash)); } this.logger.timeEnd("hashing: hash child compilations"); } @@ -4239,7 +4251,9 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o e => e.chunks[e.chunks.length - 1] ) )) { - const otherInfo = runtimeChunksMap.get(other); + const otherInfo = + /** @type {RuntimeChunkInfo} */ + (runtimeChunksMap.get(other)); otherInfo.referencedBy.push(info); info.remaining++; remaining++; @@ -4351,7 +4365,7 @@ This prevents using hashes of each other and should be avoided.`); this.logger.timeAggregate("hashing: hash runtime modules"); try { this.logger.time("hashing: hash chunks"); - const chunkHash = createHash(hashFunction); + const chunkHash = createHash(/** @type {Algorithm} */ (hashFunction)); if (outputOptions.hashSalt) { chunkHash.update(outputOptions.hashSalt); } @@ -4404,7 +4418,7 @@ This prevents using hashes of each other and should be avoided.`); for (const module of /** @type {Iterable} */ ( chunkGraph.getChunkFullHashModulesIterable(chunk) )) { - const moduleHash = createHash(hashFunction); + const moduleHash = createHash(/** @type {Algorithm} */ (hashFunction)); module.updateHash(moduleHash, { chunkGraph, runtime: chunk.runtime, @@ -4422,7 +4436,7 @@ This prevents using hashes of each other and should be avoided.`); ); codeGenerationJobsMap.get(oldHash).get(module).hash = moduleHashDigest; } - const chunkHash = createHash(hashFunction); + const chunkHash = createHash(/** @type {Algorithm} */ (hashFunction)); chunkHash.update(chunk.hash); chunkHash.update(this.hash); const chunkHashDigest = @@ -4467,6 +4481,12 @@ This prevents using hashes of each other and should be avoided.`); this._setAssetInfo(file, assetInfo, undefined); } + /** + * @private + * @param {string} file file name + * @param {AssetInfo} newInfo new asset information + * @param {AssetInfo=} oldInfo old asset information + */ _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) { if (newInfo === undefined) { this.assetsInfo.delete(file); @@ -4754,8 +4774,8 @@ This prevents using hashes of each other and should be avoided.`); try { manifest = this.getRenderManifest({ chunk, - hash: this.hash, - fullHash: this.fullHash, + hash: /** @type {string} */ (this.hash), + fullHash: /** @type {string} */ (this.fullHash), outputOptions, codeGenerationResults: this.codeGenerationResults, moduleTemplates: this.moduleTemplates, @@ -5377,7 +5397,7 @@ This prevents using hashes of each other and should be avoided.`); /** * @typedef {object} FactorizeModuleOptions - * @property {ModuleProfile} currentProfile + * @property {ModuleProfile=} currentProfile * @property {ModuleFactory} factory * @property {Dependency[]} dependencies * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module diff --git a/lib/Compiler.js b/lib/Compiler.js index bd8ba4c2fa1..99d466ec990 100644 --- a/lib/Compiler.js +++ b/lib/Compiler.js @@ -98,6 +98,8 @@ const { isSourceEqual } = require("./util/source"); /** @typedef {{ sizeOnlySource: SizeOnlySource | undefined, writtenTo: Map }} CacheEntry */ /** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: any, file: string }[] | undefined) }} SimilarEntry */ +/** @typedef {{ buildInfo: BuildInfo, references: References | undefined, memCache: WeakTupleMap }} ModuleMemCachesItem */ + /** * @param {string[]} array an array * @returns {boolean} true, if the array is sorted @@ -288,7 +290,7 @@ class Compiler { this.cache = new Cache(); - /** @type {Map }> | undefined} */ + /** @type {Map | undefined} */ this.moduleMemCaches = undefined; this.compilerPath = ""; diff --git a/lib/ConcatenationScope.js b/lib/ConcatenationScope.js index d144829b7ab..5c7bb6fd0dc 100644 --- a/lib/ConcatenationScope.js +++ b/lib/ConcatenationScope.js @@ -11,27 +11,12 @@ const { } = require("./util/concatenate"); /** @typedef {import("./Module")} Module */ +/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */ +/** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */ const MODULE_REFERENCE_REGEXP = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(?:_asiSafe(\d))?__$/; -/** - * @typedef {object} ExternalModuleInfo - * @property {number} index - * @property {Module} module - */ - -/** - * @typedef {object} ConcatenatedModuleInfo - * @property {number} index - * @property {Module} module - * @property {Map} exportMap mapping from export name to symbol - * @property {Map} rawExportMap mapping from export name to symbol - * @property {string=} namespaceExportSymbol - */ - -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */ - /** * @typedef {object} ModuleReferenceOptions * @property {string[]} ids the properties/exports of the module diff --git a/lib/ContextModule.js b/lib/ContextModule.js index b3340dfb432..b273c66e639 100644 --- a/lib/ContextModule.js +++ b/lib/ContextModule.js @@ -62,11 +62,11 @@ const makeSerializable = require("./util/makeSerializable"); * @property {ContextMode} mode * @property {boolean} recursive * @property {RegExp} regExp - * @property {"strict"|boolean=} namespaceObject + * @property {("strict" | boolean)=} namespaceObject * @property {string=} addon - * @property {string=} chunkName - * @property {RegExp | null=} include - * @property {RegExp | null=} exclude + * @property {(string | null)=} chunkName + * @property {(RegExp | null)=} include + * @property {(RegExp | null)=} exclude * @property {RawChunkGroupOptions=} groupOptions * @property {string=} typePrefix * @property {string=} category diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js index 574d8ca5e28..d7209bca2f5 100644 --- a/lib/DefinePlugin.js +++ b/lib/DefinePlugin.js @@ -22,9 +22,9 @@ const { const createHash = require("./util/createHash"); /** @typedef {import("estree").Expression} Expression */ -/** @typedef {import("./Compilation").ValueCacheVersion} ValueCacheVersion */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */ /** @typedef {import("./NormalModule")} NormalModule */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ @@ -45,6 +45,7 @@ const createHash = require("./util/createHash"); * @property {string|function(): string=} version */ +/** @typedef {string | Set} ValueCacheVersion */ /** @typedef {function({ module: NormalModule, key: string, readonly version: ValueCacheVersion }): CodeValuePrimitive} GeneratorFn */ class RuntimeValue { @@ -68,7 +69,7 @@ class RuntimeValue { /** * @param {JavascriptParser} parser the parser - * @param {Map} valueCacheVersions valueCacheVersions + * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions * @param {string} key the defined key * @returns {CodeValuePrimitive} code */ @@ -107,7 +108,9 @@ class RuntimeValue { module: parser.state.module, key, get version() { - return valueCacheVersions.get(VALUE_DEP_PREFIX + key); + return /** @type {ValueCacheVersion} */ ( + valueCacheVersions.get(VALUE_DEP_PREFIX + key) + ); } }); } @@ -136,7 +139,7 @@ function getObjKeys(properties) { /** * @param {any[]|{[k: string]: any}} obj obj * @param {JavascriptParser} parser Parser - * @param {Map} valueCacheVersions valueCacheVersions + * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions * @param {string} key the defined key * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {Logger} logger the logger object @@ -209,7 +212,7 @@ const stringifyObj = ( * Convert code to a string that evaluates * @param {CodeValue} code Code to evaluate * @param {JavascriptParser} parser Parser - * @param {Map} valueCacheVersions valueCacheVersions + * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions * @param {string} key the defined key * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {Logger} logger the logger object @@ -377,7 +380,9 @@ class DefinePlugin { * @returns {void} */ const handler = parser => { - const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); + const mainValue = + /** @type {ValueCacheVersion} */ + (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)); parser.hooks.program.tap(PLUGIN_NAME, () => { const buildInfo = /** @type {BuildInfo} */ ( parser.state.module.buildInfo @@ -397,7 +402,8 @@ class DefinePlugin { /** @type {NonNullable} */ (buildInfo.valueDependencies).set( VALUE_DEP_PREFIX + key, - compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key) + /** @type {ValueCacheVersion} */ + (compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)) ); }; @@ -666,7 +672,7 @@ class DefinePlugin { const walkDefinitionsForValues = (definitions, prefix) => { for (const key of Object.keys(definitions)) { const code = definitions[key]; - const version = toCacheVersion(code); + const version = /** @type {string} */ (toCacheVersion(code)); const name = VALUE_DEP_PREFIX + prefix + key; mainHash.update(`|${prefix}${key}`); const oldVersion = compilation.valueCacheVersions.get(name); diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js index 8e68de5b4d4..cd25dafba1b 100644 --- a/lib/HotModuleReplacementPlugin.js +++ b/lib/HotModuleReplacementPlugin.js @@ -61,8 +61,8 @@ const { /** * @typedef {object} HMRJavascriptParserHooks - * @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptCallback - * @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptWithoutCallback + * @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptCallback + * @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptWithoutCallback */ /** @typedef {{ updatedChunkIds: Set, removedChunkIds: Set, removedModules: Set, filename: string, assetInfo: AssetInfo }} HotUpdateMainContentByRuntimeItem */ diff --git a/lib/Module.js b/lib/Module.js index 467158eebfa..3b2e9f7570a 100644 --- a/lib/Module.js +++ b/lib/Module.js @@ -23,7 +23,6 @@ const makeSerializable = require("./util/makeSerializable"); /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ /** @typedef {import("./Compilation")} Compilation */ /** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compilation").ValueCacheVersion} ValueCacheVersion */ /** @typedef {import("./ConcatenationScope")} ConcatenationScope */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ @@ -114,18 +113,20 @@ const makeSerializable = require("./util/makeSerializable"); * @property {LazySet=} contextDependencies * @property {LazySet=} missingDependencies * @property {LazySet=} buildDependencies - * @property {(Map)=} valueDependencies + * @property {ValueCacheVersions=} valueDependencies * @property {TODO=} hash * @property {Record=} assets * @property {Map=} assetsInfo * @property {(Snapshot | null)=} snapshot */ +/** @typedef {Map>} ValueCacheVersions */ + /** * @typedef {object} NeedBuildContext * @property {Compilation} compilation * @property {FileSystemInfo} fileSystemInfo - * @property {Map>} valueCacheVersions + * @property {ValueCacheVersions} valueCacheVersions */ /** @typedef {KnownBuildMeta & Record} BuildMeta */ diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index 862ee793b94..546bd593ac4 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -379,7 +379,10 @@ 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) { diff --git a/lib/RuntimeTemplate.js b/lib/RuntimeTemplate.js index 084cfb84861..b38e9b0b3c5 100644 --- a/lib/RuntimeTemplate.js +++ b/lib/RuntimeTemplate.js @@ -307,7 +307,7 @@ class RuntimeTemplate { * Add a comment * @param {object} options Information content of the comment * @param {string=} options.request request string used originally - * @param {string=} options.chunkName name of the chunk referenced + * @param {(string | null)=} options.chunkName name of the chunk referenced * @param {string=} options.chunkReason reason information of the chunk * @param {string=} options.message additional message * @param {string=} options.exportName name of the export diff --git a/lib/cache/PackFileCacheStrategy.js b/lib/cache/PackFileCacheStrategy.js index c1fc07d03c4..df8958879c0 100644 --- a/lib/cache/PackFileCacheStrategy.js +++ b/lib/cache/PackFileCacheStrategy.js @@ -268,20 +268,21 @@ class Pack { } _persistFreshContent() { + /** @typedef {{ items: Items, map: Map, loc: number }} PackItem */ const itemsCount = this.freshContent.size; if (itemsCount > 0) { const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK); const itemsPerPack = Math.ceil(itemsCount / packCount); + /** @type {PackItem[]} */ const packs = []; let i = 0; let ignoreNextTimeTick = false; const createNextPack = () => { const loc = this._findLocation(); - this.content[loc] = null; // reserve + this.content[loc] = /** @type {EXPECTED_ANY} */ (null); // reserve + /** @type {PackItem} */ const pack = { - /** @type {Items} */ items: new Set(), - /** @type {Map} */ map: new Map(), loc }; @@ -407,7 +408,9 @@ class Pack { await content.unpack( "it should be merged with other small pack contents" ); - for (const [identifier, value] of content.content) { + for (const [identifier, value] of /** @type {Content} */ ( + content.content + )) { map.set(identifier, value); } }); @@ -423,7 +426,7 @@ class Pack { mergedItems, mergedUsedItems, memoize(async () => { - /** @type {Map} */ + /** @type {Content} */ const map = new Map(); await Promise.all(addToMergedMap.map(fn => fn(map))); return new PackContentItems(map); @@ -471,7 +474,11 @@ class Pack { ); const map = new Map(); for (const identifier of usedItems) { - map.set(identifier, content.content.get(identifier)); + map.set( + identifier, + /** @type {Content} */ + (content.content).get(identifier) + ); } return new PackContentItems(map); } @@ -498,7 +505,11 @@ class Pack { ); const map = new Map(); for (const identifier of unusedItems) { - map.set(identifier, content.content.get(identifier)); + map.set( + identifier, + /** @type {Content} */ + (content.content).get(identifier) + ); } return new PackContentItems(map); } @@ -552,7 +563,11 @@ class Pack { ); const map = new Map(); for (const identifier of items) { - map.set(identifier, content.content.get(identifier)); + map.set( + identifier, + /** @type {Content} */ + (content.content).get(identifier) + ); } return new PackContentItems(map); }) @@ -633,7 +648,8 @@ class Pack { ) ); for (const identifier of items) { - this.itemInfo.get(identifier).location = idx; + /** @type {PackItemInfo} */ + (this.itemInfo.get(identifier)).location = idx; } } items = read(); @@ -643,9 +659,11 @@ class Pack { makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack"); +/** @typedef {Map} Content */ + class PackContentItems { /** - * @param {Map} map items + * @param {Content} map items */ constructor(map) { this.map = map; @@ -773,6 +791,8 @@ makeSerializable( "PackContentItems" ); +/** @typedef {(function(): Promise | PackContentItems)} LazyFn */ + class PackContent { /* This class can be in these states: @@ -802,9 +822,9 @@ class PackContent { */ constructor(items, usedItems, dataOrFn, logger, lazyName) { this.items = items; - /** @type {(function(): Promise | PackContentItems) | undefined} */ + /** @type {LazyFn | undefined} */ this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined; - /** @type {Map | undefined} */ + /** @type {Content | undefined} */ this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map; this.outdated = false; this.used = usedItems; @@ -840,7 +860,7 @@ class PackContent { ); logger.time(timeMessage); } - const value = this.lazy(); + const value = /** @type {LazyFn} */ (this.lazy)(); if ("then" in value) { return value.then(data => { const map = data.map; @@ -849,7 +869,10 @@ class PackContent { } // Move to state C this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + this.lazy = SerializerMiddleware.unMemoizeLazy( + /** @type {LazyFn} */ + (this.lazy) + ); return map.get(identifier); }); } @@ -860,7 +883,10 @@ class PackContent { } // Move to state C this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + this.lazy = SerializerMiddleware.unMemoizeLazy( + /** @type {LazyFn} */ + (this.lazy) + ); return map.get(identifier); } @@ -950,7 +976,7 @@ class PackContent { } if (this.content) { // State A2 or C2 - /** @type {Map} */ + /** @type {Content} */ const map = new Map(); for (const item of this.items) { map.set(item, this.content.get(item)); @@ -981,7 +1007,7 @@ class PackContent { ); logger.time(timeMessage); } - const value = this.lazy(); + const value = /** @type {LazyFn} */ (this.lazy)(); this.outdated = false; if ("then" in value) { // Move to state B1 @@ -991,14 +1017,17 @@ class PackContent { logger.timeEnd(timeMessage); } const oldMap = data.map; - /** @type {Map} */ + /** @type {Content} */ const map = new Map(); for (const item of this.items) { map.set(item, oldMap.get(item)); } // Move to state C1 (or maybe C2) this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + this.lazy = SerializerMiddleware.unMemoizeLazy( + /** @type {LazyFn} */ + (this.lazy) + ); return new PackContentItems(map); }) @@ -1009,7 +1038,7 @@ class PackContent { logger.timeEnd(timeMessage); } const oldMap = value.map; - /** @type {Map} */ + /** @type {Content} */ const map = new Map(); for (const item of this.items) { map.set(item, oldMap.get(item)); diff --git a/lib/config/defaults.js b/lib/config/defaults.js index aab1656436d..13c3de34a53 100644 --- a/lib/config/defaults.js +++ b/lib/config/defaults.js @@ -124,7 +124,7 @@ const A = (obj, prop, factory) => { if (value === undefined) { obj[prop] = factory(); } else if (Array.isArray(value)) { - /** @type {any[] | undefined} */ + /** @type {EXPECTED_ANY[] | undefined} */ let newArray; for (let i = 0; i < value.length; i++) { const item = value[i]; @@ -133,7 +133,9 @@ const A = (obj, prop, factory) => { newArray = value.slice(0, i); obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray)); } - const items = /** @type {any[]} */ (/** @type {unknown} */ (factory())); + const items = /** @type {EXPECTED_ANY[]} */ ( + /** @type {unknown} */ (factory()) + ); if (items !== undefined) { for (const item of items) { newArray.push(item); diff --git a/lib/css/CssGenerator.js b/lib/css/CssGenerator.js index cc1d4719fcf..b64e3e26c00 100644 --- a/lib/css/CssGenerator.js +++ b/lib/css/CssGenerator.js @@ -93,9 +93,9 @@ class CssGenerator extends Generator { * @param {Dependency} dependency dependency */ const handleDependency = dependency => { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); + const constructor = + /** @type {new (...args: EXPECTED_ANY[]) => Dependency} */ + (dependency.constructor); const template = generateContext.dependencyTemplates.get(constructor); if (!template) { throw new Error( diff --git a/lib/css/CssParser.js b/lib/css/CssParser.js index bcb0983566d..e6a72aafc88 100644 --- a/lib/css/CssParser.js +++ b/lib/css/CssParser.js @@ -1140,7 +1140,7 @@ class CssParser extends Parser { if (comments.length === 0) { return EMPTY_COMMENT_OPTIONS; } - /** @type {Record } */ + /** @type {Record } */ const options = {}; /** @type {(Error & { comment: Comment })[]} */ const errors = []; diff --git a/lib/debug/ProfilingPlugin.js b/lib/debug/ProfilingPlugin.js index 83e363fc17c..9f2d445a0d0 100644 --- a/lib/debug/ProfilingPlugin.js +++ b/lib/debug/ProfilingPlugin.js @@ -390,6 +390,11 @@ const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => { ); }; +/** + * @param {string} instance instance + * @param {Trace} tracer tracer + * @returns {TODO} interceptor + */ const makeInterceptorFor = (instance, tracer) => hookName => ({ register: tapInfo => { const { name, type, fn } = tapInfo; diff --git a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js index fb4bdd33fd1..95d4507e273 100644 --- a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +++ b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js @@ -102,7 +102,7 @@ class ExportMode { this.ignored = null; // for "dynamic-reexport" | "empty-star": - /** @type {ExportModeHidden | null} */ + /** @type {ExportModeHidden | undefined | null} */ this.hidden = null; // for "missing": @@ -1055,7 +1055,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS this.getReexportFragment( module, "reexport default from dynamic", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), importVar, null, runtimeRequirements @@ -1067,7 +1069,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS initFragments.push( ...this.getReexportFakeNamespaceObjectFragments( module, - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), importVar, mode.fakeType, runtimeRequirements @@ -1080,7 +1084,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS this.getReexportFragment( module, "reexport non-default export from non-harmony", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), "undefined", "", runtimeRequirements @@ -1093,7 +1099,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS this.getReexportFragment( module, "reexport default export from named module", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), importVar, "", runtimeRequirements @@ -1106,7 +1114,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS this.getReexportFragment( module, "reexport module object", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), importVar, "", runtimeRequirements diff --git a/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/lib/dependencies/HarmonyImportDependencyParserPlugin.js index c5af07549ef..680a9b1da45 100644 --- a/lib/dependencies/HarmonyImportDependencyParserPlugin.js +++ b/lib/dependencies/HarmonyImportDependencyParserPlugin.js @@ -389,17 +389,18 @@ module.exports = class HarmonyImportDependencyParserPlugin { } const dependencies = requests.map(request => { const dep = new HarmonyAcceptImportDependency(request); - dep.loc = expr.loc; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); parser.state.module.addDependency(dep); return dep; }); if (dependencies.length > 0) { const dep = new HarmonyAcceptDependency( - expr.range, + /** @type {Range} */ + (expr.range), dependencies, true ); - dep.loc = expr.loc; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); parser.state.module.addDependency(dep); } } @@ -413,17 +414,18 @@ module.exports = class HarmonyImportDependencyParserPlugin { } const dependencies = requests.map(request => { const dep = new HarmonyAcceptImportDependency(request); - dep.loc = expr.loc; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); parser.state.module.addDependency(dep); return dep; }); if (dependencies.length > 0) { const dep = new HarmonyAcceptDependency( - expr.range, + /** @type {Range} */ + (expr.range), dependencies, false ); - dep.loc = expr.loc; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); parser.state.module.addDependency(dep); } } diff --git a/lib/javascript/JavascriptGenerator.js b/lib/javascript/JavascriptGenerator.js index 51a719a0aab..3584f1abdad 100644 --- a/lib/javascript/JavascriptGenerator.js +++ b/lib/javascript/JavascriptGenerator.js @@ -190,9 +190,9 @@ class JavascriptGenerator extends Generator { * @returns {void} */ sourceDependency(module, dependency, initFragments, source, generateContext) { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); + const constructor = + /** @type {new (...args: EXPECTED_ANY[]) => Dependency} */ + (dependency.constructor); const template = generateContext.dependencyTemplates.get(constructor); if (!template) { throw new Error( diff --git a/lib/javascript/JavascriptParser.js b/lib/javascript/JavascriptParser.js index 580728ab814..6a3a901581f 100644 --- a/lib/javascript/JavascriptParser.js +++ b/lib/javascript/JavascriptParser.js @@ -249,25 +249,25 @@ class JavascriptParser extends Parser { constructor(sourceType = "auto") { super(); this.hooks = Object.freeze({ - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluate: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluateDefinedIdentifier: new HookMap( () => new SyncBailHook(["expression"]) ), - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluateNewExpression: new HookMap( () => new SyncBailHook(["expression"]) ), - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluateCallExpression: new HookMap( () => new SyncBailHook(["expression"]) ), - /** @type {HookMap>} */ + /** @type {HookMap>} */ evaluateCallExpressionMember: new HookMap( () => new SyncBailHook(["expression", "param"]) ), @@ -552,7 +552,7 @@ class JavascriptParser extends Parser { const left = this.evaluateExpression(expr.left); let returnRight = false; - /** @type {boolean|undefined} */ + /** @type {boolean | undefined} */ let allowedRight; if (expr.operator === "&&") { const leftAsBool = left.asBool(); @@ -2669,7 +2669,7 @@ class JavascriptParser extends Parser { shorthand: this.scope.inShorthand }); } else { - const id = this.evaluateExpression(/** @type {TODO} */ (key)); + const id = this.evaluateExpression(key); const str = id.asString(); if (str) { props.add({ @@ -3691,7 +3691,7 @@ class JavascriptParser extends Parser { * @template T * @template R * @param {HookMap>} hookMap hooks the should be called - * @param {TODO} expr expression + * @param {Expression | Super} expr expression * @param {AsArray} args args for the hook * @returns {R | undefined} result of hook */ @@ -3709,7 +3709,7 @@ class JavascriptParser extends Parser { * @template T * @template R * @param {HookMap>} hookMap hooks the should be called - * @param {MemberExpression} expr expression info + * @param {Expression | Super} expr expression info * @param {(function(string, string | ScopeInfo | VariableInfo, function(): string[]): any) | undefined} fallback callback when variable in not handled by hooks * @param {(function(string): any) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook @@ -4529,7 +4529,7 @@ class JavascriptParser extends Parser { /** * @param {string} name name - * @param {TODO} tag tag info + * @param {symbol} tag tag info * @returns {TODO} tag data */ getTagData(name, tag) { @@ -4545,7 +4545,7 @@ class JavascriptParser extends Parser { /** * @param {string} name name - * @param {TODO} tag tag info + * @param {symbol} tag tag info * @param {TODO=} data data */ tagVariable(name, tag, data) { @@ -4654,7 +4654,7 @@ class JavascriptParser extends Parser { if (comments.length === 0) { return EMPTY_COMMENT_OPTIONS; } - /** @type {Record } */ + /** @type {Record } */ const options = {}; /** @type {(Error & { comment: Comment })[]} */ const errors = []; @@ -4689,7 +4689,7 @@ class JavascriptParser extends Parser { } /** - * @param {MemberExpression} expression a member expression + * @param {Expression | Super} expression a member expression * @returns {{ members: string[], object: Expression | Super, membersOptionals: boolean[], memberRanges: Range[] }} member names (reverse order) and remaining object */ extractMemberExpressionChain(expression) { @@ -4742,7 +4742,7 @@ class JavascriptParser extends Parser { /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} ExpressionExpressionInfo */ /** - * @param {MemberExpression} expression a member expression + * @param {Expression | Super} expression a member expression * @param {number} allowedTypes which types should be returned, presented in bit mask * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info */ diff --git a/lib/logging/Logger.js b/lib/logging/Logger.js index a19297d8822..910b16f78e8 100644 --- a/lib/logging/Logger.js +++ b/lib/logging/Logger.js @@ -37,7 +37,7 @@ const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); class WebpackLogger { /** - * @param {function(LogTypeEnum, any[]=): void} log log function + * @param {function(LogTypeEnum, EXPECTED_ANY[]=): void} log log function * @param {function(string | function(): string): WebpackLogger} getChildLogger function to create child logger */ constructor(log, getChildLogger) { @@ -46,43 +46,43 @@ class WebpackLogger { } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ error(...args) { this[LOG_SYMBOL](LogType.error, args); } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ warn(...args) { this[LOG_SYMBOL](LogType.warn, args); } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ info(...args) { this[LOG_SYMBOL](LogType.info, args); } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ log(...args) { this[LOG_SYMBOL](LogType.log, args); } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ debug(...args) { this[LOG_SYMBOL](LogType.debug, args); } /** - * @param {any} assertion assertion - * @param {...any} args args + * @param {EXPECTED_ANY} assertion assertion + * @param {...EXPECTED_ANY} args args */ assert(assertion, ...args) { if (!assertion) { @@ -99,21 +99,21 @@ class WebpackLogger { } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ status(...args) { this[LOG_SYMBOL](LogType.status, args); } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ group(...args) { this[LOG_SYMBOL](LogType.group, args); } /** - * @param {...any} args args + * @param {...EXPECTED_ANY} args args */ groupCollapsed(...args) { this[LOG_SYMBOL](LogType.groupCollapsed, args); diff --git a/lib/logging/createConsoleLogger.js b/lib/logging/createConsoleLogger.js index 068e8057226..3b8ffd83897 100644 --- a/lib/logging/createConsoleLogger.js +++ b/lib/logging/createConsoleLogger.js @@ -12,24 +12,24 @@ const { LogType } = require("./Logger"); /** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ /** @typedef {function(string): boolean} FilterFunction */ -/** @typedef {function(string, LogTypeEnum, any[]=): void} LoggingFunction */ +/** @typedef {function(string, LogTypeEnum, EXPECTED_ANY[]=): void} LoggingFunction */ /** * @typedef {object} LoggerConsole * @property {function(): void} clear * @property {function(): void} trace - * @property {(...args: any[]) => void} info - * @property {(...args: any[]) => void} log - * @property {(...args: any[]) => void} warn - * @property {(...args: any[]) => void} error - * @property {(...args: any[]) => void=} debug - * @property {(...args: any[]) => void=} group - * @property {(...args: any[]) => void=} groupCollapsed - * @property {(...args: any[]) => void=} groupEnd - * @property {(...args: any[]) => void=} status - * @property {(...args: any[]) => void=} profile - * @property {(...args: any[]) => void=} profileEnd - * @property {(...args: any[]) => void=} logTime + * @property {(...args: EXPECTED_ANY[]) => void} info + * @property {(...args: EXPECTED_ANY[]) => void} log + * @property {(...args: EXPECTED_ANY[]) => void} warn + * @property {(...args: EXPECTED_ANY[]) => void} error + * @property {(...args: EXPECTED_ANY[]) => void=} debug + * @property {(...args: EXPECTED_ANY[]) => void=} group + * @property {(...args: EXPECTED_ANY[]) => void=} groupCollapsed + * @property {(...args: EXPECTED_ANY[]) => void=} groupEnd + * @property {(...args: EXPECTED_ANY[]) => void=} status + * @property {(...args: EXPECTED_ANY[]) => void=} profile + * @property {(...args: EXPECTED_ANY[]) => void=} profileEnd + * @property {(...args: EXPECTED_ANY[]) => void=} logTime */ /** @@ -95,7 +95,7 @@ module.exports = ({ level = "info", debug = false, console }) => { /** * @param {string} name name of the logger * @param {LogTypeEnum} type type of the log entry - * @param {any[]=} args arguments of the log entry + * @param {EXPECTED_ANY[]=} args arguments of the log entry * @returns {void} */ const logger = (name, type, args) => { diff --git a/lib/logging/truncateArgs.js b/lib/logging/truncateArgs.js index d7f1dfbb559..148ac7ae12b 100644 --- a/lib/logging/truncateArgs.js +++ b/lib/logging/truncateArgs.js @@ -16,7 +16,7 @@ const arraySum = array => { }; /** - * @param {any[]} args items to be truncated + * @param {EXPECTED_ANY[]} args items to be truncated * @param {number} maxLength maximum length of args including spaces between * @returns {string[]} truncated args */ diff --git a/lib/node/nodeConsole.js b/lib/node/nodeConsole.js index dd179658f20..9a1125ee543 100644 --- a/lib/node/nodeConsole.js +++ b/lib/node/nodeConsole.js @@ -67,7 +67,7 @@ module.exports = ({ colors, appendOnly, stream }) => { * @param {string} prefix prefix * @param {string} colorPrefix color prefix * @param {string} colorSuffix color suffix - * @returns {(function(...any[]): void)} function to write with colors + * @returns {(function(...EXPECTED_ANY[]): void)} function to write with colors */ const writeColored = (prefix, colorPrefix, colorSuffix) => diff --git a/lib/optimize/ConcatenatedModule.js b/lib/optimize/ConcatenatedModule.js index f5e2f02ba17..e10b2d0f1fd 100644 --- a/lib/optimize/ConcatenatedModule.js +++ b/lib/optimize/ConcatenatedModule.js @@ -139,7 +139,7 @@ if (!ReferencerClass.prototype.PropertyDefinition) { * @property {number} index * @property {Program | undefined} ast * @property {Source | undefined} internalSource - * @property {ReplaceSource} source + * @property {ReplaceSource | undefined} source * @property {InitFragment[]=} chunkInitFragments * @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements * @property {Scope | undefined} globalScope @@ -176,7 +176,7 @@ if (!ReferencerClass.prototype.PropertyDefinition) { * @typedef {object} ReferenceToModuleInfo * @property {"reference"} type * @property {RuntimeSpec | boolean} runtimeCondition - * @property {ConcatenatedModuleInfo | ExternalModuleInfo} target + * @property {ModuleInfo} target */ /** @@ -1251,7 +1251,8 @@ class ConcatenatedModule extends Module { ); switch (info.type) { case "concatenated": { - for (const variable of info.moduleScope.variables) { + const variables = /** @type {Scope} */ (info.moduleScope).variables; + for (const variable of variables) { const name = variable.name; const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( usedNamesInScopeInfo, @@ -1277,7 +1278,7 @@ class ConcatenatedModule extends Module { allUsedNames.add(newName); info.internalNames.set(name, newName); topLevelDeclarations.add(newName); - const source = info.source; + const source = /** @type {ReplaceSource} */ (info.source); const allIdentifiers = new Set( references.map(r => r.identifier).concat(variable.identifiers) ); @@ -1409,7 +1410,7 @@ class ConcatenatedModule extends Module { match.asiSafe ); const r = /** @type {Range} */ (reference.identifier.range); - const source = info.source; + const source = /** @type {ReplaceSource} */ (info.source); // range is extended by 2 chars to cover the appended "._" source.replace(r[0], r[1] + 1, finalName); } @@ -1605,7 +1606,7 @@ ${defineGetters}` result.add( `\n;// ${info.module.readableIdentifier(requestShortener)}\n` ); - result.add(info.source); + result.add(/** @type {ReplaceSource} */ (info.source)); if (info.chunkInitFragments) { for (const f of info.chunkInitFragments) chunkInitFragments.push(f); } diff --git a/lib/optimize/LimitChunkCountPlugin.js b/lib/optimize/LimitChunkCountPlugin.js index fc555e09aad..9b18c9b3b27 100644 --- a/lib/optimize/LimitChunkCountPlugin.js +++ b/lib/optimize/LimitChunkCountPlugin.js @@ -57,7 +57,7 @@ class LimitChunkCountPlugin { */ constructor(options) { validate(options); - this.options = options; + this.options = /** @type {LimitChunkCountPluginOptions} */ (options); } /** @@ -74,9 +74,7 @@ class LimitChunkCountPlugin { }, chunks => { const chunkGraph = compilation.chunkGraph; - const maxChunks = - /** @type {LimitChunkCountPluginOptions} */ - (options).maxChunks; + const maxChunks = options.maxChunks; if (!maxChunks) return; if (maxChunks < 1) return; if (compilation.chunks.size <= maxChunks) return; diff --git a/lib/stats/DefaultStatsFactoryPlugin.js b/lib/stats/DefaultStatsFactoryPlugin.js index 162bdf9d803..bfc7fa28a9c 100644 --- a/lib/stats/DefaultStatsFactoryPlugin.js +++ b/lib/stats/DefaultStatsFactoryPlugin.js @@ -55,7 +55,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); */ /** @typedef {import("./StatsFactory")} StatsFactory */ /** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */ -/** @typedef {Record & KnownStatsCompilation} StatsCompilation */ +/** @typedef {Record & KnownStatsCompilation} StatsCompilation */ /** * @typedef {object} KnownStatsCompilation * @property {any=} env @@ -83,7 +83,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {Record=} logging */ -/** @typedef {Record & KnownStatsLogging} StatsLogging */ +/** @typedef {Record & KnownStatsLogging} StatsLogging */ /** * @typedef {object} KnownStatsLogging * @property {StatsLoggingEntry[]} entries @@ -91,7 +91,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {boolean} debug */ -/** @typedef {Record & KnownStatsLoggingEntry} StatsLoggingEntry */ +/** @typedef {Record & KnownStatsLoggingEntry} StatsLoggingEntry */ /** * @typedef {object} KnownStatsLoggingEntry * @property {string} type @@ -102,7 +102,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {number=} time */ -/** @typedef {Record & KnownStatsAsset} StatsAsset */ +/** @typedef {Record & KnownStatsAsset} StatsAsset */ /** * @typedef {object} KnownStatsAsset * @property {string} type @@ -123,11 +123,11 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {boolean=} isOverSizeLimit */ -/** @typedef {Record & KnownStatsChunkGroup} StatsChunkGroup */ +/** @typedef {Record & KnownStatsChunkGroup} StatsChunkGroup */ /** * @typedef {object} KnownStatsChunkGroup - * @property {string=} name - * @property {(string|number)[]=} chunks + * @property {(string | null)=} name + * @property {(string | number)[]=} chunks * @property {({ name: string, size?: number })[]=} assets * @property {number=} filteredAssets * @property {number=} assetsSize @@ -139,7 +139,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {boolean=} isOverSizeLimit */ -/** @typedef {Record & KnownStatsModule} StatsModule */ +/** @typedef {Record & KnownStatsModule} StatsModule */ /** * @typedef {object} KnownStatsModule * @property {string=} type @@ -183,7 +183,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {ReturnType=} source */ -/** @typedef {Record & KnownStatsProfile} StatsProfile */ +/** @typedef {Record & KnownStatsProfile} StatsProfile */ /** * @typedef {object} KnownStatsProfile * @property {number} total @@ -198,7 +198,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {number} dependencies */ -/** @typedef {Record & KnownStatsModuleIssuer} StatsModuleIssuer */ +/** @typedef {Record & KnownStatsModuleIssuer} StatsModuleIssuer */ /** * @typedef {object} KnownStatsModuleIssuer * @property {string} identifier @@ -207,7 +207,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {StatsProfile} profile */ -/** @typedef {Record & KnownStatsModuleReason} StatsModuleReason */ +/** @typedef {Record & KnownStatsModuleReason} StatsModuleReason */ /** * @typedef {object} KnownStatsModuleReason * @property {string | null} moduleIdentifier @@ -224,7 +224,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {(string | number | null)=} resolvedModuleId */ -/** @typedef {Record & KnownStatsChunk} StatsChunk */ +/** @typedef {Record & KnownStatsChunk} StatsChunk */ /** * @typedef {object} KnownStatsChunk * @property {boolean} rendered @@ -250,7 +250,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {StatsChunkOrigin[]=} origins */ -/** @typedef {Record & KnownStatsChunkOrigin} StatsChunkOrigin */ +/** @typedef {Record & KnownStatsChunkOrigin} StatsChunkOrigin */ /** * @typedef {object} KnownStatsChunkOrigin * @property {string} module @@ -261,7 +261,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {(string | number)=} moduleId */ -/** @typedef { Record & KnownStatsModuleTraceItem} StatsModuleTraceItem */ +/** @typedef { Record & KnownStatsModuleTraceItem} StatsModuleTraceItem */ /** * @typedef {object} KnownStatsModuleTraceItem * @property {string=} originIdentifier @@ -273,13 +273,13 @@ const { makePathsRelative, parseResource } = require("../util/identifier"); * @property {(string|number)=} moduleId */ -/** @typedef {Record & KnownStatsModuleTraceDependency} StatsModuleTraceDependency */ +/** @typedef {Record & KnownStatsModuleTraceDependency} StatsModuleTraceDependency */ /** * @typedef {object} KnownStatsModuleTraceDependency * @property {string=} loc */ -/** @typedef {Record & KnownStatsError} StatsError */ +/** @typedef {Record & KnownStatsError} StatsError */ /** * @typedef {object} KnownStatsError * @property {string} message @@ -2370,8 +2370,9 @@ const sortOrderRegular = field => { }; /** + * @template T * @param {string} field field name - * @returns {function(object, object): 0 | 1 | -1} comparators + * @returns {function(T, T): 0 | 1 | -1} comparators */ const sortByField = field => { if (!field) { diff --git a/lib/stats/StatsFactory.js b/lib/stats/StatsFactory.js index c32574693b4..b668369ea1d 100644 --- a/lib/stats/StatsFactory.js +++ b/lib/stats/StatsFactory.js @@ -129,7 +129,7 @@ class StatsFactory { * @param {Caches} cache cache * @param {string} type type * @param {function(H): R | void} fn fn - * @returns {R | undefined} hook + * @returns {R | void} hook * @private */ _forEachLevel(hookMap, cache, type, fn) { diff --git a/lib/stats/StatsPrinter.js b/lib/stats/StatsPrinter.js index 3679a88cae0..99270618389 100644 --- a/lib/stats/StatsPrinter.js +++ b/lib/stats/StatsPrinter.js @@ -67,7 +67,7 @@ const { HookMap, SyncWaterfallHook, SyncBailHook } = require("tapable"); * @property {(message: string) => string=} formatError */ -/** @typedef {Record & KnownStatsPrinterColorFn & KnownStatsPrinterFormaters & KnownStatsPrinterContext} StatsPrinterContext */ +/** @typedef {Record & KnownStatsPrinterColorFn & KnownStatsPrinterFormaters & KnownStatsPrinterContext} StatsPrinterContext */ /** @typedef {any} PrintObject */ /** @@ -148,7 +148,7 @@ class StatsPrinter { * @param {HM} hookMap hook map * @param {string} type type * @param {function(H): R | void} fn fn - * @returns {R | undefined} hook + * @returns {R | void} hook */ _forEachLevel(hookMap, type, fn) { for (const hook of this._getAllLevelHooks(hookMap, type)) { diff --git a/lib/util/create-schema-validation.js b/lib/util/create-schema-validation.js index 79b2d1d9a63..4f12c8e69af 100644 --- a/lib/util/create-schema-validation.js +++ b/lib/util/create-schema-validation.js @@ -17,12 +17,12 @@ const getValidate = memoize(() => require("schema-utils").validate); * @param {(function(T): boolean) | undefined} check check * @param {() => JsonObject} getSchema get schema fn * @param {ValidationErrorConfiguration} options options - * @returns {function(T): void} validate + * @returns {function(T=): void} validate */ const createSchemaValidation = (check, getSchema, options) => { getSchema = memoize(getSchema); return value => { - if (check && !check(value)) { + if (check && !check(/** @type {T} */ (value))) { getValidate()( getSchema(), /** @type {object | object[]} */ diff --git a/lib/util/fs.js b/lib/util/fs.js index df9a87481b5..14a18c6dc7b 100644 --- a/lib/util/fs.js +++ b/lib/util/fs.js @@ -372,7 +372,7 @@ const path = require("path"); * @typedef {object} StreamOptions * @property {(string | undefined)=} flags * @property {(BufferEncoding | undefined)} encoding - * @property {(number | any | undefined)=} fd + * @property {(number | EXPECTED_ANY | undefined)=} fd * @property {(number | undefined)=} mode * @property {(boolean | undefined)=} autoClose * @property {(boolean | undefined)=} emitClose @@ -382,12 +382,12 @@ const path = require("path"); /** * @typedef {object} FSImplementation - * @property {((...args: any[]) => any)=} open - * @property {((...args: any[]) => any)=} close + * @property {((...args: EXPECTED_ANY[]) => EXPECTED_ANY)=} open + * @property {((...args: EXPECTED_ANY[]) => EXPECTED_ANY)=} close */ /** - * @typedef {FSImplementation & { write: (...args: any[]) => any; close?: (...args: any[]) => any }} CreateWriteStreamFSImplementation + * @typedef {FSImplementation & { write: (...args: EXPECTED_ANY[]) => EXPECTED_ANY; close?: (...args: EXPECTED_ANY[]) => EXPECTED_ANY }} CreateWriteStreamFSImplementation */ /** diff --git a/types.d.ts b/types.d.ts index 2b2443190b4..b584db77bd5 100644 --- a/types.d.ts +++ b/types.d.ts @@ -5,6 +5,7 @@ */ import { Buffer } from "buffer"; +import { Scope } from "eslint-scope"; import { ArrayExpression, ArrayPattern, @@ -386,18 +387,18 @@ declare class AsyncDependenciesBlock extends DependenciesBlock { constructor( groupOptions: | null - | (RawChunkGroupOptions & { name?: string } & { + | (RawChunkGroupOptions & { name?: null | string } & { entryOptions?: EntryOptions; }), loc?: null | SyntheticDependencyLocation | RealDependencyLocation, request?: null | string ); - groupOptions: RawChunkGroupOptions & { name?: string } & { + groupOptions: RawChunkGroupOptions & { name?: null | string } & { entryOptions?: EntryOptions; }; loc?: null | SyntheticDependencyLocation | RealDependencyLocation; request?: null | string; - chunkName?: string; + chunkName?: null | string; module: any; } declare abstract class AsyncQueue { @@ -559,6 +560,7 @@ declare abstract class BasicEvaluatedExpression { getMembersOptionals?: () => boolean[]; getMemberRanges?: () => [number, number][]; expression?: + | Program | UnaryExpression | ArrayExpression | ArrowFunctionExpression @@ -617,7 +619,6 @@ declare abstract class BasicEvaluatedExpression { | MethodDefinition | PropertyDefinition | VariableDeclarator - | Program | SwitchCase | CatchClause | ObjectPattern @@ -625,13 +626,13 @@ declare abstract class BasicEvaluatedExpression { | RestElement | AssignmentPattern | Property + | Super | AssignmentProperty | ClassBody | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier - | Super | TemplateElement; isUnknown(): boolean; isNull(): boolean; @@ -782,6 +783,7 @@ declare abstract class BasicEvaluatedExpression { */ setExpression( expression?: + | Program | UnaryExpression | ArrayExpression | ArrowFunctionExpression @@ -840,7 +842,6 @@ declare abstract class BasicEvaluatedExpression { | MethodDefinition | PropertyDefinition | VariableDeclarator - | Program | SwitchCase | CatchClause | ObjectPattern @@ -848,13 +849,13 @@ declare abstract class BasicEvaluatedExpression { | RestElement | AssignmentPattern | Property + | Super | AssignmentProperty | ClassBody | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier - | Super | TemplateElement ): BasicEvaluatedExpression; } @@ -1308,7 +1309,7 @@ declare abstract class ChunkGroup { * returns the name of current ChunkGroup * sets a new name for current ChunkGroup */ - name?: string; + name?: null | string; /** * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's @@ -1397,7 +1398,7 @@ declare abstract class ChunkGroup { getModuleIndex: (module: Module) => undefined | number; getModuleIndex2: (module: Module) => undefined | number; } -type ChunkGroupOptions = RawChunkGroupOptions & { name?: string }; +type ChunkGroupOptions = RawChunkGroupOptions & { name?: null | string }; declare interface ChunkHashContext { /** * results of code generation @@ -1619,7 +1620,7 @@ declare interface CleanPluginCompilationHooks { /** * when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config */ - keep: SyncBailHook<[string], boolean>; + keep: SyncBailHook<[string], boolean | void>; } declare interface CodeGenerationContext { /** @@ -1800,7 +1801,7 @@ declare class Compilation { void >; afterOptimizeChunkModules: SyncHook<[Iterable, Iterable]>; - shouldRecord: SyncBailHook<[], undefined | boolean>; + shouldRecord: SyncBailHook<[], boolean | void>; additionalChunkRuntimeRequirements: SyncHook< [Chunk, Set, RuntimeRequirementsContext] >; @@ -1845,7 +1846,7 @@ declare class Compilation { recordHash: SyncHook<[any]>; record: SyncHook<[Compilation, any]>; beforeModuleAssets: SyncHook<[]>; - shouldGenerateChunkAssets: SyncBailHook<[], boolean>; + shouldGenerateChunkAssets: SyncBailHook<[], boolean | void>; beforeChunkAssets: SyncHook<[]>; additionalChunkAssets: FakeHook< Pick< @@ -1879,7 +1880,7 @@ declare class Compilation { >; afterProcessAssets: SyncHook<[CompilationAssets]>; processAdditionalAssets: AsyncSeriesHook<[CompilationAssets]>; - needAdditionalSeal: SyncBailHook<[], undefined | boolean>; + needAdditionalSeal: SyncBailHook<[], boolean | void>; afterSeal: AsyncSeriesHook<[]>; renderManifest: SyncWaterfallHook< [RenderManifestEntry[], RenderManifestOptions] @@ -1889,9 +1890,9 @@ declare class Compilation { moduleAsset: SyncHook<[Module, string]>; chunkAsset: SyncHook<[Chunk, string]>; assetPath: SyncWaterfallHook<[string, object, undefined | AssetInfo]>; - needAdditionalPass: SyncBailHook<[], boolean>; + needAdditionalPass: SyncBailHook<[], boolean | void>; childCompiler: SyncHook<[Compiler, string, number]>; - log: SyncBailHook<[string, LogEntry], true>; + log: SyncBailHook<[string, LogEntry], boolean | void>; processWarnings: SyncWaterfallHook<[WebpackError[]]>; processErrors: SyncWaterfallHook<[WebpackError[]]>; statsPreset: HookMap< @@ -1913,7 +1914,7 @@ declare class Compilation { resolverFactory: ResolverFactory; inputFileSystem: InputFileSystem; fileSystemInfo: FileSystemInfo; - valueCacheVersions: Map; + valueCacheVersions: Map>; requestShortener: RequestShortener; compilerPath: string; logger: WebpackLogger; @@ -2302,19 +2303,19 @@ declare interface CompilationHooksJavascriptModulesPlugin { renderRequire: SyncWaterfallHook<[string, RenderBootstrapContext]>; inlineInRuntimeBailout: SyncBailHook< [Module, RenderBootstrapContext], - string + string | void >; embedInRuntimeBailout: SyncBailHook<[Module, RenderContext], string | void>; strictRuntimeBailout: SyncBailHook<[RenderContext], string | void>; chunkHash: SyncHook<[Chunk, Hash, ChunkHashContext]>; - useSourceMap: SyncBailHook<[Chunk, RenderContext], boolean>; + useSourceMap: SyncBailHook<[Chunk, RenderContext], boolean | void>; } declare interface CompilationHooksModuleFederationPlugin { addContainerEntryDependency: SyncHook; addFederationRuntimeDependency: SyncHook; } declare interface CompilationHooksRealContentHashPlugin { - updateHash: SyncBailHook<[Buffer[], string], string>; + updateHash: SyncBailHook<[Buffer[], string], string | void>; } declare interface CompilationParams { normalModuleFactory: NormalModuleFactory; @@ -2324,7 +2325,7 @@ declare class Compiler { constructor(context: string, options?: WebpackOptionsNormalized); hooks: Readonly<{ initialize: SyncHook<[]>; - shouldEmit: SyncBailHook<[Compilation], undefined | boolean>; + shouldEmit: SyncBailHook<[Compilation], boolean | void>; done: AsyncSeriesHook<[Stats]>; afterDone: SyncHook<[Stats]>; additionalPass: AsyncSeriesHook<[]>; @@ -2349,12 +2350,15 @@ declare class Compiler { invalid: SyncHook<[null | string, number]>; watchClose: SyncHook<[]>; shutdown: AsyncSeriesHook<[]>; - infrastructureLog: SyncBailHook<[string, string, undefined | any[]], true>; + infrastructureLog: SyncBailHook< + [string, string, undefined | any[]], + true | void + >; environment: SyncHook<[]>; afterEnvironment: SyncHook<[]>; afterPlugins: SyncHook<[Compiler]>; afterResolvers: SyncHook<[Compiler]>; - entryOption: SyncBailHook<[string, EntryNormalized], boolean>; + entryOption: SyncBailHook<[string, EntryNormalized], boolean | void>; }>; webpack: typeof exports; name?: string; @@ -2391,14 +2395,7 @@ declare class Compiler { context: string; requestShortener: RequestShortener; cache: Cache; - moduleMemCaches?: Map< - Module, - { - buildInfo: BuildInfo; - references?: WeakMap; - memCache: WeakTupleMap; - } - >; + moduleMemCaches?: Map; compilerPath: string; running: boolean; idle: boolean; @@ -2447,19 +2444,27 @@ declare class ConcatSource extends Source { addAllSkipOptimizing(items: Source[]): void; } declare interface ConcatenatedModuleInfo { - index: number; + type: "concatenated"; module: Module; - - /** - * mapping from export name to symbol - */ - exportMap: Map; - - /** - * mapping from export name to symbol - */ - rawExportMap: Map; + index: number; + ast?: Program; + internalSource?: Source; + source?: ReplaceSource; + chunkInitFragments?: InitFragment[]; + runtimeRequirements?: ReadonlySet; + globalScope?: Scope; + moduleScope?: Scope; + internalNames: Map; + exportMap?: Map; + rawExportMap?: Map; namespaceExportSymbol?: string; + namespaceObjectName?: string; + interopNamespaceObjectUsed: boolean; + interopNamespaceObjectName?: string; + interopNamespaceObject2Used: boolean; + interopNamespaceObject2Name?: string; + interopDefaultAccessUsed: boolean; + interopDefaultAccessName?: string; } declare interface ConcatenationBailoutReasonContext { /** @@ -2975,7 +2980,7 @@ declare interface ContextModuleOptions { regExp: RegExp; namespaceObject?: boolean | "strict"; addon?: string; - chunkName?: string; + chunkName?: null | string; include?: null | RegExp; exclude?: null | RegExp; groupOptions?: RawChunkGroupOptions; @@ -4613,8 +4618,17 @@ declare class ExternalModule extends Module { ): void; } declare interface ExternalModuleInfo { - index: number; + type: "external"; module: Module; + runtimeCondition?: string | boolean | SortableSet; + index: number; + name?: string; + interopNamespaceObjectUsed: boolean; + interopNamespaceObjectName?: string; + interopNamespaceObject2Used: boolean; + interopNamespaceObject2Name?: string; + interopDefaultAccessUsed: boolean; + interopDefaultAccessName?: string; } type Externals = | string @@ -4712,7 +4726,7 @@ declare interface FSImplementation { close?: (...args: any[]) => any; } declare interface FactorizeModuleOptions { - currentProfile: ModuleProfile; + currentProfile?: ModuleProfile; factory: ModuleFactory; dependencies: Dependency[]; @@ -5155,8 +5169,43 @@ declare interface GroupOptions { targetGroupCount?: number; } declare interface HMRJavascriptParserHooks { - hotAcceptCallback: SyncBailHook<[any, string[]], void>; - hotAcceptWithoutCallback: SyncBailHook<[any, string[]], void>; + hotAcceptCallback: SyncBailHook< + [ + ( + | UnaryExpression + | ArrayExpression + | ArrowFunctionExpression + | AssignmentExpression + | AwaitExpression + | BinaryExpression + | SimpleCallExpression + | NewExpression + | ChainExpression + | ClassExpression + | ConditionalExpression + | FunctionExpression + | Identifier + | ImportExpression + | SimpleLiteral + | RegExpLiteral + | BigIntLiteral + | LogicalExpression + | MemberExpression + | MetaProperty + | ObjectExpression + | SequenceExpression + | TaggedTemplateExpression + | TemplateLiteral + | ThisExpression + | UpdateExpression + | YieldExpression + | SpreadElement + ), + string[] + ], + void + >; + hotAcceptWithoutCallback: SyncBailHook<[CallExpression, string[]], void>; } declare interface HandleModuleCreationOptions { factory: ModuleFactory; @@ -6456,12 +6505,68 @@ declare class JavascriptParser extends Parser { walkMetaProperty(metaProperty: MetaProperty): void; callHooksForExpression( hookMap: HookMap>, - expr: any, + expr: + | UnaryExpression + | ArrayExpression + | ArrowFunctionExpression + | AssignmentExpression + | AwaitExpression + | BinaryExpression + | SimpleCallExpression + | NewExpression + | ChainExpression + | ClassExpression + | ConditionalExpression + | FunctionExpression + | Identifier + | ImportExpression + | SimpleLiteral + | RegExpLiteral + | BigIntLiteral + | LogicalExpression + | MemberExpression + | MetaProperty + | ObjectExpression + | SequenceExpression + | TaggedTemplateExpression + | TemplateLiteral + | ThisExpression + | UpdateExpression + | YieldExpression + | Super, ...args: AsArray ): undefined | R; callHooksForExpressionWithFallback( hookMap: HookMap>, - expr: MemberExpression, + expr: + | UnaryExpression + | ArrayExpression + | ArrowFunctionExpression + | AssignmentExpression + | AwaitExpression + | BinaryExpression + | SimpleCallExpression + | NewExpression + | ChainExpression + | ClassExpression + | ConditionalExpression + | FunctionExpression + | Identifier + | ImportExpression + | SimpleLiteral + | RegExpLiteral + | BigIntLiteral + | LogicalExpression + | MemberExpression + | MetaProperty + | ObjectExpression + | SequenceExpression + | TaggedTemplateExpression + | TemplateLiteral + | ThisExpression + | UpdateExpression + | YieldExpression + | Super, fallback: | undefined | (( @@ -6669,8 +6774,8 @@ declare class JavascriptParser extends Parser { setAsiPosition(pos: number): void; unsetAsiPosition(pos: number): void; isStatementLevelExpression(expr: Expression): boolean; - getTagData(name: string, tag?: any): any; - tagVariable(name: string, tag?: any, data?: any): void; + getTagData(name: string, tag: symbol): any; + tagVariable(name: string, tag: symbol, data?: any): void; defineVariable(name: string): void; undefineVariable(name: string): void; isVariableDefined(name: string): boolean; @@ -6681,7 +6786,37 @@ declare class JavascriptParser extends Parser { options: null | Record; errors: null | (Error & { comment: Comment })[]; }; - extractMemberExpressionChain(expression: MemberExpression): { + extractMemberExpressionChain( + expression: + | UnaryExpression + | ArrayExpression + | ArrowFunctionExpression + | AssignmentExpression + | AwaitExpression + | BinaryExpression + | SimpleCallExpression + | NewExpression + | ChainExpression + | ClassExpression + | ConditionalExpression + | FunctionExpression + | Identifier + | ImportExpression + | SimpleLiteral + | RegExpLiteral + | BigIntLiteral + | LogicalExpression + | MemberExpression + | MetaProperty + | ObjectExpression + | SequenceExpression + | TaggedTemplateExpression + | TemplateLiteral + | ThisExpression + | UpdateExpression + | YieldExpression + | Super + ): { members: string[]; object: | UnaryExpression @@ -6719,7 +6854,35 @@ declare class JavascriptParser extends Parser { varName: string ): undefined | { name: string; info: string | VariableInfo }; getMemberExpressionInfo( - expression: MemberExpression, + expression: + | UnaryExpression + | ArrayExpression + | ArrowFunctionExpression + | AssignmentExpression + | AwaitExpression + | BinaryExpression + | SimpleCallExpression + | NewExpression + | ChainExpression + | ClassExpression + | ConditionalExpression + | FunctionExpression + | Identifier + | ImportExpression + | SimpleLiteral + | RegExpLiteral + | BigIntLiteral + | LogicalExpression + | MemberExpression + | MetaProperty + | ObjectExpression + | SequenceExpression + | TaggedTemplateExpression + | TemplateLiteral + | ThisExpression + | UpdateExpression + | YieldExpression + | Super, allowedTypes: number ): undefined | CallExpressionInfo | ExpressionExpressionInfo; getNameForExpression( @@ -7075,7 +7238,7 @@ declare interface KnownBuildInfo { contextDependencies?: LazySet; missingDependencies?: LazySet; buildDependencies?: LazySet; - valueDependencies?: Map; + valueDependencies?: Map>; hash?: any; assets?: Record; assetsInfo?: Map; @@ -7197,7 +7360,7 @@ declare interface KnownStatsChunk { origins?: StatsChunkOrigin[]; } declare interface KnownStatsChunkGroup { - name?: string; + name?: null | string; chunks?: (string | number)[]; assets?: { name: string; size?: number }[]; filteredAssets?: number; @@ -7712,7 +7875,7 @@ declare class LibraryTemplatePlugin { } declare class LimitChunkCountPlugin { constructor(options?: LimitChunkCountPluginOptions); - options?: LimitChunkCountPluginOptions; + options: LimitChunkCountPluginOptions; apply(compiler: Compiler): void; } declare interface LimitChunkCountPluginOptions { @@ -8723,6 +8886,11 @@ declare class ModuleGraphConnection { } type ModuleId = string | number; type ModuleInfo = ConcatenatedModuleInfo | ExternalModuleInfo; +declare interface ModuleMemCachesItem { + buildInfo: BuildInfo; + references?: WeakMap; + memCache: WeakTupleMap; +} declare interface ModuleObject { id: string; exports: any; @@ -9390,11 +9558,13 @@ declare abstract class NormalModuleFactory extends ModuleFactory { ResolveData ] >; - createParser: HookMap>; + createParser: HookMap>; parser: HookMap>; - createGenerator: HookMap>; + createGenerator: HookMap< + SyncBailHook<[GeneratorOptions], void | Generator> + >; generator: HookMap>; - createModuleClass: HookMap>; + createModuleClass: HookMap>; }>; resolverFactory: ResolverFactory; ruleSet: RuleSet; @@ -13027,7 +13197,7 @@ declare abstract class RuntimeTemplate { /** * name of the chunk referenced */ - chunkName?: string; + chunkName?: null | string; /** * reason information of the chunk */ @@ -13396,7 +13566,7 @@ declare abstract class RuntimeValue { get fileDependencies(): true | string[]; exec( parser: JavascriptParser, - valueCacheVersions: Map, + valueCacheVersions: Map>, key: string ): CodeValuePrimitive; getCacheVersion(): undefined | string; @@ -14075,46 +14245,37 @@ declare abstract class StatsFactory { type StatsFactoryContext = Record & KnownStatsFactoryContext; declare interface StatsFactoryHooks { extract: HookMap< - SyncBailHook<[ObjectForExtract, any, StatsFactoryContext], undefined> + SyncBailHook<[ObjectForExtract, any, StatsFactoryContext], void> >; filter: HookMap< - SyncBailHook< - [any, StatsFactoryContext, number, number], - undefined | boolean - > + SyncBailHook<[any, StatsFactoryContext, number, number], boolean | void> >; sort: HookMap< SyncBailHook< [((arg0?: any, arg1?: any) => 0 | 1 | -1)[], StatsFactoryContext], - undefined + void > >; filterSorted: HookMap< - SyncBailHook< - [any, StatsFactoryContext, number, number], - undefined | boolean - > + SyncBailHook<[any, StatsFactoryContext, number, number], boolean | void> >; groupResults: HookMap< - SyncBailHook<[GroupConfig[], StatsFactoryContext], undefined> + SyncBailHook<[GroupConfig[], StatsFactoryContext], void> >; sortResults: HookMap< SyncBailHook< [((arg0?: any, arg1?: any) => 0 | 1 | -1)[], StatsFactoryContext], - undefined + void > >; filterResults: HookMap< - SyncBailHook< - [any, StatsFactoryContext, number, number], - undefined | boolean - > + SyncBailHook<[any, StatsFactoryContext, number, number], boolean | void> >; merge: HookMap>; result: HookMap>; - getItemName: HookMap>; + getItemName: HookMap>; getItemFactory: HookMap< - SyncBailHook<[any, StatsFactoryContext], undefined | StatsFactory> + SyncBailHook<[any, StatsFactoryContext], void | StatsFactory> >; } type StatsLogging = Record & KnownStatsLogging; @@ -14576,12 +14737,14 @@ declare interface StatsOptions { declare interface StatsPrintHooks { sortElements: HookMap>; printElements: HookMap< - SyncBailHook<[PrintedElement[], StatsPrinterContext], undefined | string> + SyncBailHook<[PrintedElement[], StatsPrinterContext], string | void> + >; + sortItems: HookMap< + SyncBailHook<[any[], StatsPrinterContext], boolean | void> >; - sortItems: HookMap>; - getItemName: HookMap>; + getItemName: HookMap>; printItems: HookMap< - SyncBailHook<[string[], StatsPrinterContext], undefined | string> + SyncBailHook<[string[], StatsPrinterContext], string | void> >; print: HookMap>; result: HookMap>; @@ -14743,7 +14906,7 @@ declare interface UpdateHashContextGenerator { type UsageStateType = 0 | 1 | 2 | 3 | 4; type UsedName = string | false | string[]; type Value = string | number | boolean | RegExp; -type ValueCacheVersion = undefined | string | Set; +type ValueCacheVersion = string | Set; declare abstract class VariableInfo { declaredScope: ScopeInfo; freeName?: string | true;