From 568f28bb874a914d93062435d387336e6aff7a92 Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Mon, 12 Jun 2023 17:21:21 +0300 Subject: [PATCH 1/5] refactor(types): more --- lib/json/JsonGenerator.js | 1 + lib/serialization/ObjectMiddleware.js | 9 ++- lib/util/AsyncQueue.js | 6 +- lib/util/ParallelismFactorCalculator.js | 10 +++ lib/util/Semaphore.js | 2 +- lib/util/createHash.js | 39 +++++++++--- lib/util/deprecation.js | 13 +++- lib/util/deterministicGrouping.js | 61 +++++++++++++++---- lib/util/findGraphRoots.js | 6 +- lib/util/memoize.js | 6 +- lib/util/processAsyncTree.js | 8 ++- lib/util/registerExternalSerializer.js | 2 +- lib/util/runtime.js | 15 ++++- lib/util/smartGrouping.js | 2 +- .../AsyncWasmLoadingRuntimeModule.js | 6 +- lib/wasm-async/AsyncWebAssemblyParser.js | 8 ++- .../WasmChunkLoadingRuntimeModule.js | 19 ++++-- lib/wasm-sync/WasmFinalizeExportsPlugin.js | 4 +- lib/wasm-sync/WebAssemblyGenerator.js | 1 + lib/wasm-sync/WebAssemblyParser.js | 8 ++- lib/web/JsonpChunkLoadingRuntimeModule.js | 5 +- lib/webpack.js | 11 +++- .../ImportScriptsChunkLoadingRuntimeModule.js | 29 +++++---- types.d.ts | 12 ++-- 24 files changed, 209 insertions(+), 74 deletions(-) diff --git a/lib/json/JsonGenerator.js b/lib/json/JsonGenerator.js index d7074fc0ca7..2c8c49dedbe 100644 --- a/lib/json/JsonGenerator.js +++ b/lib/json/JsonGenerator.js @@ -172,6 +172,7 @@ class JsonGenerator extends Generator { ); } const exportsInfo = moduleGraph.getExportsInfo(module); + console.log(exportsInfo); /** @type {RawJsonData} */ let finalJson = typeof data === "object" && diff --git a/lib/serialization/ObjectMiddleware.js b/lib/serialization/ObjectMiddleware.js index 3635fa6544d..31890dfe819 100644 --- a/lib/serialization/ObjectMiddleware.js +++ b/lib/serialization/ObjectMiddleware.js @@ -107,7 +107,7 @@ const ESCAPE_UNDEFINED = false; const CURRENT_VERSION = 2; -/** @type {Map} */ +/** @type {Map} */ const serializers = new Map(); /** @type {Map} */ const serializerInversed = new Map(); @@ -158,7 +158,10 @@ if (exports.constructor !== Object) { } for (const { request, name, serializer } of serializers.values()) { - serializerInversed.set(`${request}/${name}`, serializer); + serializerInversed.set( + `${request}/${name}`, + /** @type {ObjectSerializer} */ (serializer) + ); } /** @type {Map boolean>} */ @@ -191,7 +194,7 @@ class ObjectMiddleware extends SerializerMiddleware { /** * @param {Constructor} Constructor the constructor * @param {string} request the request which will be required when deserializing - * @param {string} name the name to make multiple serializer unique when sharing a request + * @param {string | null} name the name to make multiple serializer unique when sharing a request * @param {ObjectSerializer} serializer the serializer * @returns {void} */ diff --git a/lib/util/AsyncQueue.js b/lib/util/AsyncQueue.js index 604337d1cec..feb69a7d5d1 100644 --- a/lib/util/AsyncQueue.js +++ b/lib/util/AsyncQueue.js @@ -70,7 +70,7 @@ class AsyncQueue { this._entries = new Map(); /** @type {ArrayQueue>} */ this._queued = new ArrayQueue(); - /** @type {AsyncQueue[]} */ + /** @type {AsyncQueue[] | undefined} */ this._children = undefined; this._activeTasks = 0; this._willEnsureProcessing = false; @@ -159,7 +159,9 @@ class AsyncQueue { */ invalidate(item) { const key = this._getKey(item); - const entry = this._entries.get(key); + const entry = + /** @type {AsyncQueueEntry} */ + (this._entries.get(key)); this._entries.delete(key); if (entry.state === QUEUED_STATE) { this._queued.delete(entry); diff --git a/lib/util/ParallelismFactorCalculator.js b/lib/util/ParallelismFactorCalculator.js index cbdda42f2ad..415ff3681a5 100644 --- a/lib/util/ParallelismFactorCalculator.js +++ b/lib/util/ParallelismFactorCalculator.js @@ -7,12 +7,22 @@ const binarySearchBounds = require("../util/binarySearchBounds"); +/** @typedef {function(number): void} Callback */ + class ParallelismFactorCalculator { constructor() { + /** @type {number[]} */ this._rangePoints = []; + /** @type {Callback[]} */ this._rangeCallbacks = []; } + /** + * @param {number} start range start + * @param {number} end range end + * @param {Callback} callback callback + * @returns {void} + */ range(start, end, callback) { if (start === end) return callback(1); this._rangePoints.push(start); diff --git a/lib/util/Semaphore.js b/lib/util/Semaphore.js index 52fdd30701c..68cd8898b30 100644 --- a/lib/util/Semaphore.js +++ b/lib/util/Semaphore.js @@ -44,7 +44,7 @@ class Semaphore { if (this.available > 0) { if (this.waiters.length > 0) { this.available--; - const callback = this.waiters.pop(); + const callback = /** @type {(function(): void)} */ (this.waiters.pop()); callback(); } } diff --git a/lib/util/createHash.js b/lib/util/createHash.js index 75087d99873..3bc0cd005c3 100644 --- a/lib/util/createHash.js +++ b/lib/util/createHash.js @@ -11,11 +11,14 @@ const BULK_SIZE = 2000; // We are using an object instead of a Map as this will stay static during the runtime // so access to it can be optimized by v8 +/** @type {Object>} */ const digestCaches = {}; +/** @typedef {function(): Hash} HashFactory */ + class BulkUpdateDecorator extends Hash { /** - * @param {Hash | function(): Hash} hashOrFactory function to create a hash + * @param {Hash | HashFactory} hashOrFactory function to create a hash * @param {string=} hashKey key for caching */ constructor(hashOrFactory, hashKey) { @@ -43,7 +46,8 @@ class BulkUpdateDecorator extends Hash { typeof data !== "string" || data.length > BULK_SIZE ) { - if (this.hash === undefined) this.hash = this.hashFactory(); + if (this.hash === undefined) + this.hash = /** @type {HashFactory} */ (this.hashFactory)(); if (this.buffer.length > 0) { this.hash.update(this.buffer); this.buffer = ""; @@ -52,7 +56,8 @@ class BulkUpdateDecorator extends Hash { } else { this.buffer += data; if (this.buffer.length > BULK_SIZE) { - if (this.hash === undefined) this.hash = this.hashFactory(); + if (this.hash === undefined) + this.hash = /** @type {HashFactory} */ (this.hashFactory)(); this.hash.update(this.buffer); this.buffer = ""; } @@ -77,7 +82,7 @@ class BulkUpdateDecorator extends Hash { } const cacheEntry = digestCache.get(buffer); if (cacheEntry !== undefined) return cacheEntry; - this.hash = this.hashFactory(); + this.hash = /** @type {HashFactory} */ (this.hashFactory)(); } if (buffer.length > 0) { this.hash.update(buffer); @@ -111,7 +116,9 @@ class DebugHash extends Hash { if (data.startsWith(prefix)) { data = Buffer.from(data.slice(prefix.length), "hex").toString(); } - this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`; + this.string += `[${data}](${ + /** @type {string} */ (new Error().stack).split("\n", 3)[2] + })\n`; return this; } @@ -125,9 +132,13 @@ class DebugHash extends Hash { } } +/** @type {typeof import("crypto") | undefined} */ let crypto = undefined; +/** @type {typeof import("./hash/xxhash64") | undefined} */ let createXXHash64 = undefined; +/** @type {typeof import("./hash/md4") | undefined} */ let createMd4 = undefined; +/** @type {typeof import("./hash/BatchedHash") | undefined} */ let BatchedHash = undefined; /** @@ -150,7 +161,9 @@ module.exports = algorithm => { BatchedHash = require("./hash/BatchedHash"); } } - return new BatchedHash(createXXHash64()); + return new /** @type {typeof import("./hash/BatchedHash")} */ ( + BatchedHash + )(createXXHash64()); case "md4": if (createMd4 === undefined) { createMd4 = require("./hash/md4"); @@ -158,14 +171,22 @@ module.exports = algorithm => { BatchedHash = require("./hash/BatchedHash"); } } - return new BatchedHash(createMd4()); + return new /** @type {typeof import("./hash/BatchedHash")} */ ( + BatchedHash + )(createMd4()); case "native-md4": if (crypto === undefined) crypto = require("crypto"); - return new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4"); + return new BulkUpdateDecorator( + () => /** @type {typeof import("crypto")} */ (crypto).createHash("md4"), + "md4" + ); default: if (crypto === undefined) crypto = require("crypto"); return new BulkUpdateDecorator( - () => crypto.createHash(algorithm), + () => + /** @type {typeof import("crypto")} */ (crypto).createHash( + /** @type {string} */ (algorithm) + ), algorithm ); } diff --git a/lib/util/deprecation.js b/lib/util/deprecation.js index f90a0faf907..35298d74077 100644 --- a/lib/util/deprecation.js +++ b/lib/util/deprecation.js @@ -78,7 +78,7 @@ exports.arrayToSetDeprecation = (set, name) => { ); /** * @deprecated - * @this {Set} + * @this {Set} * @returns {number} count */ set[method] = function () { @@ -101,7 +101,7 @@ exports.arrayToSetDeprecation = (set, name) => { ); /** * @deprecated - * @this {Set} + * @this {Set} * @returns {number} count */ set.push = function () { @@ -119,9 +119,13 @@ exports.arrayToSetDeprecation = (set, name) => { ); }; } + /** + * @param {number} index index + * @returns {any} value + */ const createIndexGetter = index => { /** - * @this {Set} a Set + * @this {Set} a Set * @returns {any} the value at this location */ const fn = function () { @@ -134,6 +138,9 @@ exports.arrayToSetDeprecation = (set, name) => { }; return fn; }; + /** + * @param {number} index index + */ const defineIndexGetter = index => { Object.defineProperty(set, index, { get: createIndexGetter(index), diff --git a/lib/util/deterministicGrouping.js b/lib/util/deterministicGrouping.js index 69f6a467c2e..97f266b58e6 100644 --- a/lib/util/deterministicGrouping.js +++ b/lib/util/deterministicGrouping.js @@ -94,7 +94,8 @@ const subtractSizeFrom = (total, size) => { }; /** - * @param {Iterable} nodes some nodes + * @template T + * @param {Iterable>} nodes some nodes * @returns {Record} total size */ const sumSize = nodes => { @@ -105,6 +106,11 @@ const sumSize = nodes => { return sum; }; +/** + * @param {Record} size size + * @param {Record} maxSize minimum size + * @returns {boolean} true, when size is too big + */ const isTooBig = (size, maxSize) => { for (const key of Object.keys(size)) { const s = size[key]; @@ -117,6 +123,11 @@ const isTooBig = (size, maxSize) => { return false; }; +/** + * @param {Record} size size + * @param {Record} minSize minimum size + * @returns {boolean} true, when size is too small + */ const isTooSmall = (size, minSize) => { for (const key of Object.keys(size)) { const s = size[key]; @@ -129,6 +140,11 @@ const isTooSmall = (size, minSize) => { return false; }; +/** + * @param {Record} size size + * @param {Record} minSize minimum size + * @returns {Set} set of types that are too small + */ const getTooSmallTypes = (size, minSize) => { const types = new Set(); for (const key of Object.keys(size)) { @@ -142,6 +158,12 @@ const getTooSmallTypes = (size, minSize) => { return types; }; +/** + * @template T + * @param {TODO} size size + * @param {Set} types types + * @returns {number} number of matching size types + */ const getNumberOfMatchingSizeTypes = (size, types) => { let i = 0; for (const key of Object.keys(size)) { @@ -150,6 +172,11 @@ const getNumberOfMatchingSizeTypes = (size, types) => { return i; }; +/** + * @param {Record} size size + * @param {Set} types types + * @returns {number} selective size sum + */ const selectiveSizeSum = (size, types) => { let sum = 0; for (const key of Object.keys(size)) { @@ -180,20 +207,20 @@ class Node { class Group { /** * @param {Node[]} nodes nodes - * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) + * @param {number[] | null} similarities similarities between the nodes (length = nodes.length - 1) * @param {Record=} size size of the group */ constructor(nodes, similarities, size) { this.nodes = nodes; this.similarities = similarities; this.size = size || sumSize(nodes); - /** @type {string} */ + /** @type {string | undefined} */ this.key = undefined; } /** - * @param {function(Node): boolean} filter filter function - * @returns {Node[]} removed nodes + * @param {function(Node): boolean} filter filter function + * @returns {Node[] | undefined} removed nodes */ popNodes(filter) { const newNodes = []; @@ -208,7 +235,7 @@ class Group { if (newNodes.length > 0) { newSimilarities.push( lastNode === this.nodes[i - 1] - ? this.similarities[i - 1] + ? /** @type {number[]} */ (this.similarities)[i - 1] : similarity(lastNode.key, node.key) ); } @@ -225,7 +252,8 @@ class Group { } /** - * @param {Iterable} nodes nodes + * @template T + * @param {Iterable>} nodes nodes * @returns {number[]} similarities */ const getSimilarities = nodes => { @@ -297,6 +325,11 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { if (initialNodes.length > 0) { const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); + /** + * @param {Group} group group + * @param {Record} consideredSize size of the group to consider + * @returns {boolean} true, if the group was modified + */ const removeProblematicNodes = (group, consideredSize = group.size) => { const problemTypes = getTooSmallTypes(consideredSize, minSize); if (problemTypes.size > 0) { @@ -347,7 +380,7 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { const queue = [initialGroup]; while (queue.length) { - const group = queue.pop(); + const group = /** @type {Group} */ (queue.pop()); // only groups bigger than maxSize need to be splitted if (!isTooBig(group.size, maxSize)) { result.push(group); @@ -428,7 +461,9 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { // rightSize ^^^^^^^^^^^^^^^ while (pos <= right + 1) { - const similarity = group.similarities[pos - 1]; + const similarity = /** @type {number[]} */ (group.similarities)[ + pos - 1 + ]; if ( similarity < bestSimilarity && !isTooSmall(leftSize, minSize) && @@ -458,7 +493,9 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { /** @type {number[]} */ const rightSimilarities = []; for (let i = right + 2; i < group.nodes.length; i++) { - rightSimilarities.push(group.similarities[i - 1]); + rightSimilarities.push( + /** @type {number[]} */ (group.similarities)[i - 1] + ); rightNodes.push(group.nodes[i]); } queue.push(new Group(rightNodes, rightSimilarities)); @@ -467,7 +504,9 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { /** @type {number[]} */ const leftSimilarities = []; for (let i = 1; i < left; i++) { - leftSimilarities.push(group.similarities[i - 1]); + leftSimilarities.push( + /** @type {number[]} */ (group.similarities)[i - 1] + ); leftNodes.push(group.nodes[i]); } queue.push(new Group(leftNodes, leftSimilarities)); diff --git a/lib/util/findGraphRoots.js b/lib/util/findGraphRoots.js index 272bdf85d87..4e3c1cb2722 100644 --- a/lib/util/findGraphRoots.js +++ b/lib/util/findGraphRoots.js @@ -109,7 +109,9 @@ module.exports = (items, getDependencies) => { // Are there still edges unprocessed in the current node? if (topOfStack.openEdges.length > 0) { // Process one dependency - const dependency = topOfStack.openEdges.pop(); + const dependency = + /** @type {Node} */ + (topOfStack.openEdges.pop()); switch (dependency.marker) { case NO_MARKER: // dependency has not be visited yet @@ -169,7 +171,7 @@ module.exports = (items, getDependencies) => { // so it's not really a root cycle // remove the cycle from the root cycles // and convert it to a normal node - rootCycles.delete(dependency.cycle); + rootCycles.delete(/** @type {Cycle} */ (dependency.cycle)); dependency.marker = DONE_MARKER; break; // DONE_MARKER: nothing to do, don't recurse into dependencies diff --git a/lib/util/memoize.js b/lib/util/memoize.js index 981b5318882..5a73ee75ce3 100644 --- a/lib/util/memoize.js +++ b/lib/util/memoize.js @@ -13,18 +13,18 @@ */ const memoize = fn => { let cache = false; - /** @type {T} */ + /** @type {T | undefined} */ let result = undefined; return () => { if (cache) { - return result; + return /** @type {T} */ (result); } else { result = fn(); cache = true; // Allow to clean up memory for fn // and all dependent resources fn = undefined; - return result; + return /** @type {T} */ (result); } }; }; diff --git a/lib/util/processAsyncTree.js b/lib/util/processAsyncTree.js index f57ac496bf1..38253865231 100644 --- a/lib/util/processAsyncTree.js +++ b/lib/util/processAsyncTree.js @@ -21,6 +21,9 @@ const processAsyncTree = (items, concurrency, processor, callback) => { let finished = false; let processScheduled = true; + /** + * @param {T} item item + */ const push = item => { queue.push(item); if (!processScheduled && processing < concurrency) { @@ -29,6 +32,9 @@ const processAsyncTree = (items, concurrency, processor, callback) => { } }; + /** + * @param {E | null | undefined} err error + */ const processorCallback = err => { processing--; if (err && !finished) { @@ -46,7 +52,7 @@ const processAsyncTree = (items, concurrency, processor, callback) => { if (finished) return; while (processing < concurrency && queue.length > 0) { processing++; - const item = queue.pop(); + const item = /** @type {T} */ (queue.pop()); processor(item, push, processorCallback); } processScheduled = false; diff --git a/lib/util/registerExternalSerializer.js b/lib/util/registerExternalSerializer.js index 4b45428f8ec..21cf714a180 100644 --- a/lib/util/registerExternalSerializer.js +++ b/lib/util/registerExternalSerializer.js @@ -26,7 +26,7 @@ const { /** @typedef {import("./serialization").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("./serialization").ObjectSerializerContext} ObjectSerializerContext */ -/** @typedef {ObjectSerializerContext & { writeLazy?: (any) => void }} WebpackObjectSerializerContext */ +/** @typedef {ObjectSerializerContext & { writeLazy?: (value: any) => void }} WebpackObjectSerializerContext */ const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer"; diff --git a/lib/util/runtime.js b/lib/util/runtime.js index cdc29c24db7..bb7106127c3 100644 --- a/lib/util/runtime.js +++ b/lib/util/runtime.js @@ -434,7 +434,7 @@ class RuntimeSpecMap { /** * @param {RuntimeSpec} runtime the runtimes - * @returns {T} value + * @returns {T | undefined} value */ get(runtime) { switch (this._mode) { @@ -517,6 +517,9 @@ class RuntimeSpecMap { } } + /** + * @param {RuntimeSpec} runtime the runtimes + */ delete(runtime) { switch (this._mode) { case 0: @@ -593,6 +596,9 @@ class RuntimeSpecMap { exports.RuntimeSpecMap = RuntimeSpecMap; class RuntimeSpecSet { + /** + * @param {Iterable=} iterable iterable + */ constructor(iterable) { /** @type {Map} */ this._map = new Map(); @@ -603,10 +609,17 @@ class RuntimeSpecSet { } } + /** + * @param {RuntimeSpec} runtime runtime + */ add(runtime) { this._map.set(getRuntimeKey(runtime), runtime); } + /** + * @param {RuntimeSpec} runtime runtime + * @returns {boolean} true, when the runtime exists + */ has(runtime) { return this._map.has(getRuntimeKey(runtime)); } diff --git a/lib/util/smartGrouping.js b/lib/util/smartGrouping.js index ec348ad15e9..ae4132a60f1 100644 --- a/lib/util/smartGrouping.js +++ b/lib/util/smartGrouping.js @@ -110,7 +110,7 @@ const smartGrouping = (items, groupConfigs) => { /** @type {(T | R)[]} */ const results = []; for (;;) { - /** @type {Group} */ + /** @type {Group | undefined} */ let bestGroup = undefined; let bestGroupSize = -1; let bestGroupItems = undefined; diff --git a/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js b/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js index d2dfe0cd262..a5194ab22a4 100644 --- a/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +++ b/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js @@ -9,6 +9,9 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ + /** * @typedef {Object} AsyncWasmLoadingRuntimeModuleOptions * @property {function(string): string} generateLoadBinaryCode @@ -29,7 +32,8 @@ class AsyncWasmLoadingRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation, chunk } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); const { outputOptions, runtimeTemplate } = compilation; const fn = RuntimeGlobals.instantiateWasm; const wasmModuleSrcPath = compilation.getPath( diff --git a/lib/wasm-async/AsyncWebAssemblyParser.js b/lib/wasm-async/AsyncWebAssemblyParser.js index 0773981e716..0b9c256c0d9 100644 --- a/lib/wasm-async/AsyncWebAssemblyParser.js +++ b/lib/wasm-async/AsyncWebAssemblyParser.js @@ -11,6 +11,7 @@ const Parser = require("../Parser"); const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); +/** @typedef {import("../Module").BuildInfo} BuildInfo */ /** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ @@ -43,9 +44,10 @@ class WebAssemblyParser extends Parser { } // flag it as async module - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "namespace"; - state.module.buildMeta.async = true; + const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo); + buildInfo.strict = true; + buildInfo.exportsType = "namespace"; + buildInfo.async = true; // parse it const program = decode(source, decoderOpts); diff --git a/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js b/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js index 1aa295a4c21..1d6a5f2eeee 100644 --- a/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +++ b/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js @@ -10,6 +10,7 @@ const Template = require("../Template"); const { compareModulesByIdentifier } = require("../util/comparators"); const WebAssemblyUtils = require("./WebAssemblyUtils"); +/** @typedef {import("@webassemblyjs/ast").Signature} Signature */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Compilation")} Compilation */ @@ -91,9 +92,11 @@ const generateImportObject = ( value: `${instanceVar}[${JSON.stringify(usedName)}]` }); } else { - const params = description.signature.params.map( - (param, k) => "p" + k + param.valtype - ); + const params = + /** @type {Signature} */ + (description.signature).params.map( + (param, k) => "p" + k + param.valtype + ); const mod = `${RuntimeGlobals.moduleCache}[${JSON.stringify( chunkGraph.getModuleId(importedModule) @@ -130,6 +133,7 @@ const generateImportObject = ( "};" ]; } else { + /** @type {Map>} */ const propertiesByModule = new Map(); for (const p of properties) { let list = propertiesByModule.get(p.module); @@ -225,20 +229,23 @@ class WasmChunkLoadingRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { chunkGraph, compilation, chunk, mangleImports } = this; - const { moduleGraph, outputOptions } = compilation; const fn = RuntimeGlobals.ensureChunkHandlers; const withHmr = this._runtimeRequirements.has( RuntimeGlobals.hmrDownloadUpdateHandlers ); + const compilation = /** @type {Compilation} */ (this.compilation); + const { moduleGraph, outputOptions } = compilation; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); + const { mangleImports } = this; /** @type {string[]} */ const declarations = []; const importObjects = wasmModules.map(module => { return generateImportObject( chunkGraph, module, - this.mangleImports, + mangleImports, declarations, chunk.runtime ); diff --git a/lib/wasm-sync/WasmFinalizeExportsPlugin.js b/lib/wasm-sync/WasmFinalizeExportsPlugin.js index 5719e8be387..7e5668798be 100644 --- a/lib/wasm-sync/WasmFinalizeExportsPlugin.js +++ b/lib/wasm-sync/WasmFinalizeExportsPlugin.js @@ -11,6 +11,7 @@ const UnsupportedWebAssemblyFeatureError = require("./UnsupportedWebAssemblyFeat /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ class WasmFinalizeExportsPlugin { /** @@ -27,7 +28,8 @@ class WasmFinalizeExportsPlugin { // 1. if a WebAssembly module if (module.type.startsWith("webassembly") === true) { const jsIncompatibleExports = - module.buildMeta.jsIncompatibleExports; + /** @type {BuildMeta} */ + (module.buildMeta).jsIncompatibleExports; if (jsIncompatibleExports === undefined) { continue; diff --git a/lib/wasm-sync/WebAssemblyGenerator.js b/lib/wasm-sync/WebAssemblyGenerator.js index aba49d6ed06..4c0bb0318dc 100644 --- a/lib/wasm-sync/WebAssemblyGenerator.js +++ b/lib/wasm-sync/WebAssemblyGenerator.js @@ -174,6 +174,7 @@ const createDefaultInitForGlobal = globalType => { */ const rewriteImportedGlobals = state => bin => { const additionalInitCode = state.additionalInitCode; + /** @type {Array} */ const newGlobals = []; bin = editWithAST(state.ast, bin, { diff --git a/lib/wasm-sync/WebAssemblyParser.js b/lib/wasm-sync/WebAssemblyParser.js index f065bd2443b..bebd276f8cd 100644 --- a/lib/wasm-sync/WebAssemblyParser.js +++ b/lib/wasm-sync/WebAssemblyParser.js @@ -14,6 +14,8 @@ const WebAssemblyExportImportedDependency = require("../dependencies/WebAssembly const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); /** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ @@ -81,8 +83,10 @@ class WebAssemblyParser extends Parser { } // flag it as ESM - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "namespace"; + /** @type {BuildInfo} */ + (state.module.buildInfo).strict = true; + /** @type {BuildMeta} */ + (state.module.buildMeta).exportsType = "namespace"; // parse it const program = decode(source, decoderOpts); diff --git a/lib/web/JsonpChunkLoadingRuntimeModule.js b/lib/web/JsonpChunkLoadingRuntimeModule.js index 6b608b98c3c..a4f8ae37073 100644 --- a/lib/web/JsonpChunkLoadingRuntimeModule.js +++ b/lib/web/JsonpChunkLoadingRuntimeModule.js @@ -14,6 +14,7 @@ const { getInitialChunkIds } = require("../javascript/StartupHelpers"); const compileBooleanMatcher = require("../util/compileBooleanMatcher"); /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** * @typedef {Object} JsonpCompilationPluginHooks @@ -72,7 +73,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { chunkGraph, compilation, chunk } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate, outputOptions: { @@ -114,6 +115,8 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule { const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( chunkLoadingGlobal )}]`; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); const hasJsMatcher = compileBooleanMatcher(conditionMap); const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); diff --git a/lib/webpack.js b/lib/webpack.js index f664598cc98..ec718b62721 100644 --- a/lib/webpack.js +++ b/lib/webpack.js @@ -61,7 +61,10 @@ const createMultiCompiler = (childOptions, options) => { const createCompiler = rawOptions => { const options = getNormalizedWebpackOptions(rawOptions); applyWebpackOptionsBaseDefaults(options); - const compiler = new Compiler(options.context, options); + const compiler = new Compiler( + /** @type {string} */ (options.context), + options + ); new NodeEnvironmentPlugin({ infrastructureLogging: options.infrastructureLogging }).apply(compiler); @@ -96,6 +99,11 @@ const createCompiler = rawOptions => { * @returns {MultiCompiler} the multi compiler object */ +/** + * @template T + * @param {Array | T} options options + * @returns {Array} array of options + */ const asArray = options => Array.isArray(options) ? Array.from(options) : [options]; @@ -117,6 +125,7 @@ const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( } /** @type {MultiCompiler|Compiler} */ let compiler; + /** @type {boolean | undefined} */ let watch = false; /** @type {WatchOptions|WatchOptions[]} */ let watchOptions; diff --git a/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js b/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js index 75464310d65..3262add747d 100644 --- a/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +++ b/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js @@ -16,6 +16,8 @@ const compileBooleanMatcher = require("../util/compileBooleanMatcher"); const { getUndoPath } = require("../util/identifier"); /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { /** @@ -38,8 +40,9 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { if (options && options.baseUri) { return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`; } - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + const compilation = /** @type {Compilation} */ (this.compilation); + const outputName = compilation.getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), { chunk, contentHashType: "javascript" @@ -47,7 +50,7 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { ); const rootOutputDir = getUndoPath( outputName, - /** @type {string} */ (this.compilation.outputOptions.path), + /** @type {string} */ (compilation.outputOptions.path), false ); return `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify( @@ -59,16 +62,7 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { - chunk, - chunkGraph, - compilation: { - runtimeTemplate, - outputOptions: { chunkLoadingGlobal, hotUpdateGlobal } - }, - _withCreateScriptUrl: withCreateScriptUrl - } = this; - const globalObject = runtimeTemplate.globalObject; + const compilation = /** @type {Compilation} */ (this.compilation); const fn = RuntimeGlobals.ensureChunkHandlers; const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); const withLoading = this.runtimeRequirements.has( @@ -80,9 +74,12 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { const withHmrManifest = this.runtimeRequirements.has( RuntimeGlobals.hmrDownloadManifest ); + const globalObject = compilation.runtimeTemplate.globalObject; const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( - chunkLoadingGlobal + compilation.outputOptions.chunkLoadingGlobal )}]`; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const hasJsMatcher = compileBooleanMatcher( chunkGraph.getChunkConditionMap(chunk, chunkHasJs) ); @@ -91,6 +88,8 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { const stateExpression = withHmr ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts` : undefined; + const runtimeTemplate = compilation.runtimeTemplate; + const { _withCreateScriptUrl: withCreateScriptUrl } = this; return Template.asString([ withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI", @@ -169,7 +168,7 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { Template.indent([ "var success = false;", `${globalObject}[${JSON.stringify( - hotUpdateGlobal + compilation.outputOptions.hotUpdateGlobal )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [ "for(var moduleId in moreModules) {", Template.indent([ diff --git a/types.d.ts b/types.d.ts index 553523f45a7..390aa1a68f2 100644 --- a/types.d.ts +++ b/types.d.ts @@ -11072,20 +11072,20 @@ declare interface RuntimeRequirementsContext { type RuntimeSpec = undefined | string | SortableSet; declare class RuntimeSpecMap { constructor(clone?: RuntimeSpecMap); - get(runtime: RuntimeSpec): T; + get(runtime: RuntimeSpec): undefined | T; has(runtime: RuntimeSpec): boolean; set(runtime?: any, value?: any): void; provide(runtime?: any, computer?: any): any; - delete(runtime?: any): void; + delete(runtime: RuntimeSpec): void; update(runtime?: any, fn?: any): void; keys(): RuntimeSpec[]; values(): IterableIterator; get size(): number; } declare class RuntimeSpecSet { - constructor(iterable?: any); - add(runtime?: any): void; - has(runtime?: any): boolean; + constructor(iterable?: Iterable); + add(runtime: RuntimeSpec): void; + has(runtime: RuntimeSpec): boolean; get size(): number; [Symbol.iterator](): IterableIterator; } @@ -13816,7 +13816,7 @@ declare namespace exports { export const register: ( Constructor: Constructor, request: string, - name: string, + name: null | string, serializer: ObjectSerializer ) => void; export const registerLoader: ( From 98942261492c47235c628e047a770dd1915c25d1 Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Mon, 12 Jun 2023 20:24:59 +0300 Subject: [PATCH 2/5] refactor(types): more --- lib/CaseSensitiveModulesWarning.js | 4 +- lib/ConcatenationScope.js | 4 +- lib/ConditionalInitFragment.js | 12 +- lib/ConstPlugin.js | 86 ++-- lib/FlagEntryExportAsUsedPlugin.js | 4 + lib/ModuleDependencyError.js | 6 +- lib/ModuleDependencyWarning.js | 6 +- lib/ModuleGraph.js | 55 ++- lib/ModuleGraphConnection.js | 25 +- lib/ModuleInfoHeaderPlugin.js | 11 +- lib/ModuleNotFoundError.js | 7 +- lib/ModuleStoreError.js | 3 +- lib/MultiWatching.js | 4 + lib/WebpackError.js | 11 +- lib/WebpackOptionsDefaulter.js | 13 +- lib/dependencies/ConstDependency.js | 4 +- lib/ids/SyncModuleIdsPlugin.js | 1 + lib/javascript/BasicEvaluatedExpression.js | 38 +- lib/javascript/CommonJsChunkFormatPlugin.js | 8 +- lib/javascript/JavascriptParser.js | 176 +++++--- lib/javascript/JavascriptParserHelpers.js | 52 ++- lib/performance/SizeLimitsPlugin.js | 11 +- .../ChunkPrefetchFunctionRuntimeModule.js | 4 +- .../ChunkPrefetchStartupRuntimeModule.js | 7 +- .../ChunkPrefetchTriggerRuntimeModule.js | 4 +- .../ChunkPreloadTriggerRuntimeModule.js | 4 +- lib/rules/BasicEffectRulePlugin.js | 4 + lib/rules/BasicMatcherRulePlugin.js | 5 + lib/runtime/AsyncModuleRuntimeModule.js | 5 +- lib/runtime/AutoPublicPathRuntimeModule.js | 4 +- lib/runtime/BaseUriRuntimeModule.js | 4 +- .../CompatGetDefaultExportRuntimeModule.js | 5 +- lib/runtime/CompatRuntimeModule.js | 7 +- .../CreateFakeNamespaceObjectRuntimeModule.js | 5 +- lib/runtime/CreateScriptRuntimeModule.js | 4 +- lib/runtime/CreateScriptUrlRuntimeModule.js | 4 +- .../DefinePropertyGettersRuntimeModule.js | 5 +- lib/runtime/EnsureChunkRuntimeModule.js | 5 +- lib/runtime/GetChunkFilenameRuntimeModule.js | 14 +- lib/runtime/GetFullHashRuntimeModule.js | 5 +- lib/runtime/GetMainFilenameRuntimeModule.js | 5 +- .../GetTrustedTypesPolicyRuntimeModule.js | 4 +- lib/runtime/HasOwnPropertyRuntimeModule.js | 5 +- lib/runtime/LoadScriptRuntimeModule.js | 2 +- .../MakeNamespaceObjectRuntimeModule.js | 5 +- lib/runtime/OnChunksLoadedRuntimeModule.js | 4 +- lib/runtime/PublicPathRuntimeModule.js | 4 +- lib/runtime/RelativeUrlRuntimeModule.js | 5 +- lib/runtime/RuntimeIdRuntimeModule.js | 6 +- .../StartupChunkDependenciesRuntimeModule.js | 10 +- lib/runtime/StartupEntrypointRuntimeModule.js | 3 +- .../ConsumeSharedFallbackDependency.js | 3 + lib/sharing/ConsumeSharedRuntimeModule.js | 17 +- lib/sharing/ProvideSharedDependency.js | 11 + lib/sharing/ProvideSharedModule.js | 4 + lib/sharing/ProvideSharedPlugin.js | 43 +- lib/sharing/ShareRuntimeModule.js | 15 +- lib/sharing/resolveMatchedConfigs.js | 2 +- lib/sharing/utils.js | 37 +- lib/validateSchema.js | 8 +- types.d.ts | 411 +++++++++++------- 61 files changed, 841 insertions(+), 399 deletions(-) diff --git a/lib/CaseSensitiveModulesWarning.js b/lib/CaseSensitiveModulesWarning.js index 8ccc682bf37..e4dec2283d7 100644 --- a/lib/CaseSensitiveModulesWarning.js +++ b/lib/CaseSensitiveModulesWarning.js @@ -42,7 +42,9 @@ const createModulesListMessage = (modules, moduleGraph) => { if (validReasons.length > 0) { message += `\n Used by ${validReasons.length} module(s), i. e.`; - message += `\n ${validReasons[0].identifier()}`; + message += `\n ${ + /** @type {Module[]} */ (validReasons)[0].identifier() + }`; } return message; }) diff --git a/lib/ConcatenationScope.js b/lib/ConcatenationScope.js index c1e1758f30e..8c26166b153 100644 --- a/lib/ConcatenationScope.js +++ b/lib/ConcatenationScope.js @@ -108,7 +108,7 @@ class ConcatenationScope { module, { ids = undefined, call = false, directImport = false, asiSafe = false } ) { - const info = this._modulesMap.get(module); + const info = /** @type {ModuleInfo} */ (this._modulesMap.get(module)); const callFlag = call ? "_call" : ""; const directImportFlag = directImport ? "_directImport" : ""; const asiSafeFlag = asiSafe @@ -133,7 +133,7 @@ class ConcatenationScope { /** * @param {string} name the identifier - * @returns {ModuleReferenceOptions & { index: number }} parsed options and index + * @returns {ModuleReferenceOptions & { index: number } | null} parsed options and index */ static matchModuleReference(name) { const match = MODULE_REFERENCE_REGEXP.exec(name); diff --git a/lib/ConditionalInitFragment.js b/lib/ConditionalInitFragment.js index 0a44f42a8dd..93402f5b50d 100644 --- a/lib/ConditionalInitFragment.js +++ b/lib/ConditionalInitFragment.js @@ -14,6 +14,11 @@ const { mergeRuntime } = require("./util/runtime"); /** @typedef {import("./Generator").GenerateContext} GenerateContext */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** + * @param {string} condition condition + * @param {string | Source} source source + * @returns {string | Source} wrapped source + */ const wrapInCondition = (condition, source) => { if (typeof source === "string") { return Template.asString([ @@ -33,13 +38,14 @@ const wrapInCondition = (condition, source) => { /** * @typedef {GenerateContext} Context + * @extends {InitFragment} */ class ConditionalInitFragment extends InitFragment { /** * @param {string|Source} content the source code that will be included as initialization code * @param {number} stage category of initialization code (contribute to order) * @param {number} position position in the category (contribute to order) - * @param {string} key unique key to avoid emitting the same initialization code twice + * @param {string | undefined} key unique key to avoid emitting the same initialization code twice * @param {RuntimeSpec | boolean} runtimeCondition in which runtime this fragment should be executed * @param {string|Source=} endContent the source code that will be included at the end of the module */ @@ -89,6 +95,10 @@ class ConditionalInitFragment extends InitFragment { return wrapInCondition(expr, this.endContent); } + /** + * @param {ConditionalInitFragment} other fragment to merge with + * @returns {ConditionalInitFragment} merged fragment + */ merge(other) { if (this.runtimeCondition === true) return this; if (other.runtimeCondition === true) return other; diff --git a/lib/ConstPlugin.js b/lib/ConstPlugin.js index 6bc5e5b3d7c..932a8c483cc 100644 --- a/lib/ConstPlugin.js +++ b/lib/ConstPlugin.js @@ -15,9 +15,14 @@ const ConstDependency = require("./dependencies/ConstDependency"); const { evaluateToString } = require("./javascript/JavascriptParserHelpers"); const { parseResource } = require("./util/identifier"); -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("estree").Super} SuperNode */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("estree").Statement} Statement */ +/** @typedef {import("estree").Super} Super */ /** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ const collectDeclaration = (declarations, pattern) => { const stack = [pattern]; @@ -136,6 +141,9 @@ class ConstPlugin { new CachedConstDependency.Template() ); + /** + * @param {JavascriptParser} parser the parser + */ const handler = parser => { parser.hooks.statementIf.tap(PLUGIN_NAME, statement => { if (parser.scope.isAsmJs) return; @@ -143,8 +151,11 @@ class ConstPlugin { const bool = param.asBool(); if (typeof bool === "boolean") { if (!param.couldHaveSideEffects()) { - const dep = new ConstDependency(`${bool}`, param.range); - dep.loc = statement.loc; + const dep = new ConstDependency( + `${bool}`, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (statement.loc); parser.state.module.addPresentationalDependency(dep); } else { parser.walkExpression(statement.test); @@ -200,9 +211,9 @@ class ConstPlugin { } const dep = new ConstDependency( replacement, - branchToRemove.range + /** @type {Range} */ (branchToRemove.range) ); - dep.loc = branchToRemove.loc; + dep.loc = /** @type {SourceLocation} */ (branchToRemove.loc); parser.state.module.addPresentationalDependency(dep); } return bool; @@ -216,8 +227,11 @@ class ConstPlugin { const bool = param.asBool(); if (typeof bool === "boolean") { if (!param.couldHaveSideEffects()) { - const dep = new ConstDependency(` ${bool}`, param.range); - dep.loc = expression.loc; + const dep = new ConstDependency( + ` ${bool}`, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); parser.state.module.addPresentationalDependency(dep); } else { parser.walkExpression(expression.test); @@ -236,8 +250,11 @@ class ConstPlugin { const branchToRemove = bool ? expression.alternate : expression.consequent; - const dep = new ConstDependency("0", branchToRemove.range); - dep.loc = branchToRemove.loc; + const dep = new ConstDependency( + "0", + /** @type {Range} */ (branchToRemove.range) + ); + dep.loc = /** @type {SourceLocation} */ (branchToRemove.loc); parser.state.module.addPresentationalDependency(dep); return bool; } @@ -313,8 +330,11 @@ class ConstPlugin { // // returnfalse&&'foo' // - const dep = new ConstDependency(` ${bool}`, param.range); - dep.loc = expression.loc; + const dep = new ConstDependency( + ` ${bool}`, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); parser.state.module.addPresentationalDependency(dep); } else { parser.walkExpression(expression.left); @@ -322,9 +342,9 @@ class ConstPlugin { if (!keepRight) { const dep = new ConstDependency( "0", - expression.right.range + /** @type {Range} */ (expression.right.range) ); - dep.loc = expression.loc; + dep.loc = /** @type {SourceLocation} */ (expression.loc); parser.state.module.addPresentationalDependency(dep); } return keepRight; @@ -363,15 +383,18 @@ class ConstPlugin { // // returnnull??'foo' // - const dep = new ConstDependency(" null", param.range); - dep.loc = expression.loc; + const dep = new ConstDependency( + " null", + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); parser.state.module.addPresentationalDependency(dep); } else { const dep = new ConstDependency( "0", - expression.right.range + /** @type {Range} */ (expression.right.range) ); - dep.loc = expression.loc; + dep.loc = /** @type {SourceLocation} */ (expression.loc); parser.state.module.addPresentationalDependency(dep); parser.walkExpression(expression.left); } @@ -382,9 +405,9 @@ class ConstPlugin { } ); parser.hooks.optionalChaining.tap(PLUGIN_NAME, expr => { - /** @type {ExpressionNode[]} */ + /** @type {Expression[]} */ const optionalExpressionsStack = []; - /** @type {ExpressionNode|SuperNode} */ + /** @type {Expression | Super} */ let next = expr.expression; while ( @@ -395,7 +418,7 @@ class ConstPlugin { if (next.optional) { // SuperNode can not be optional optionalExpressionsStack.push( - /** @type {ExpressionNode} */ (next.object) + /** @type {Expression} */ (next.object) ); } next = next.object; @@ -403,7 +426,7 @@ class ConstPlugin { if (next.optional) { // SuperNode can not be optional optionalExpressionsStack.push( - /** @type {ExpressionNode} */ (next.callee) + /** @type {Expression} */ (next.callee) ); } next = next.callee; @@ -412,7 +435,9 @@ class ConstPlugin { while (optionalExpressionsStack.length) { const expression = optionalExpressionsStack.pop(); - const evaluated = parser.evaluateExpression(expression); + const evaluated = parser.evaluateExpression( + /** @type {Expression} */ (expression) + ); if (evaluated.asNullish()) { // ------------------------------------------ @@ -427,8 +452,11 @@ class ConstPlugin { // // ------------------------------------------ // - const dep = new ConstDependency(" undefined", expr.range); - dep.loc = expr.loc; + const dep = new ConstDependency( + " undefined", + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); parser.state.module.addPresentationalDependency(dep); return true; } @@ -452,10 +480,10 @@ class ConstPlugin { JSON.stringify( cachedParseResource(parser.state.module.resource).query ), - expr.range, + /** @type {Range} */ (expr.range), "__resourceQuery" ); - dep.loc = expr.loc; + dep.loc = /** @type {SourceLocation} */ (expr.loc); parser.state.module.addPresentationalDependency(dep); return true; }); @@ -478,10 +506,10 @@ class ConstPlugin { JSON.stringify( cachedParseResource(parser.state.module.resource).fragment ), - expr.range, + /** @type {Range} */ (expr.range), "__resourceFragment" ); - dep.loc = expr.loc; + dep.loc = /** @type {SourceLocation} */ (expr.loc); parser.state.module.addPresentationalDependency(dep); return true; }); diff --git a/lib/FlagEntryExportAsUsedPlugin.js b/lib/FlagEntryExportAsUsedPlugin.js index 943d336719f..d2826d12fb2 100644 --- a/lib/FlagEntryExportAsUsedPlugin.js +++ b/lib/FlagEntryExportAsUsedPlugin.js @@ -12,6 +12,10 @@ const { getEntryRuntime } = require("./util/runtime"); const PLUGIN_NAME = "FlagEntryExportAsUsedPlugin"; class FlagEntryExportAsUsedPlugin { + /** + * @param {boolean} nsObjectUsed true, if the ns object is used + * @param {string} explanation explanation for the reason + */ constructor(nsObjectUsed, explanation) { this.nsObjectUsed = nsObjectUsed; this.explanation = explanation; diff --git a/lib/ModuleDependencyError.js b/lib/ModuleDependencyError.js index 416a6357d0c..7aff42c4b5b 100644 --- a/lib/ModuleDependencyError.js +++ b/lib/ModuleDependencyError.js @@ -23,7 +23,7 @@ class ModuleDependencyError extends WebpackError { this.name = "ModuleDependencyError"; this.details = err && !(/** @type {any} */ (err).hideStack) - ? err.stack.split("\n").slice(1).join("\n") + ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") : undefined; this.module = module; this.loc = loc; @@ -32,7 +32,9 @@ class ModuleDependencyError extends WebpackError { if (err && /** @type {any} */ (err).hideStack) { this.stack = - err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; + /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") + + "\n\n" + + this.stack; } } } diff --git a/lib/ModuleDependencyWarning.js b/lib/ModuleDependencyWarning.js index f22a5825b4f..a02d6f185e2 100644 --- a/lib/ModuleDependencyWarning.js +++ b/lib/ModuleDependencyWarning.js @@ -23,7 +23,7 @@ class ModuleDependencyWarning extends WebpackError { this.name = "ModuleDependencyWarning"; this.details = err && !(/** @type {any} */ (err).hideStack) - ? err.stack.split("\n").slice(1).join("\n") + ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") : undefined; this.module = module; this.loc = loc; @@ -32,7 +32,9 @@ class ModuleDependencyWarning extends WebpackError { if (err && /** @type {any} */ (err).hideStack) { this.stack = - err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; + /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") + + "\n\n" + + this.stack; } } } diff --git a/lib/ModuleGraph.js b/lib/ModuleGraph.js index 4e96315a56e..cf15c6cf9b6 100644 --- a/lib/ModuleGraph.js +++ b/lib/ModuleGraph.js @@ -35,14 +35,15 @@ const getConnectionsByOriginModule = set => { const map = new Map(); /** @type {Module | 0} */ let lastModule = 0; - /** @type {ModuleGraphConnection[]} */ + /** @type {ModuleGraphConnection[] | undefined} */ let lastList = undefined; for (const connection of set) { const { originModule } = connection; if (lastModule === originModule) { - lastList.push(connection); + /** @type {ModuleGraphConnection[]} */ + (lastList).push(connection); } else { - lastModule = originModule; + lastModule = /** @type {Module} */ (originModule); const list = map.get(originModule); if (list !== undefined) { lastList = list; @@ -65,12 +66,13 @@ const getConnectionsByModule = set => { const map = new Map(); /** @type {Module | 0} */ let lastModule = 0; - /** @type {ModuleGraphConnection[]} */ + /** @type {ModuleGraphConnection[] | undefined} */ let lastList = undefined; for (const connection of set) { const { module } = connection; if (lastModule === module) { - lastList.push(connection); + /** @type {ModuleGraphConnection[]} */ + (lastList).push(connection); } else { lastModule = module; const list = map.get(module); @@ -99,13 +101,13 @@ class ModuleGraphModule { this.optimizationBailout = []; /** @type {ExportsInfo} */ this.exports = new ExportsInfo(); - /** @type {number} */ + /** @type {number | null} */ this.preOrderIndex = null; - /** @type {number} */ + /** @type {number | null} */ this.postOrderIndex = null; - /** @type {number} */ + /** @type {number | null} */ this.depth = null; - /** @type {ModuleProfile} */ + /** @type {ModuleProfile | undefined | null} */ this.profile = undefined; /** @type {boolean} */ this.async = false; @@ -116,20 +118,20 @@ class ModuleGraphModule { class ModuleGraph { constructor() { - /** @type {WeakMap} */ + /** @type {WeakMap} */ this._dependencyMap = new WeakMap(); /** @type {Map} */ this._moduleMap = new Map(); /** @type {WeakMap} */ this._metaMap = new WeakMap(); - /** @type {WeakTupleMap} */ + /** @type {WeakTupleMap | undefined} */ this._cache = undefined; /** @type {Map>} */ this._moduleMemCaches = undefined; - /** @type {string} */ + /** @type {string | undefined} */ this._cacheStage = undefined; } @@ -221,7 +223,9 @@ class ModuleGraph { * @returns {void} */ updateModule(dependency, module) { - const connection = this.getConnection(dependency); + const connection = + /** @type {ModuleGraphConnection} */ + (this.getConnection(dependency)); if (connection.module === module) return; const newConnection = connection.clone(); newConnection.module = module; @@ -375,7 +379,7 @@ class ModuleGraph { /** * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {Module} the referenced module + * @returns {Module | null} the referenced module */ getResolvedModule(dependency) { const connection = this.getConnection(dependency); @@ -398,7 +402,10 @@ class ModuleGraph { ) { let foundConnection; for (const connection of mgm._unassignedConnections) { - this._dependencyMap.set(connection.dependency, connection); + this._dependencyMap.set( + /** @type {Dependency} */ (connection.dependency), + connection + ); if (connection.dependency === dependency) foundConnection = connection; } @@ -416,7 +423,7 @@ class ModuleGraph { /** * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {Module} the referenced module + * @returns {Module | null} the referenced module */ getModule(dependency) { const connection = this.getConnection(dependency); @@ -425,7 +432,7 @@ class ModuleGraph { /** * @param {Dependency} dependency the dependency to look for a referencing module - * @returns {Module} the referencing module + * @returns {Module | null} the referencing module */ getOrigin(dependency) { const connection = this.getConnection(dependency); @@ -434,7 +441,7 @@ class ModuleGraph { /** * @param {Dependency} dependency the dependency to look for a referencing module - * @returns {Module} the original referencing module + * @returns {Module | null} the original referencing module */ getResolvedOrigin(dependency) { const connection = this.getConnection(dependency); @@ -604,7 +611,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @returns {number} the index of the module + * @returns {number | null} the index of the module */ getPreOrderIndex(module) { const mgm = this._getModuleGraphModule(module); @@ -613,7 +620,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @returns {number} the index of the module + * @returns {number | null} the index of the module */ getPostOrderIndex(module) { const mgm = this._getModuleGraphModule(module); @@ -670,7 +677,7 @@ class ModuleGraph { /** * @param {Module} module the module - * @returns {number} the depth of the module + * @returns {number | null} the depth of the module */ getDepth(module) { const mgm = this._getModuleGraphModule(module); @@ -727,14 +734,14 @@ class ModuleGraph { let meta = this._metaMap.get(thing); if (meta === undefined) { meta = Object.create(null); - this._metaMap.set(thing, meta); + this._metaMap.set(thing, /** @type {Object} */ (meta)); } - return meta; + return /** @type {Object} */ (meta); } /** * @param {any} thing any thing - * @returns {Object} metadata + * @returns {Object | undefined} metadata */ getMetaIfExisting(thing) { return this._metaMap.get(thing); diff --git a/lib/ModuleGraphConnection.js b/lib/ModuleGraphConnection.js index bde1030cc09..515d2c9d1cd 100644 --- a/lib/ModuleGraphConnection.js +++ b/lib/ModuleGraphConnection.js @@ -74,9 +74,9 @@ class ModuleGraphConnection { this.weak = weak; this.conditional = !!condition; this._active = condition !== false; - /** @type {function(ModuleGraphConnection, RuntimeSpec): ConnectionState} */ + /** @type {(function(ModuleGraphConnection, RuntimeSpec): ConnectionState) | undefined} */ this.condition = condition || undefined; - /** @type {Set} */ + /** @type {Set | undefined} */ this.explanations = undefined; if (explanation) { this.explanations = new Set(); @@ -107,7 +107,9 @@ class ModuleGraphConnection { */ addCondition(condition) { if (this.conditional) { - const old = this.condition; + const old = + /** @type {(function(ModuleGraphConnection, RuntimeSpec): ConnectionState)} */ + (this.condition); this.condition = (c, r) => intersectConnectionStates(old(c, r), condition(c, r)); } else if (this._active) { @@ -143,7 +145,12 @@ class ModuleGraphConnection { */ isActive(runtime) { if (!this.conditional) return this._active; - return this.condition(this, runtime) !== false; + + return ( + /** @type {(function(ModuleGraphConnection, RuntimeSpec): ConnectionState)} */ ( + this.condition + )(this, runtime) !== false + ); } /** @@ -152,7 +159,11 @@ class ModuleGraphConnection { */ isTargetActive(runtime) { if (!this.conditional) return this._active; - return this.condition(this, runtime) === true; + return ( + /** @type {(function(ModuleGraphConnection, RuntimeSpec): ConnectionState)} */ ( + this.condition + )(this, runtime) === true + ); } /** @@ -161,7 +172,9 @@ class ModuleGraphConnection { */ getActiveState(runtime) { if (!this.conditional) return this._active; - return this.condition(this, runtime); + return /** @type {(function(ModuleGraphConnection, RuntimeSpec): ConnectionState)} */ ( + this.condition + )(this, runtime); } /** diff --git a/lib/ModuleInfoHeaderPlugin.js b/lib/ModuleInfoHeaderPlugin.js index 1402a75f32b..2ee0b2a8122 100644 --- a/lib/ModuleInfoHeaderPlugin.js +++ b/lib/ModuleInfoHeaderPlugin.js @@ -15,10 +15,16 @@ const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); /** @typedef {import("./ExportsInfo")} ExportsInfo */ /** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ /** @typedef {import("./ModuleTemplate")} ModuleTemplate */ /** @typedef {import("./RequestShortener")} RequestShortener */ +/** + * @template T + * @param {Iterable} iterable iterable + * @returns {string} joined with comma + */ const joinIterableWithComma = iterable => { // This is more performant than Array.from().join(", ") // as it doesn't create an array @@ -139,7 +145,7 @@ const printExportsInfoToSource = ( } }; -/** @type {WeakMap }>>} */ +/** @type {WeakMap }>>} */ const caches = new WeakMap(); class ModuleInfoHeaderPlugin { @@ -197,7 +203,8 @@ class ModuleInfoHeaderPlugin { } source.add(header); if (verbose) { - const exportsType = module.buildMeta.exportsType; + const exportsType = /** @type {BuildMeta} */ (module.buildMeta) + .exportsType; source.add( Template.toComment( exportsType diff --git a/lib/ModuleNotFoundError.js b/lib/ModuleNotFoundError.js index a8f14b1e538..6fdf241dee8 100644 --- a/lib/ModuleNotFoundError.js +++ b/lib/ModuleNotFoundError.js @@ -43,7 +43,7 @@ const previouslyPolyfilledBuiltinModules = { class ModuleNotFoundError extends WebpackError { /** - * @param {Module} module module tied to dependency + * @param {Module | null} module module tied to dependency * @param {Error&any} err error thrown * @param {DependencyLocation} loc location of dependency */ @@ -54,7 +54,10 @@ class ModuleNotFoundError extends WebpackError { const match = err.message.match(/Can't resolve '([^']+)'/); if (match) { const request = match[1]; - const alias = previouslyPolyfilledBuiltinModules[request]; + const alias = + previouslyPolyfilledBuiltinModules[ + /** @type {keyof previouslyPolyfilledBuiltinModules} */ (request) + ]; if (alias) { const pathIndex = alias.indexOf("/"); const dependency = pathIndex > 0 ? alias.slice(0, pathIndex) : alias; diff --git a/lib/ModuleStoreError.js b/lib/ModuleStoreError.js index 9d1f66b5413..e00e1cbbf22 100644 --- a/lib/ModuleStoreError.js +++ b/lib/ModuleStoreError.js @@ -16,6 +16,7 @@ class ModuleStoreError extends WebpackError { */ constructor(module, err) { let message = "Module storing failed: "; + /** @type {string | undefined} */ let details = undefined; if (err !== null && typeof err === "object") { if (typeof err.stack === "string" && err.stack) { @@ -33,7 +34,7 @@ class ModuleStoreError extends WebpackError { super(message); this.name = "ModuleStoreError"; - this.details = details; + this.details = /** @type {string | undefined} */ (details); this.module = module; this.error = err; } diff --git a/lib/MultiWatching.js b/lib/MultiWatching.js index 2bbd5365a1c..b4fcd87c852 100644 --- a/lib/MultiWatching.js +++ b/lib/MultiWatching.js @@ -27,6 +27,10 @@ class MultiWatching { this.compiler = compiler; } + /** + * @param {Callback=} callback signals when the build has completed again + * @returns {void} + */ invalidate(callback) { if (callback) { asyncLib.each( diff --git a/lib/WebpackError.js b/lib/WebpackError.js index 30adc0a0e57..2cc3a9d2c7b 100644 --- a/lib/WebpackError.js +++ b/lib/WebpackError.js @@ -22,16 +22,17 @@ class WebpackError extends Error { constructor(message) { super(message); + /** @type {string | undefined} */ this.details = undefined; - /** @type {Module} */ + /** @type {Module | undefined | null} */ this.module = undefined; - /** @type {DependencyLocation} */ + /** @type {DependencyLocation | undefined} */ this.loc = undefined; - /** @type {boolean} */ + /** @type {boolean | undefined} */ this.hideStack = undefined; - /** @type {Chunk} */ + /** @type {Chunk | undefined} */ this.chunk = undefined; - /** @type {string} */ + /** @type {string | undefined} */ this.file = undefined; } diff --git a/lib/WebpackOptionsDefaulter.js b/lib/WebpackOptionsDefaulter.js index dd12ddbb530..12fbe698d93 100644 --- a/lib/WebpackOptionsDefaulter.js +++ b/lib/WebpackOptionsDefaulter.js @@ -8,11 +8,18 @@ const { applyWebpackOptionsDefaults } = require("./config/defaults"); const { getNormalizedWebpackOptions } = require("./config/normalization"); +/** @typedef {import("./config/normalization").WebpackOptions} WebpackOptions */ +/** @typedef {import("./config/normalization").WebpackOptionsNormalized} WebpackOptionsNormalized */ + class WebpackOptionsDefaulter { + /** + * @param {WebpackOptions} options webpack options + * @returns {WebpackOptionsNormalized} normalized webpack options + */ process(options) { - options = getNormalizedWebpackOptions(options); - applyWebpackOptionsDefaults(options); - return options; + const normalizedOptions = getNormalizedWebpackOptions(options); + applyWebpackOptionsDefaults(normalizedOptions); + return normalizedOptions; } } diff --git a/lib/dependencies/ConstDependency.js b/lib/dependencies/ConstDependency.js index 1c9dcfe61fd..d1996ac2fb1 100644 --- a/lib/dependencies/ConstDependency.js +++ b/lib/dependencies/ConstDependency.js @@ -23,8 +23,8 @@ const NullDependency = require("./NullDependency"); class ConstDependency extends NullDependency { /** * @param {string} expression the expression - * @param {number|Range} range the source range - * @param {string[]=} runtimeRequirements runtime requirements + * @param {number | Range} range the source range + * @param {(string[] | null)=} runtimeRequirements runtime requirements */ constructor(expression, range, runtimeRequirements) { super(); diff --git a/lib/ids/SyncModuleIdsPlugin.js b/lib/ids/SyncModuleIdsPlugin.js index 14eab7556ed..2a94189d3ef 100644 --- a/lib/ids/SyncModuleIdsPlugin.js +++ b/lib/ids/SyncModuleIdsPlugin.js @@ -63,6 +63,7 @@ class SyncModuleIdsPlugin { if (this._write) { compiler.hooks.emitRecords.tapAsync(plugin, callback => { if (!data || !dataChanged) return callback(); + /** @type {Object} */ const json = {}; const sorted = Array.from(data).sort(([a], [b]) => (a < b ? -1 : 1)); for (const [key, value] of sorted) { diff --git a/lib/javascript/BasicEvaluatedExpression.js b/lib/javascript/BasicEvaluatedExpression.js index c15cd9bcfa8..701791c83c5 100644 --- a/lib/javascript/BasicEvaluatedExpression.js +++ b/lib/javascript/BasicEvaluatedExpression.js @@ -5,7 +5,7 @@ "use strict"; -/** @typedef {import("estree").Node} EsTreeNode */ +/** @typedef {import("estree").Node} Node */ /** @typedef {import("./JavascriptParser").Range} Range */ /** @typedef {import("./JavascriptParser").VariableInfoInterface} VariableInfoInterface */ @@ -27,7 +27,7 @@ const TypeBigInt = 13; class BasicEvaluatedExpression { constructor() { this.type = TypeUnknown; - /** @type {[number, number]} */ + /** @type {[number, number] | undefined} */ this.range = undefined; /** @type {boolean} */ this.falsy = false; @@ -57,23 +57,23 @@ class BasicEvaluatedExpression { this.items = undefined; /** @type {BasicEvaluatedExpression[] | undefined} */ this.options = undefined; - /** @type {BasicEvaluatedExpression | undefined} */ + /** @type {BasicEvaluatedExpression | undefined | null} */ this.prefix = undefined; - /** @type {BasicEvaluatedExpression | undefined} */ + /** @type {BasicEvaluatedExpression | undefined | null} */ this.postfix = undefined; - /** @type {BasicEvaluatedExpression[]} */ + /** @type {BasicEvaluatedExpression[] | undefined} */ this.wrappedInnerExpressions = undefined; /** @type {string | VariableInfoInterface | undefined} */ this.identifier = undefined; - /** @type {string | VariableInfoInterface} */ + /** @type {string | VariableInfoInterface | undefined} */ this.rootInfo = undefined; - /** @type {() => string[]} */ + /** @type {(() => string[]) | undefined} */ this.getMembers = undefined; - /** @type {() => boolean[]} */ + /** @type {(() => boolean[]) | undefined} */ this.getMembersOptionals = undefined; - /** @type {() => Range[]} */ + /** @type {(() => Range[]) | undefined} */ this.getMemberRanges = undefined; - /** @type {EsTreeNode} */ + /** @type {Node | undefined} */ this.expression = undefined; } @@ -293,7 +293,9 @@ class BasicEvaluatedExpression { if (this.isRegExp()) return `${this.regExp}`; if (this.isArray()) { let array = []; - for (const item of this.items) { + for (const item of /** @type {BasicEvaluatedExpression[]} */ ( + this.items + )) { const itemStr = item.asString(); if (itemStr === undefined) return undefined; array.push(itemStr); @@ -303,7 +305,9 @@ class BasicEvaluatedExpression { if (this.isConstArray()) return `${this.array}`; if (this.isTemplateString()) { let str = ""; - for (const part of this.parts) { + for (const part of /** @type {BasicEvaluatedExpression[]} */ ( + this.parts + )) { const partStr = part.asString(); if (partStr === undefined) return undefined; str += partStr; @@ -313,6 +317,10 @@ class BasicEvaluatedExpression { return undefined; } + /** + * @param {string} string value + * @returns {BasicEvaluatedExpression} basic evaluated expression + */ setString(string) { this.type = TypeString; this.string = string; @@ -410,8 +418,8 @@ class BasicEvaluatedExpression { /** * Wraps an array of expressions with a prefix and postfix expression. * - * @param {BasicEvaluatedExpression | null} prefix Expression to be added before the innerExpressions - * @param {BasicEvaluatedExpression} postfix Expression to be added after the innerExpressions + * @param {BasicEvaluatedExpression | null | undefined} prefix Expression to be added before the innerExpressions + * @param {BasicEvaluatedExpression | null | undefined} postfix Expression to be added after the innerExpressions * @param {BasicEvaluatedExpression[]} innerExpressions Expressions to be wrapped * @returns {this} this */ @@ -551,7 +559,7 @@ class BasicEvaluatedExpression { /** * Set the expression node for the expression. * - * @param {EsTreeNode} expression expression + * @param {Node | undefined} expression expression * @returns {this} this */ setExpression(expression) { diff --git a/lib/javascript/CommonJsChunkFormatPlugin.js b/lib/javascript/CommonJsChunkFormatPlugin.js index 291589ddba6..65963ec599b 100644 --- a/lib/javascript/CommonJsChunkFormatPlugin.js +++ b/lib/javascript/CommonJsChunkFormatPlugin.js @@ -17,7 +17,9 @@ const { updateHashForEntryStartup } = require("./StartupHelpers"); +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ class CommonJsChunkFormatPlugin { /** @@ -66,7 +68,9 @@ class CommonJsChunkFormatPlugin { chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) ); if (entries.length > 0) { - const runtimeChunk = entries[0][1].getRuntimeChunk(); + const runtimeChunk = + /** @type {Entrypoint} */ + (entries[0][1]).getRuntimeChunk(); const currentOutputName = compilation .getPath( getChunkFilenameTemplate(chunk, compilation.outputOptions), @@ -83,7 +87,7 @@ class CommonJsChunkFormatPlugin { compilation.outputOptions ), { - chunk: runtimeChunk, + chunk: /** @type {Chunk} */ (runtimeChunk), contentHashType: "javascript" } ) diff --git a/lib/javascript/JavascriptParser.js b/lib/javascript/JavascriptParser.js index 50d2ba58d1e..68f7780292a 100644 --- a/lib/javascript/JavascriptParser.js +++ b/lib/javascript/JavascriptParser.js @@ -47,6 +47,7 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); /** @typedef {import("estree").MetaProperty} MetaProperty */ /** @typedef {import("estree").Property} Property */ /** @typedef {import("estree").AssignmentPattern} AssignmentPattern */ +/** @typedef {import("estree").ChainElement} ChainElement */ /** @typedef {import("estree").Pattern} Pattern */ /** @typedef {import("estree").UpdateExpression} UpdateExpression */ /** @typedef {import("estree").ObjectExpression} ObjectExpression */ @@ -105,7 +106,7 @@ const parser = AcornParser.extend(importAssertions); class VariableInfo { /** * @param {ScopeInfo} declaredScope scope in which the variable is declared - * @param {string | true} freeName which free name the variable aliases, or true when none + * @param {string | true | undefined} freeName which free name the variable aliases, or true when none * @param {TagInfo | undefined} tagInfo info about tags */ constructor(declaredScope, freeName, tagInfo) { @@ -404,9 +405,9 @@ class JavascriptParser extends Parser { unhandledExpressionMemberChain: new HookMap( () => new SyncBailHook(["expression", "members"]) ), - /** @type {SyncBailHook<[Expression], boolean | void>} */ + /** @type {SyncBailHook<[ConditionalExpression], boolean | void>} */ expressionConditionalOperator: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[Expression], boolean | void>} */ + /** @type {SyncBailHook<[LogicalExpression], boolean | void>} */ expressionLogicalOperator: new SyncBailHook(["expression"]), /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */ program: new SyncBailHook(["ast", "comments"]), @@ -422,7 +423,7 @@ class JavascriptParser extends Parser { this.semicolons = undefined; /** @type {(Statement | ModuleDeclaration | Expression)[]} */ this.statementPath = undefined; - /** @type {Statement | ModuleDeclaration | Expression} */ + /** @type {Statement | ModuleDeclaration | Expression | undefined} */ this.prevStatement = undefined; /** @type {WeakMap>} */ this.destructuringAssignmentProperties = undefined; @@ -438,27 +439,29 @@ class JavascriptParser extends Parser { case "number": return new BasicEvaluatedExpression() .setNumber(expr.value) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); case "bigint": return new BasicEvaluatedExpression() .setBigInt(expr.value) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); case "string": return new BasicEvaluatedExpression() .setString(expr.value) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); case "boolean": return new BasicEvaluatedExpression() .setBoolean(expr.value) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); } if (expr.value === null) { - return new BasicEvaluatedExpression().setNull().setRange(expr.range); + return new BasicEvaluatedExpression() + .setNull() + .setRange(/** @type {Range} */ (expr.range)); } if (expr.value instanceof RegExp) { return new BasicEvaluatedExpression() .setRegExp(expr.value) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); } }); this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => { @@ -493,7 +496,7 @@ class JavascriptParser extends Parser { } else { return new BasicEvaluatedExpression() .setRegExp(new RegExp("")) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); } const arg2 = expr.arguments[1]; @@ -518,7 +521,7 @@ class JavascriptParser extends Parser { return new BasicEvaluatedExpression() .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); }); this.hooks.evaluate .for("LogicalExpression") @@ -584,7 +587,7 @@ class JavascriptParser extends Parser { * @param {boolean | number | BigInt | string} value the value to convert to an expression * @param {BinaryExpression | UnaryExpression} expr the expression being evaluated * @param {boolean} sideEffects whether the expression has side effects - * @returns {BasicEvaluatedExpression} the evaluated expression + * @returns {BasicEvaluatedExpression | undefined} the evaluated expression * @example * * ```js @@ -611,22 +614,22 @@ class JavascriptParser extends Parser { return new BasicEvaluatedExpression() .setBoolean(value) .setSideEffects(sideEffects) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); case "number": return new BasicEvaluatedExpression() .setNumber(value) .setSideEffects(sideEffects) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); case "bigint": return new BasicEvaluatedExpression() .setBigInt(value) .setSideEffects(sideEffects) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); case "string": return new BasicEvaluatedExpression() .setString(value) .setSideEffects(sideEffects) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); } }; @@ -720,7 +723,7 @@ class JavascriptParser extends Parser { const left = this.evaluateExpression(expr.left); const right = this.evaluateExpression(expr.right); const res = new BasicEvaluatedExpression(); - res.setRange(expr.range); + res.setRange(/** @type {Range} */ (expr.range)); const leftConst = left.isCompileTimeValue(); const rightConst = right.isCompileTimeValue(); @@ -758,8 +761,14 @@ class JavascriptParser extends Parser { (rightPrimitive === false && (rightConst || leftPrimitive === true)) || // Different nullish or boolish status also means not equal - isAlwaysDifferent(left.asBool(), right.asBool()) || - isAlwaysDifferent(left.asNullish(), right.asNullish()) + isAlwaysDifferent( + /** @type {boolean} */ (left.asBool()), + /** @type {boolean} */ (right.asBool()) + ) || + isAlwaysDifferent( + /** @type {boolean} */ (left.asNullish()), + /** @type {boolean} */ (right.asNullish()) + ) ) { return res .setBoolean(!eql) @@ -1363,7 +1372,7 @@ class JavascriptParser extends Parser { const part = new BasicEvaluatedExpression() .setString(quasi) - .setRange(quasiExpr.range) + .setRange(/** @type {Range} */ (quasiExpr.range)) .setExpression(quasiExpr); quasis.push(part); parts.push(part); @@ -1381,11 +1390,11 @@ class JavascriptParser extends Parser { const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); if (parts.length === 1) { - return parts[0].setRange(node.range); + return parts[0].setRange(/** @type {Range} */ (node.range)); } return new BasicEvaluatedExpression() .setTemplateString(quasis, parts, "cooked") - .setRange(node.range); + .setRange(/** @type {Range} */ (node.range)); }); this.hooks.evaluate .for("TaggedTemplateExpression") @@ -1400,7 +1409,7 @@ class JavascriptParser extends Parser { ); return new BasicEvaluatedExpression() .setTemplateString(quasis, parts, "raw") - .setRange(node.range); + .setRange(/** @type {Range} */ (node.range)); } }); @@ -1490,7 +1499,7 @@ class JavascriptParser extends Parser { return new BasicEvaluatedExpression() .setArray(result) .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); }); this.hooks.evaluate .for("ConditionalExpression") @@ -1505,12 +1514,16 @@ class JavascriptParser extends Parser { const alternate = this.evaluateExpression(expr.alternate); res = new BasicEvaluatedExpression(); if (consequent.isConditional()) { - res.setOptions(consequent.options); + res.setOptions( + /** @type {BasicEvaluatedExpression[]} */ (consequent.options) + ); } else { res.setOptions([consequent]); } if (alternate.isConditional()) { - res.addOptions(alternate.options); + res.addOptions( + /** @type {BasicEvaluatedExpression[]} */ (alternate.options) + ); } else { res.addOptions([alternate]); } @@ -1520,7 +1533,7 @@ class JavascriptParser extends Parser { ); if (condition.couldHaveSideEffects()) res.setSideEffects(); } - res.setRange(expr.range); + res.setRange(/** @type {Range} */ (expr.range)); return res; }); this.hooks.evaluate @@ -1538,7 +1551,7 @@ class JavascriptParser extends Parser { if (!items.every(Boolean)) return; return new BasicEvaluatedExpression() .setItems(items) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); }); this.hooks.evaluate .for("ChainExpression") @@ -1573,11 +1586,13 @@ class JavascriptParser extends Parser { } while (optionalExpressionsStack.length > 0) { - const expression = optionalExpressionsStack.pop(); + const expression = + /** @type {Expression} */ + (optionalExpressionsStack.pop()); const evaluated = this.evaluateExpression(expression); if (evaluated.asNullish()) { - return evaluated.setRange(_expr.range); + return evaluated.setRange(/** @type {Range} */ (_expr.range)); } } return this.evaluateExpression(expr.expression); @@ -2696,6 +2711,9 @@ class JavascriptParser extends Parser { } } + /** + * @param {TODO} expression expression + */ walkExpression(expression) { switch (expression.type) { case "ArrayExpression": @@ -3423,10 +3441,10 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {MemberExpression} expr expression info - * @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks - * @param {function(string): any} defined callback when variable is defined + * @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 - * @returns {R} result of hook + * @returns {R | undefined} result of hook */ callHooksForExpressionWithFallback( hookMap, @@ -3458,7 +3476,7 @@ class JavascriptParser extends Parser { * @param {HookMap>} hookMap hooks the should be called * @param {string} name key in map * @param {AsArray} args args for the hook - * @returns {R} result of hook + * @returns {R | undefined} result of hook */ callHooksForName(hookMap, name, ...args) { return this.callHooksForNameWithFallback( @@ -3476,7 +3494,7 @@ class JavascriptParser extends Parser { * @param {HookMap>} hookMap hooks that should be called * @param {ExportedVariableInfo} info variable info * @param {AsArray} args args for the hook - * @returns {R} result of hook + * @returns {R | undefined} result of hook */ callHooksForInfo(hookMap, info, ...args) { return this.callHooksForInfoWithFallback( @@ -3493,10 +3511,10 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {ExportedVariableInfo} info variable info - * @param {function(string): any} fallback callback when variable in not handled by hooks - * @param {function(): any} defined callback when variable is defined + * @param {(function(string): any) | undefined} fallback callback when variable in not handled by hooks + * @param {(function(): any) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook - * @returns {R} result of hook + * @returns {R | undefined} result of hook */ callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { let name; @@ -3543,10 +3561,10 @@ class JavascriptParser extends Parser { * @template R * @param {HookMap>} hookMap hooks the should be called * @param {string} name key in map - * @param {function(string): any} fallback callback when variable in not handled by hooks - * @param {function(): any} defined callback when variable is defined + * @param {(function(string): any) | undefined} fallback callback when variable in not handled by hooks + * @param {(function(): any) | undefined} defined callback when variable is defined * @param {AsArray} args args for the hook - * @returns {R} result of hook + * @returns {R | undefined} result of hook */ callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { return this.callHooksForInfoWithFallback( @@ -3586,6 +3604,12 @@ class JavascriptParser extends Parser { this.scope = oldScope; } + /** + * @param {boolean} hasThis true, when this is defined + * @param {any} params scope params + * @param {function(): void} fn inner function + * @returns {void} + */ inClassScope(hasThis, params, fn) { const oldScope = this.scope; this.scope = { @@ -3610,6 +3634,12 @@ class JavascriptParser extends Parser { this.scope = oldScope; } + /** + * @param {boolean} hasThis true, when this is defined + * @param {any} params scope params + * @param {function(): void} fn inner function + * @returns {void} + */ inFunctionScope(hasThis, params, fn) { const oldScope = this.scope; this.scope = { @@ -3634,6 +3664,10 @@ class JavascriptParser extends Parser { this.scope = oldScope; } + /** + * @param {function(): void} fn inner function + * @returns {void} + */ inBlockScope(fn) { const oldScope = this.scope; this.scope = { @@ -3650,15 +3684,28 @@ class JavascriptParser extends Parser { this.scope = oldScope; } + /** + * @param {Array} statements statements + */ detectMode(statements) { const isLiteral = statements.length >= 1 && statements[0].type === "ExpressionStatement" && statements[0].expression.type === "Literal"; - if (isLiteral && statements[0].expression.value === "use strict") { + if ( + isLiteral && + /** @type {Literal} */ + (/** @type {ExpressionStatement} */ (statements[0]).expression).value === + "use strict" + ) { this.scope.isStrict = true; } - if (isLiteral && statements[0].expression.value === "use asm") { + if ( + isLiteral && + /** @type {Literal} */ + (/** @type {ExpressionStatement} */ (statements[0]).expression).value === + "use asm" + ) { this.scope.isAsmJs = true; } } @@ -3761,7 +3808,7 @@ class JavascriptParser extends Parser { } /** - * @param {Expression} expression expression node + * @param {TODO} expression expression node * @returns {BasicEvaluatedExpression} evaluation result */ evaluateExpression(expression) { @@ -3779,7 +3826,7 @@ class JavascriptParser extends Parser { // ignore error } return new BasicEvaluatedExpression() - .setRange(expression.range) + .setRange(/** @type {Range} */ (expression.range)) .setExpression(expression); } @@ -4024,43 +4071,52 @@ class JavascriptParser extends Parser { case "VariableDeclaration": return expr.declarations.every(decl => - this.isPure(decl.init, decl.range[0]) + this.isPure(decl.init, /** @type {Range} */ (decl.range)[0]) ); case "ConditionalExpression": return ( this.isPure(expr.test, commentsStartPos) && - this.isPure(expr.consequent, expr.test.range[1]) && - this.isPure(expr.alternate, expr.consequent.range[1]) + this.isPure( + expr.consequent, + /** @type {Range} */ (expr.test.range)[1] + ) && + this.isPure( + expr.alternate, + /** @type {Range} */ (expr.consequent.range)[1] + ) ); case "LogicalExpression": return ( this.isPure(expr.left, commentsStartPos) && - this.isPure(expr.right, expr.left.range[1]) + this.isPure(expr.right, /** @type {Range} */ (expr.left.range)[1]) ); case "SequenceExpression": return expr.expressions.every(expr => { const pureFlag = this.isPure(expr, commentsStartPos); - commentsStartPos = expr.range[1]; + commentsStartPos = /** @type {Range} */ (expr.range)[1]; return pureFlag; }); case "CallExpression": { const pureFlag = - expr.range[0] - commentsStartPos > 12 && - this.getComments([commentsStartPos, expr.range[0]]).some( + /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 && + this.getComments([ + commentsStartPos, + /** @type {Range} */ (expr.range)[0] + ]).some( comment => comment.type === "Block" && /^\s*(#|@)__PURE__\s*$/.test(comment.value) ); if (!pureFlag) return false; - commentsStartPos = expr.callee.range[1]; + commentsStartPos = /** @type {Range} */ (expr.callee.range)[1]; return expr.arguments.every(arg => { if (arg.type === "SpreadElement") return false; const pureFlag = this.isPure(arg, commentsStartPos); - commentsStartPos = arg.range[1]; + commentsStartPos = /** @type {Range} */ (arg.range)[1]; return pureFlag; }); } @@ -4114,6 +4170,10 @@ class JavascriptParser extends Parser { this.semicolons.delete(pos); } + /** + * @param {Expression} expr expression + * @returns {boolean} true, when the expression is a statement level expression + */ isStatementLevelExpression(expr) { const currentStatement = this.statementPath[this.statementPath.length - 1]; return ( @@ -4303,7 +4363,7 @@ class JavascriptParser extends Parser { /** * @param {string} varName variable name - * @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that + * @returns {{name: string, info: VariableInfo | string} | undefined} name of the free variable and variable info for that */ getFreeInfoFromVariable(varName) { const info = this.getVariableInfo(varName); @@ -4383,7 +4443,7 @@ class JavascriptParser extends Parser { /** * @param {MemberExpression} expression an expression - * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info + * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]} | undefined} name info */ getNameForExpression(expression) { return this.getMemberExpressionInfo( @@ -4407,7 +4467,7 @@ class JavascriptParser extends Parser { sourceType: type === "auto" ? "module" : type }; - /** @type {AnyNode} */ + /** @type {AnyNode | undefined} */ let ast; let error; let threw = false; diff --git a/lib/javascript/JavascriptParserHelpers.js b/lib/javascript/JavascriptParserHelpers.js index fc1dea816ac..4d5298876e2 100644 --- a/lib/javascript/JavascriptParserHelpers.js +++ b/lib/javascript/JavascriptParserHelpers.js @@ -9,20 +9,26 @@ const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); const ConstDependency = require("../dependencies/ConstDependency"); const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); -/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("estree").Expression} Expression */ /** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ /** @typedef {import("./JavascriptParser")} JavascriptParser */ +/** @typedef {import("./JavascriptParser").Range} Range */ /** * @param {JavascriptParser} parser the parser * @param {string} value the const value * @param {string[]=} runtimeRequirements runtime requirements - * @returns {function(ExpressionNode): true} plugin function + * @returns {function(Expression): true} plugin function */ exports.toConstantDependency = (parser, value, runtimeRequirements) => { return function constDependency(expr) { - const dep = new ConstDependency(value, expr.range, runtimeRequirements); - dep.loc = expr.loc; + const dep = new ConstDependency( + value, + /** @type {Range} */ (expr.range), + runtimeRequirements + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); parser.state.module.addPresentationalDependency(dep); return true; }; @@ -30,33 +36,37 @@ exports.toConstantDependency = (parser, value, runtimeRequirements) => { /** * @param {string} value the string value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @returns {function(Expression): BasicEvaluatedExpression} plugin function */ exports.evaluateToString = value => { return function stringExpression(expr) { - return new BasicEvaluatedExpression().setString(value).setRange(expr.range); + return new BasicEvaluatedExpression() + .setString(value) + .setRange(/** @type {Range} */ (expr.range)); }; }; /** * @param {number} value the number value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @returns {function(Expression): BasicEvaluatedExpression} plugin function */ exports.evaluateToNumber = value => { return function stringExpression(expr) { - return new BasicEvaluatedExpression().setNumber(value).setRange(expr.range); + return new BasicEvaluatedExpression() + .setNumber(value) + .setRange(/** @type {Range} */ (expr.range)); }; }; /** * @param {boolean} value the boolean value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @returns {function(Expression): BasicEvaluatedExpression} plugin function */ exports.evaluateToBoolean = value => { return function booleanExpression(expr) { return new BasicEvaluatedExpression() .setBoolean(value) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); }; }; @@ -65,14 +75,14 @@ exports.evaluateToBoolean = value => { * @param {string} rootInfo rootInfo * @param {function(): string[]} getMembers getMembers * @param {boolean|null=} truthy is truthy, null if nullish - * @returns {function(ExpressionNode): BasicEvaluatedExpression} callback + * @returns {function(Expression): BasicEvaluatedExpression} callback */ exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { return function identifierExpression(expr) { let evaluatedExpression = new BasicEvaluatedExpression() .setIdentifier(identifier, rootInfo, getMembers) .setSideEffects(false) - .setRange(expr.range); + .setRange(/** @type {Range} */ (expr.range)); switch (truthy) { case true: evaluatedExpression.setTruthy(); @@ -89,14 +99,26 @@ exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { }; }; +/** + * @param {JavascriptParser} parser the parser + * @param {string} message the message + * @returns {function(Expression): boolean | undefined} callback to handle unsupported expression + */ exports.expressionIsUnsupported = (parser, message) => { return function unsupportedExpression(expr) { - const dep = new ConstDependency("(void 0)", expr.range, null); - dep.loc = expr.loc; + const dep = new ConstDependency( + "(void 0)", + /** @type {Range} */ (expr.range), + null + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); parser.state.module.addPresentationalDependency(dep); if (!parser.state.module) return; parser.state.module.addWarning( - new UnsupportedFeatureWarning(message, expr.loc) + new UnsupportedFeatureWarning( + message, + /** @type {SourceLocation} */ (expr.loc) + ) ); return true; }; diff --git a/lib/performance/SizeLimitsPlugin.js b/lib/performance/SizeLimitsPlugin.js index afbca68de79..ad1637e301c 100644 --- a/lib/performance/SizeLimitsPlugin.js +++ b/lib/performance/SizeLimitsPlugin.js @@ -95,7 +95,7 @@ module.exports = class SizeLimitsPlugin { } const size = info.size || source.size(); - if (size > assetSizeLimit) { + if (size > /** @type {number} */ (assetSizeLimit)) { assetsOverSizeLimit.push({ name, size @@ -114,7 +114,7 @@ module.exports = class SizeLimitsPlugin { for (const [name, entry] of compilation.entrypoints) { const size = getEntrypointSize(entry); - if (size > entrypointSizeLimit) { + if (size > /** @type {number} */ (entrypointSizeLimit)) { entrypointsOverLimit.push({ name: name, size: size, @@ -131,14 +131,17 @@ module.exports = class SizeLimitsPlugin { // if !1, then 2, if !2 return if (assetsOverSizeLimit.length > 0) { warnings.push( - new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) + new AssetsOverSizeLimitWarning( + assetsOverSizeLimit, + /** @type {number} */ (assetSizeLimit) + ) ); } if (entrypointsOverLimit.length > 0) { warnings.push( new EntrypointsOverSizeLimitWarning( entrypointsOverLimit, - entrypointSizeLimit + /** @type {number} */ (entrypointSizeLimit) ) ); } diff --git a/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js b/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js index 1924294bc6e..8b4f7782264 100644 --- a/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +++ b/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js @@ -7,6 +7,7 @@ const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { @@ -27,7 +28,8 @@ class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { */ generate() { const { runtimeFunction, runtimeHandlers } = this; - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; return Template.asString([ `${runtimeHandlers} = {};`, `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [ diff --git a/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js b/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js index e2cb3a849a5..112c11622c0 100644 --- a/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +++ b/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js @@ -9,6 +9,7 @@ const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { @@ -24,8 +25,10 @@ class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { startupChunks, chunk } = this; - const { runtimeTemplate } = this.compilation; + const { startupChunks } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); + const { runtimeTemplate } = compilation; return Template.asString( startupChunks.map( ({ onChunks, chunks }) => diff --git a/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js b/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js index 8e68da61451..72eb040dc7a 100644 --- a/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +++ b/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js @@ -8,6 +8,7 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { @@ -24,7 +25,8 @@ class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { */ generate() { const { chunkMap } = this; - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const body = [ "var chunks = chunkToChildrenMap[chunkId];", `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` diff --git a/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js b/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js index bc5ec7530c1..2a3efe8c35a 100644 --- a/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +++ b/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js @@ -8,6 +8,7 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { @@ -24,7 +25,8 @@ class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { */ generate() { const { chunkMap } = this; - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const body = [ "var chunks = chunkToChildrenMap[chunkId];", `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` diff --git a/lib/rules/BasicEffectRulePlugin.js b/lib/rules/BasicEffectRulePlugin.js index f265b3b80cf..7043f3b0637 100644 --- a/lib/rules/BasicEffectRulePlugin.js +++ b/lib/rules/BasicEffectRulePlugin.js @@ -8,6 +8,10 @@ /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ class BasicEffectRulePlugin { + /** + * @param {string} ruleProperty the rule property + * @param {string=} effectType the effect type + */ constructor(ruleProperty, effectType) { this.ruleProperty = ruleProperty; this.effectType = effectType || ruleProperty; diff --git a/lib/rules/BasicMatcherRulePlugin.js b/lib/rules/BasicMatcherRulePlugin.js index 1c349436170..7bfd13dc454 100644 --- a/lib/rules/BasicMatcherRulePlugin.js +++ b/lib/rules/BasicMatcherRulePlugin.js @@ -9,6 +9,11 @@ /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ class BasicMatcherRulePlugin { + /** + * @param {string} ruleProperty the rule property + * @param {string=} dataProperty the data property + * @param {boolean=} invert if true, inverts the condition + */ constructor(ruleProperty, dataProperty, invert) { this.ruleProperty = ruleProperty; this.dataProperty = dataProperty || ruleProperty; diff --git a/lib/runtime/AsyncModuleRuntimeModule.js b/lib/runtime/AsyncModuleRuntimeModule.js index db6b24f82e3..aaa8316e437 100644 --- a/lib/runtime/AsyncModuleRuntimeModule.js +++ b/lib/runtime/AsyncModuleRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class AsyncModuleRuntimeModule extends HelperRuntimeModule { constructor() { super("async module"); @@ -17,7 +19,8 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const fn = RuntimeGlobals.asyncModule; return Template.asString([ 'var webpackQueues = typeof Symbol === "function" ? Symbol("webpack queues") : "__webpack_queues__";', diff --git a/lib/runtime/AutoPublicPathRuntimeModule.js b/lib/runtime/AutoPublicPathRuntimeModule.js index 5cc1342f104..fa8c9c5bfd9 100644 --- a/lib/runtime/AutoPublicPathRuntimeModule.js +++ b/lib/runtime/AutoPublicPathRuntimeModule.js @@ -10,6 +10,8 @@ const Template = require("../Template"); const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin"); const { getUndoPath } = require("../util/identifier"); +/** @typedef {import("../Compilation")} Compilation */ + class AutoPublicPathRuntimeModule extends RuntimeModule { constructor() { super("publicPath", RuntimeModule.STAGE_BASIC); @@ -19,7 +21,7 @@ class AutoPublicPathRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { scriptType, importMetaName, path } = compilation.outputOptions; const chunkName = compilation.getPath( JavascriptModulesPlugin.getChunkFilenameTemplate( diff --git a/lib/runtime/BaseUriRuntimeModule.js b/lib/runtime/BaseUriRuntimeModule.js index b6c8faa437e..fcf2a82387c 100644 --- a/lib/runtime/BaseUriRuntimeModule.js +++ b/lib/runtime/BaseUriRuntimeModule.js @@ -9,6 +9,7 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); /** @typedef {import("../../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */ +/** @typedef {import("../Chunk")} Chunk */ class BaseUriRuntimeModule extends RuntimeModule { constructor() { @@ -19,8 +20,7 @@ class BaseUriRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { chunk } = this; - + const chunk = /** @type {Chunk} */ (this.chunk); const options = /** @type {EntryDescriptionNormalized} */ (chunk.getEntryOptions()); diff --git a/lib/runtime/CompatGetDefaultExportRuntimeModule.js b/lib/runtime/CompatGetDefaultExportRuntimeModule.js index 4947bcc62aa..9549a57eeda 100644 --- a/lib/runtime/CompatGetDefaultExportRuntimeModule.js +++ b/lib/runtime/CompatGetDefaultExportRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { constructor() { super("compat get default export"); @@ -17,7 +19,8 @@ class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const fn = RuntimeGlobals.compatGetDefaultExport; return Template.asString([ "// getDefaultExport function for compatibility with non-harmony modules", diff --git a/lib/runtime/CompatRuntimeModule.js b/lib/runtime/CompatRuntimeModule.js index ed9d9aff984..f85e1796bdb 100644 --- a/lib/runtime/CompatRuntimeModule.js +++ b/lib/runtime/CompatRuntimeModule.js @@ -7,6 +7,9 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../MainTemplate")} MainTemplate */ class CompatRuntimeModule extends RuntimeModule { @@ -19,7 +22,9 @@ class CompatRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { chunkGraph, chunk, compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const { runtimeTemplate, mainTemplate, diff --git a/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js b/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js index 6c2157eed39..d3d1d8fb5c8 100644 --- a/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +++ b/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { constructor() { super("create fake namespace object"); @@ -17,7 +19,8 @@ class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const fn = RuntimeGlobals.createFakeNamespaceObject; return Template.asString([ `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction( diff --git a/lib/runtime/CreateScriptRuntimeModule.js b/lib/runtime/CreateScriptRuntimeModule.js index ad174fa4d93..f2cd55242c1 100644 --- a/lib/runtime/CreateScriptRuntimeModule.js +++ b/lib/runtime/CreateScriptRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class CreateScriptRuntimeModule extends HelperRuntimeModule { constructor() { super("trusted types script"); @@ -17,7 +19,7 @@ class CreateScriptRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate, outputOptions } = compilation; const { trustedTypes } = outputOptions; const fn = RuntimeGlobals.createScript; diff --git a/lib/runtime/CreateScriptUrlRuntimeModule.js b/lib/runtime/CreateScriptUrlRuntimeModule.js index 63a5b0eada2..d598b51b368 100644 --- a/lib/runtime/CreateScriptUrlRuntimeModule.js +++ b/lib/runtime/CreateScriptUrlRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { constructor() { super("trusted types script url"); @@ -17,7 +19,7 @@ class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate, outputOptions } = compilation; const { trustedTypes } = outputOptions; const fn = RuntimeGlobals.createScriptUrl; diff --git a/lib/runtime/DefinePropertyGettersRuntimeModule.js b/lib/runtime/DefinePropertyGettersRuntimeModule.js index 5fce2be9cc1..e229b5227e7 100644 --- a/lib/runtime/DefinePropertyGettersRuntimeModule.js +++ b/lib/runtime/DefinePropertyGettersRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { constructor() { super("define property getters"); @@ -17,7 +19,8 @@ class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const fn = RuntimeGlobals.definePropertyGetters; return Template.asString([ "// define getter functions for harmony exports", diff --git a/lib/runtime/EnsureChunkRuntimeModule.js b/lib/runtime/EnsureChunkRuntimeModule.js index 999c96d7dd7..b0344b9cea5 100644 --- a/lib/runtime/EnsureChunkRuntimeModule.js +++ b/lib/runtime/EnsureChunkRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Compilation")} Compilation */ + class EnsureChunkRuntimeModule extends RuntimeModule { /** * @param {ReadonlySet} runtimeRequirements runtime requirements @@ -21,7 +23,8 @@ class EnsureChunkRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; // Check if there are non initial chunks which need to be imported using require-ensure if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) { const withFetchPriority = this.runtimeRequirements.has( diff --git a/lib/runtime/GetChunkFilenameRuntimeModule.js b/lib/runtime/GetChunkFilenameRuntimeModule.js index eef169fdff5..c2f6f7d6fc6 100644 --- a/lib/runtime/GetChunkFilenameRuntimeModule.js +++ b/lib/runtime/GetChunkFilenameRuntimeModule.js @@ -10,6 +10,7 @@ const Template = require("../Template"); const { first } = require("../util/SetHelpers"); /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Compilation").AssetInfo} AssetInfo */ /** @typedef {import("../Compilation").PathData} PathData */ @@ -37,15 +38,10 @@ class GetChunkFilenameRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { - global, - chunk, - chunkGraph, - contentType, - getFilenameForChunk, - allChunks, - compilation - } = this; + const { global, contentType, getFilenameForChunk, allChunks } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const { runtimeTemplate } = compilation; /** @type {Map>} */ diff --git a/lib/runtime/GetFullHashRuntimeModule.js b/lib/runtime/GetFullHashRuntimeModule.js index fa2908443c4..d555735e78a 100644 --- a/lib/runtime/GetFullHashRuntimeModule.js +++ b/lib/runtime/GetFullHashRuntimeModule.js @@ -19,9 +19,10 @@ class GetFullHashRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; return `${RuntimeGlobals.getFullHash} = ${runtimeTemplate.returningFunction( - JSON.stringify(this.compilation.hash || "XXXX") + JSON.stringify(compilation.hash || "XXXX") )}`; } } diff --git a/lib/runtime/GetMainFilenameRuntimeModule.js b/lib/runtime/GetMainFilenameRuntimeModule.js index cd9a6937b49..e1976bad2c8 100644 --- a/lib/runtime/GetMainFilenameRuntimeModule.js +++ b/lib/runtime/GetMainFilenameRuntimeModule.js @@ -8,6 +8,7 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compilation")} Compilation */ class GetMainFilenameRuntimeModule extends RuntimeModule { @@ -26,7 +27,9 @@ class GetMainFilenameRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { global, filename, compilation, chunk } = this; + const { global, filename } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); const { runtimeTemplate } = compilation; const url = compilation.getPath(JSON.stringify(filename), { hash: `" + ${RuntimeGlobals.getFullHash}() + "`, diff --git a/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js b/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js index 53e6f2914d9..f4691d42616 100644 --- a/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +++ b/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { /** * @param {ReadonlySet} runtimeRequirements runtime requirements @@ -21,7 +23,7 @@ class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate, outputOptions } = compilation; const { trustedTypes } = outputOptions; const fn = RuntimeGlobals.getTrustedTypesPolicy; diff --git a/lib/runtime/HasOwnPropertyRuntimeModule.js b/lib/runtime/HasOwnPropertyRuntimeModule.js index 1971794609f..384c7ef58ea 100644 --- a/lib/runtime/HasOwnPropertyRuntimeModule.js +++ b/lib/runtime/HasOwnPropertyRuntimeModule.js @@ -9,6 +9,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Compilation")} Compilation */ + class HasOwnPropertyRuntimeModule extends RuntimeModule { constructor() { super("hasOwnProperty shorthand"); @@ -18,7 +20,8 @@ class HasOwnPropertyRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; return Template.asString([ `${RuntimeGlobals.hasOwnProperty} = ${runtimeTemplate.returningFunction( diff --git a/lib/runtime/LoadScriptRuntimeModule.js b/lib/runtime/LoadScriptRuntimeModule.js index 59eabf72318..2231a3b191a 100644 --- a/lib/runtime/LoadScriptRuntimeModule.js +++ b/lib/runtime/LoadScriptRuntimeModule.js @@ -56,7 +56,7 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate, outputOptions } = compilation; const { scriptType, diff --git a/lib/runtime/MakeNamespaceObjectRuntimeModule.js b/lib/runtime/MakeNamespaceObjectRuntimeModule.js index c08dcabbc79..a2e9cc65fa0 100644 --- a/lib/runtime/MakeNamespaceObjectRuntimeModule.js +++ b/lib/runtime/MakeNamespaceObjectRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { constructor() { super("make namespace object"); @@ -17,7 +19,8 @@ class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; const fn = RuntimeGlobals.makeNamespaceObject; return Template.asString([ "// define __esModule on exports", diff --git a/lib/runtime/OnChunksLoadedRuntimeModule.js b/lib/runtime/OnChunksLoadedRuntimeModule.js index e870e6518a7..3a78fd966e8 100644 --- a/lib/runtime/OnChunksLoadedRuntimeModule.js +++ b/lib/runtime/OnChunksLoadedRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Compilation")} Compilation */ + class OnChunksLoadedRuntimeModule extends RuntimeModule { constructor() { super("chunk loaded"); @@ -17,7 +19,7 @@ class OnChunksLoadedRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate } = compilation; return Template.asString([ "var deferred = [];", diff --git a/lib/runtime/PublicPathRuntimeModule.js b/lib/runtime/PublicPathRuntimeModule.js index caa43f80425..cb1c37be387 100644 --- a/lib/runtime/PublicPathRuntimeModule.js +++ b/lib/runtime/PublicPathRuntimeModule.js @@ -8,6 +8,7 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); /** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../Compilation")} Compilation */ class PublicPathRuntimeModule extends RuntimeModule { /** @@ -22,7 +23,8 @@ class PublicPathRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation, publicPath } = this; + const { publicPath } = this; + const compilation = /** @type {Compilation} */ (this.compilation); return `${RuntimeGlobals.publicPath} = ${JSON.stringify( compilation.getPath(publicPath || "", { diff --git a/lib/runtime/RelativeUrlRuntimeModule.js b/lib/runtime/RelativeUrlRuntimeModule.js index 5699ecc38c2..e2ace885370 100644 --- a/lib/runtime/RelativeUrlRuntimeModule.js +++ b/lib/runtime/RelativeUrlRuntimeModule.js @@ -8,6 +8,8 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HelperRuntimeModule = require("./HelperRuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ + class RelativeUrlRuntimeModule extends HelperRuntimeModule { constructor() { super("relative url"); @@ -17,7 +19,8 @@ class RelativeUrlRuntimeModule extends HelperRuntimeModule { * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; return Template.asString([ `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, Template.indent([ diff --git a/lib/runtime/RuntimeIdRuntimeModule.js b/lib/runtime/RuntimeIdRuntimeModule.js index ca2313c7de5..979d545f2b7 100644 --- a/lib/runtime/RuntimeIdRuntimeModule.js +++ b/lib/runtime/RuntimeIdRuntimeModule.js @@ -7,6 +7,9 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ + class RuntimeIdRuntimeModule extends RuntimeModule { constructor() { super("runtimeId"); @@ -16,7 +19,8 @@ class RuntimeIdRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { chunkGraph, chunk } = this; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const runtime = chunk.runtime; if (typeof runtime !== "string") throw new Error("RuntimeIdRuntimeModule must be in a single runtime"); diff --git a/lib/runtime/StartupChunkDependenciesRuntimeModule.js b/lib/runtime/StartupChunkDependenciesRuntimeModule.js index 4b3bcd76cf0..f510316ba41 100644 --- a/lib/runtime/StartupChunkDependenciesRuntimeModule.js +++ b/lib/runtime/StartupChunkDependenciesRuntimeModule.js @@ -9,6 +9,10 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); const Template = require("../Template"); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ + class StartupChunkDependenciesRuntimeModule extends RuntimeModule { /** * @param {boolean} asyncChunkLoading use async chunk loading @@ -22,13 +26,15 @@ class StartupChunkDependenciesRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { chunkGraph, chunk, compilation } = this; - const { runtimeTemplate } = compilation; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); const chunkIds = Array.from( chunkGraph.getChunkEntryDependentChunksIterable(chunk) ).map(chunk => { return chunk.id; }); + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; return Template.asString([ `var next = ${RuntimeGlobals.startup};`, `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( diff --git a/lib/runtime/StartupEntrypointRuntimeModule.js b/lib/runtime/StartupEntrypointRuntimeModule.js index 3112e5e8aaa..635cd10c7e3 100644 --- a/lib/runtime/StartupEntrypointRuntimeModule.js +++ b/lib/runtime/StartupEntrypointRuntimeModule.js @@ -7,6 +7,7 @@ const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../MainTemplate")} MainTemplate */ class StartupEntrypointRuntimeModule extends RuntimeModule { @@ -22,7 +23,7 @@ class StartupEntrypointRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate } = compilation; return `${ RuntimeGlobals.startupEntrypoint diff --git a/lib/sharing/ConsumeSharedFallbackDependency.js b/lib/sharing/ConsumeSharedFallbackDependency.js index 126ba4ef410..bd6eefef13f 100644 --- a/lib/sharing/ConsumeSharedFallbackDependency.js +++ b/lib/sharing/ConsumeSharedFallbackDependency.js @@ -9,6 +9,9 @@ const ModuleDependency = require("../dependencies/ModuleDependency"); const makeSerializable = require("../util/makeSerializable"); class ConsumeSharedFallbackDependency extends ModuleDependency { + /** + * @param {string} request the request + */ constructor(request) { super(request); } diff --git a/lib/sharing/ConsumeSharedRuntimeModule.js b/lib/sharing/ConsumeSharedRuntimeModule.js index 9b5f0aaf69b..e81336af04a 100644 --- a/lib/sharing/ConsumeSharedRuntimeModule.js +++ b/lib/sharing/ConsumeSharedRuntimeModule.js @@ -17,10 +17,15 @@ const { /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Module")} Module */ /** @typedef {import("./ConsumeSharedModule")} ConsumeSharedModule */ class ConsumeSharedRuntimeModule extends RuntimeModule { + /** + * @param {ReadonlySet} runtimeRequirements runtime requirements + */ constructor(runtimeRequirements) { super("consumes", RuntimeModule.STAGE_ATTACH); this._runtimeRequirements = runtimeRequirements; @@ -30,11 +35,13 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation, chunkGraph } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); const { runtimeTemplate, codeGenerationResults } = compilation; const chunkToModuleMapping = {}; /** @type {Map} */ const moduleIdToSourceMapping = new Map(); + /** @type {(string | number)[]} */ const initialConsumes = []; /** * @@ -57,7 +64,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { ); } }; - for (const chunk of this.chunk.getAllAsyncChunks()) { + for (const chunk of /** @type {Chunk} */ (this.chunk).getAllAsyncChunks()) { const modules = chunkGraph.getChunkModulesIterableBySourceType( chunk, "consume-shared" @@ -65,7 +72,9 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { if (!modules) continue; addModules(modules, chunk, (chunkToModuleMapping[chunk.id] = [])); } - for (const chunk of this.chunk.getAllInitialChunks()) { + for (const chunk of /** @type {Chunk} */ ( + this.chunk + ).getAllInitialChunks()) { const modules = chunkGraph.getChunkModulesIterableBySourceType( chunk, "consume-shared" @@ -166,7 +175,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { ] )};`, `var warn = ${ - this.compilation.options.output.ignoreBrowserWarnings + compilation.outputOptions.ignoreBrowserWarnings ? runtimeTemplate.basicFunction("", "") : runtimeTemplate.basicFunction("msg", [ 'if (typeof console !== "undefined" && console.warn) console.warn(msg);' diff --git a/lib/sharing/ProvideSharedDependency.js b/lib/sharing/ProvideSharedDependency.js index 2f7246d667b..2df18a618ed 100644 --- a/lib/sharing/ProvideSharedDependency.js +++ b/lib/sharing/ProvideSharedDependency.js @@ -12,6 +12,13 @@ const makeSerializable = require("../util/makeSerializable"); /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ class ProvideSharedDependency extends Dependency { + /** + * @param {string} shareScope share scope + * @param {string} name module name + * @param {string | false} version version + * @param {string} request request + * @param {boolean} eager true, if this is an eager dependency + */ constructor(shareScope, name, version, request, eager) { super(); this.shareScope = shareScope; @@ -46,6 +53,10 @@ class ProvideSharedDependency extends Dependency { super.serialize(context); } + /** + * @param {ObjectDeserializerContext} context context + * @returns {ProvideSharedDependency} deserialize fallback dependency + */ static deserialize(context) { const { read } = context; const obj = new ProvideSharedDependency( diff --git a/lib/sharing/ProvideSharedModule.js b/lib/sharing/ProvideSharedModule.js index 23f67eb7dd9..ae8e38dcefe 100644 --- a/lib/sharing/ProvideSharedModule.js +++ b/lib/sharing/ProvideSharedModule.js @@ -174,6 +174,10 @@ class ProvideSharedModule extends Module { super.serialize(context); } + /** + * @param {ObjectDeserializerContext} context context + * @returns {ProvideSharedModule} deserialize fallback dependency + */ static deserialize(context) { const { read } = context; const obj = new ProvideSharedModule(read(), read(), read(), read(), read()); diff --git a/lib/sharing/ProvideSharedPlugin.js b/lib/sharing/ProvideSharedPlugin.js index e360fdc9abd..5f2eb65041c 100644 --- a/lib/sharing/ProvideSharedPlugin.js +++ b/lib/sharing/ProvideSharedPlugin.js @@ -42,27 +42,28 @@ class ProvideSharedPlugin { constructor(options) { validate(options); - /** @type {[string, ProvideOptions][]} */ - this._provides = parseOptions( - options.provides, - item => { - if (Array.isArray(item)) - throw new Error("Unexpected array of provides"); - /** @type {ProvideOptions} */ - const result = { - shareKey: item, - version: undefined, - shareScope: options.shareScope || "default", - eager: false - }; - return result; - }, - item => ({ - shareKey: item.shareKey, - version: item.version, - shareScope: item.shareScope || options.shareScope || "default", - eager: !!item.eager - }) + this._provides = /** @type {[string, ProvideOptions][]} */ ( + parseOptions( + options.provides, + item => { + if (Array.isArray(item)) + throw new Error("Unexpected array of provides"); + /** @type {ProvideOptions} */ + const result = { + shareKey: item, + version: undefined, + shareScope: options.shareScope || "default", + eager: false + }; + return result; + }, + item => ({ + shareKey: item.shareKey, + version: item.version, + shareScope: item.shareScope || options.shareScope || "default", + eager: !!item.eager + }) + ) ); this._provides.sort(([a], [b]) => { if (a < b) return -1; diff --git a/lib/sharing/ShareRuntimeModule.js b/lib/sharing/ShareRuntimeModule.js index 73ab44e6150..fca056424da 100644 --- a/lib/sharing/ShareRuntimeModule.js +++ b/lib/sharing/ShareRuntimeModule.js @@ -13,6 +13,10 @@ const { compareStrings } = require("../util/comparators"); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ + class ShareRuntimeModule extends RuntimeModule { constructor() { super("sharing"); @@ -22,15 +26,18 @@ class ShareRuntimeModule extends RuntimeModule { * @returns {string} runtime code */ generate() { - const { compilation, chunkGraph } = this; + const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate, codeGenerationResults, - outputOptions: { uniqueName } + outputOptions: { uniqueName, ignoreBrowserWarnings } } = compilation; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); /** @type {Map>>} */ const initCodePerScope = new Map(); - for (const chunk of this.chunk.getAllReferencedChunks()) { + for (const chunk of /** @type {Chunk} */ ( + this.chunk + ).getAllReferencedChunks()) { const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( chunk, "share-init", @@ -78,7 +85,7 @@ class ShareRuntimeModule extends RuntimeModule { "// runs all init snippets from all modules reachable", `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, `var warn = ${ - this.compilation.options.output.ignoreBrowserWarnings + ignoreBrowserWarnings ? runtimeTemplate.basicFunction("", "") : runtimeTemplate.basicFunction("msg", [ 'if (typeof console !== "undefined" && console.warn) console.warn(msg);' diff --git a/lib/sharing/resolveMatchedConfigs.js b/lib/sharing/resolveMatchedConfigs.js index 69f1d9633af..029e8886db0 100644 --- a/lib/sharing/resolveMatchedConfigs.js +++ b/lib/sharing/resolveMatchedConfigs.js @@ -66,7 +66,7 @@ exports.resolveMatchedConfigs = (compilation, configs) => { ); return resolve(); } - resolved.set(result, config); + resolved.set(/** @type {string} */ (result), config); resolve(); } ); diff --git a/lib/sharing/utils.js b/lib/sharing/utils.js index 555553066d8..b415df313d5 100644 --- a/lib/sharing/utils.js +++ b/lib/sharing/utils.js @@ -52,6 +52,11 @@ const DEF_GIT_PROTOCOL = "git+ssh://"; // thanks to https://github.com/npm/hosted-git-info/blob/latest/git-host-info.js const extractCommithashByDomain = { + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ "github.com": (pathname, hash) => { let [, user, project, type, commithash] = pathname.split("/", 5); if (type && type !== "tree") { @@ -74,6 +79,11 @@ const extractCommithashByDomain = { return commithash; }, + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ "gitlab.com": (pathname, hash) => { const path = pathname.slice(1); if (path.includes("/-/") || path.includes("/archive.tar.gz")) { @@ -81,7 +91,7 @@ const extractCommithashByDomain = { } const segments = path.split("/"); - let project = segments.pop(); + let project = /** @type {string} */ (segments.pop()); if (project.endsWith(".git")) { project = project.slice(0, -4); } @@ -93,6 +103,11 @@ const extractCommithashByDomain = { return hash; }, + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ "bitbucket.org": (pathname, hash) => { let [, user, project, aux] = pathname.split("/", 4); if (["get"].includes(aux)) { @@ -109,6 +124,11 @@ const extractCommithashByDomain = { return hash; }, + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ "gist.github.com": (pathname, hash) => { let [, user, project, aux] = pathname.split("/", 4); if (aux === "raw") { @@ -121,7 +141,6 @@ const extractCommithashByDomain = { } project = user; - user = null; } if (project.endsWith(".git")) { @@ -136,7 +155,7 @@ const extractCommithashByDomain = { * extract commit hash from parsed url * * @inner - * @param {Object} urlParsed parsed url + * @param {URL} urlParsed parsed url * @returns {string} commithash */ function getCommithash(urlParsed) { @@ -148,8 +167,16 @@ function getCommithash(urlParsed) { // eslint-disable-next-line no-empty } catch (e) {} - if (extractCommithashByDomain[hostname]) { - return extractCommithashByDomain[hostname](pathname, hash) || ""; + if ( + extractCommithashByDomain[ + /** @type {keyof extractCommithashByDomain} */ (hostname) + ] + ) { + return ( + extractCommithashByDomain[ + /** @type {keyof extractCommithashByDomain} */ (hostname) + ](pathname, hash) || "" + ); } return hash; diff --git a/lib/validateSchema.js b/lib/validateSchema.js index 2f84ac42ba9..fae211a358a 100644 --- a/lib/validateSchema.js +++ b/lib/validateSchema.js @@ -119,7 +119,9 @@ const validateSchema = (schema, options, validationConfiguration) => { ) ) { return `${formattedError}\nDid you mean ${ - DID_YOU_MEAN[params.additionalProperty] + DID_YOU_MEAN[ + /** @type {keyof DID_YOU_MEAN} */ (params.additionalProperty) + ] }?`; } @@ -129,7 +131,9 @@ const validateSchema = (schema, options, validationConfiguration) => { params.additionalProperty ) ) { - return `${formattedError}\n${REMOVED[params.additionalProperty]}?`; + return `${formattedError}\n${ + REMOVED[/** @type {keyof REMOVED} */ (params.additionalProperty)] + }?`; } if (!error.dataPath) { diff --git a/types.d.ts b/types.d.ts index 390aa1a68f2..849b152cfb9 100644 --- a/types.d.ts +++ b/types.d.ts @@ -27,6 +27,7 @@ import { ConditionalExpression, ContinueStatement, DebuggerStatement, + Directive, DoWhileStatement, EmptyStatement, ExportAllDeclaration, @@ -491,7 +492,7 @@ declare interface BaseResolveRequest { } declare abstract class BasicEvaluatedExpression { type: number; - range: [number, number]; + range?: [number, number]; falsy: boolean; truthy: boolean; nullish?: boolean; @@ -506,15 +507,89 @@ declare abstract class BasicEvaluatedExpression { array?: any[]; items?: BasicEvaluatedExpression[]; options?: BasicEvaluatedExpression[]; - prefix?: BasicEvaluatedExpression; - postfix?: BasicEvaluatedExpression; - wrappedInnerExpressions: BasicEvaluatedExpression[]; + prefix?: null | BasicEvaluatedExpression; + postfix?: null | BasicEvaluatedExpression; + wrappedInnerExpressions?: BasicEvaluatedExpression[]; identifier?: string | VariableInfoInterface; - rootInfo: string | VariableInfoInterface; - getMembers: () => string[]; - getMembersOptionals: () => boolean[]; - getMemberRanges: () => [number, number][]; - expression: NodeEstreeIndex; + rootInfo?: string | VariableInfoInterface; + getMembers?: () => string[]; + getMembersOptionals?: () => boolean[]; + getMemberRanges?: () => [number, number][]; + 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 + | FunctionDeclaration + | VariableDeclaration + | ClassDeclaration + | PrivateIdentifier + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration + | MethodDefinition + | PropertyDefinition + | VariableDeclarator + | Program + | SwitchCase + | CatchClause + | ObjectPattern + | ArrayPattern + | RestElement + | AssignmentPattern + | SpreadElement + | Property + | AssignmentProperty + | ClassBody + | ImportSpecifier + | ImportDefaultSpecifier + | ImportNamespaceSpecifier + | ExportSpecifier + | Super + | TemplateElement; isUnknown(): boolean; isNull(): boolean; isUndefined(): boolean; @@ -567,7 +642,7 @@ declare abstract class BasicEvaluatedExpression { * Creates a string representation of this evaluated expression. */ asString(): undefined | string; - setString(string?: any): BasicEvaluatedExpression; + setString(string: string): BasicEvaluatedExpression; setUndefined(): BasicEvaluatedExpression; setNull(): BasicEvaluatedExpression; @@ -606,8 +681,8 @@ declare abstract class BasicEvaluatedExpression { * Wraps an array of expressions with a prefix and postfix expression. */ setWrapped( - prefix: null | BasicEvaluatedExpression, - postfix: BasicEvaluatedExpression, + prefix: undefined | null | BasicEvaluatedExpression, + postfix: undefined | null | BasicEvaluatedExpression, innerExpressions: BasicEvaluatedExpression[] ): BasicEvaluatedExpression; @@ -662,7 +737,83 @@ declare abstract class BasicEvaluatedExpression { /** * Set the expression node for the expression. */ - setExpression(expression: NodeEstreeIndex): BasicEvaluatedExpression; + setExpression( + 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 + | FunctionDeclaration + | VariableDeclaration + | ClassDeclaration + | PrivateIdentifier + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration + | MethodDefinition + | PropertyDefinition + | VariableDeclarator + | Program + | SwitchCase + | CatchClause + | ObjectPattern + | ArrayPattern + | RestElement + | AssignmentPattern + | SpreadElement + | Property + | AssignmentProperty + | ClassBody + | ImportSpecifier + | ImportDefaultSpecifier + | ImportNamespaceSpecifier + | ExportSpecifier + | Super + | TemplateElement + ): BasicEvaluatedExpression; } declare interface BuildInfo { [index: string]: any; @@ -2196,7 +2347,7 @@ declare class ConcatenationScope { static isModuleReference(name: string): boolean; static matchModuleReference( name: string - ): ModuleReferenceOptions & { index: number }; + ): null | (ModuleReferenceOptions & { index: number }); static DEFAULT_EXPORT: string; static NAMESPACE_OBJECT_EXPORT: string; } @@ -2460,7 +2611,7 @@ declare class ConstDependency extends NullDependency { constructor( expression: string, range: number | [number, number], - runtimeRequirements?: string[] + runtimeRequirements?: null | string[] ); expression: string; range: number | [number, number]; @@ -5383,8 +5534,14 @@ declare class JavascriptParser extends Parser { unhandledExpressionMemberChain: HookMap< SyncBailHook<[Expression, string[]], boolean | void> >; - expressionConditionalOperator: SyncBailHook<[Expression], boolean | void>; - expressionLogicalOperator: SyncBailHook<[Expression], boolean | void>; + expressionConditionalOperator: SyncBailHook< + [ConditionalExpression], + boolean | void + >; + expressionLogicalOperator: SyncBailHook< + [LogicalExpression], + boolean | void + >; program: SyncBailHook<[Program, Comment[]], boolean | void>; finish: SyncBailHook<[Program, Comment[]], boolean | void>; }>; @@ -5448,7 +5605,7 @@ declare class JavascriptParser extends Parser { | ExportDefaultDeclaration | ExportAllDeclaration )[]; - prevStatement: + prevStatement?: | UnaryExpression | ArrayExpression | ArrowFunctionExpression @@ -5837,43 +5994,75 @@ declare class JavascriptParser extends Parser { callHooksForExpressionWithFallback( hookMap: HookMap>, expr: MemberExpression, - fallback: ( - arg0: string, - arg1: string | ScopeInfo | VariableInfo, - arg2: () => string[] - ) => any, - defined: (arg0: string) => any, + fallback: + | undefined + | (( + arg0: string, + arg1: string | ScopeInfo | VariableInfo, + arg2: () => string[] + ) => any), + defined: undefined | ((arg0: string) => any), ...args: AsArray - ): R; + ): undefined | R; callHooksForName( hookMap: HookMap>, name: string, ...args: AsArray - ): R; + ): undefined | R; callHooksForInfo( hookMap: HookMap>, info: ExportedVariableInfo, ...args: AsArray - ): R; + ): undefined | R; callHooksForInfoWithFallback( hookMap: HookMap>, info: ExportedVariableInfo, - fallback: (arg0: string) => any, - defined: () => any, + fallback: undefined | ((arg0: string) => any), + defined: undefined | (() => any), ...args: AsArray - ): R; + ): undefined | R; callHooksForNameWithFallback( hookMap: HookMap>, name: string, - fallback: (arg0: string) => any, - defined: () => any, + fallback: undefined | ((arg0: string) => any), + defined: undefined | (() => any), ...args: AsArray - ): R; + ): undefined | R; inScope(params: any, fn: () => void): void; - inClassScope(hasThis?: any, params?: any, fn?: any): void; - inFunctionScope(hasThis?: any, params?: any, fn?: any): void; - inBlockScope(fn?: any): void; - detectMode(statements?: any): void; + inClassScope(hasThis: boolean, params: any, fn: () => void): void; + inFunctionScope(hasThis: boolean, params: any, fn: () => void): void; + inBlockScope(fn: () => void): void; + detectMode( + statements: ( + | FunctionDeclaration + | VariableDeclaration + | ClassDeclaration + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration + | Directive + )[] + ): void; enterPatterns(patterns?: any, onIdent?: any): void; enterPattern(pattern?: any, onIdent?: any): void; enterIdentifier(pattern: Identifier, onIdent?: any): void; @@ -5881,7 +6070,7 @@ declare class JavascriptParser extends Parser { enterArrayPattern(pattern: ArrayPattern, onIdent?: any): void; enterRestElement(pattern: RestElement, onIdent?: any): void; enterAssignmentPattern(pattern: AssignmentPattern, onIdent?: any): void; - evaluateExpression(expression: Expression): BasicEvaluatedExpression; + evaluateExpression(expression?: any): BasicEvaluatedExpression; parseString(expression: Expression): string; parseCalculatedString(expression?: any): any; evaluate(source: string): BasicEvaluatedExpression; @@ -5925,7 +6114,7 @@ declare class JavascriptParser extends Parser { getComments(range: [number, number]): any[]; isAsiPosition(pos: number): boolean; unsetAsiPosition(pos: number): void; - isStatementLevelExpression(expr?: any): boolean; + isStatementLevelExpression(expr: Expression): boolean; getTagData(name?: any, tag?: any): any; tagVariable(name?: any, tag?: any, data?: any): void; defineVariable(name: string): void; @@ -5969,19 +6158,22 @@ declare class JavascriptParser extends Parser { membersOptionals: boolean[]; memberRanges: [number, number][]; }; - getFreeInfoFromVariable(varName: string): { - name: string; - info: string | VariableInfo; - }; + getFreeInfoFromVariable( + varName: string + ): undefined | { name: string; info: string | VariableInfo }; getMemberExpressionInfo( expression: MemberExpression, allowedTypes: number ): undefined | CallExpressionInfo | ExpressionExpressionInfo; - getNameForExpression(expression: MemberExpression): { - name: string; - rootInfo: ExportedVariableInfo; - getMembers: () => string[]; - }; + getNameForExpression( + expression: MemberExpression + ): + | undefined + | { + name: string; + rootInfo: ExportedVariableInfo; + getMembers: () => string[]; + }; static ALLOWED_MEMBER_TYPES_ALL: 3; static ALLOWED_MEMBER_TYPES_EXPRESSION: 2; static ALLOWED_MEMBER_TYPES_CALL_EXPRESSION: 1; @@ -7289,9 +7481,9 @@ declare class Module extends DependenciesBlock { get hash(): string; get renderedHash(): string; profile: null | ModuleProfile; - index: number; - index2: number; - depth: number; + index: null | number; + index2: null | number; + depth: null | number; issuer: null | Module; get usedExports(): null | boolean | SortableSet; get optimizationBailout(): ( @@ -7575,11 +7767,11 @@ declare class ModuleGraph { filterConnection: (arg0: ModuleGraphConnection) => boolean ): void; addExtraReason(module: Module, explanation: string): void; - getResolvedModule(dependency: Dependency): Module; + getResolvedModule(dependency: Dependency): null | Module; getConnection(dependency: Dependency): undefined | ModuleGraphConnection; - getModule(dependency: Dependency): Module; - getOrigin(dependency: Dependency): Module; - getResolvedOrigin(dependency: Dependency): Module; + getModule(dependency: Dependency): null | Module; + getOrigin(dependency: Dependency): null | Module; + getResolvedOrigin(dependency: Dependency): null | Module; getIncomingConnections(module: Module): Iterable; getOutgoingConnections(module: Module): Iterable; getIncomingConnectionsByOriginModule( @@ -7608,19 +7800,19 @@ declare class ModuleGraph { module: Module, runtime: RuntimeSpec ): null | boolean | SortableSet; - getPreOrderIndex(module: Module): number; - getPostOrderIndex(module: Module): number; + getPreOrderIndex(module: Module): null | number; + getPostOrderIndex(module: Module): null | number; setPreOrderIndex(module: Module, index: number): void; setPreOrderIndexIfUnset(module: Module, index: number): boolean; setPostOrderIndex(module: Module, index: number): void; setPostOrderIndexIfUnset(module: Module, index: number): boolean; - getDepth(module: Module): number; + getDepth(module: Module): null | number; setDepth(module: Module, depth: number): void; setDepthIfLower(module: Module, depth: number): boolean; isAsync(module: Module): boolean; setAsync(module: Module): void; getMeta(thing?: any): Object; - getMetaIfExisting(thing?: any): Object; + getMetaIfExisting(thing?: any): undefined | Object; freeze(cacheStage?: string): void; unfreeze(): void; cached( @@ -7661,11 +7853,11 @@ declare class ModuleGraphConnection { module: Module; weak: boolean; conditional: boolean; - condition: ( + condition?: ( arg0: ModuleGraphConnection, arg1: RuntimeSpec ) => ConnectionState; - explanations: Set; + explanations?: Set; clone(): ModuleGraphConnection; addCondition( condition: ( @@ -7988,7 +8180,7 @@ declare abstract class MultiStats { declare abstract class MultiWatching { watchings: Watching[]; compiler: MultiCompiler; - invalidate(callback?: any): void; + invalidate(callback?: CallbackFunction): void; suspend(): void; resume(): void; close(callback: CallbackFunction): void; @@ -8050,6 +8242,7 @@ declare class NoEmitOnErrorsPlugin { */ apply(compiler: Compiler): void; } +type Node = false | NodeOptions; declare class NodeEnvironmentPlugin { constructor(options: { /** @@ -8069,81 +8262,6 @@ declare class NodeEnvironmentPlugin { */ apply(compiler: Compiler): void; } -type NodeEstreeIndex = - | 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 - | FunctionDeclaration - | VariableDeclaration - | ClassDeclaration - | PrivateIdentifier - | ExpressionStatement - | BlockStatement - | StaticBlock - | EmptyStatement - | DebuggerStatement - | WithStatement - | ReturnStatement - | LabeledStatement - | BreakStatement - | ContinueStatement - | IfStatement - | SwitchStatement - | ThrowStatement - | TryStatement - | WhileStatement - | DoWhileStatement - | ForStatement - | ForInStatement - | ForOfStatement - | ImportDeclaration - | ExportNamedDeclaration - | ExportDefaultDeclaration - | ExportAllDeclaration - | MethodDefinition - | PropertyDefinition - | VariableDeclarator - | Program - | SwitchCase - | CatchClause - | ObjectPattern - | ArrayPattern - | RestElement - | AssignmentPattern - | SpreadElement - | Property - | AssignmentProperty - | ClassBody - | ImportSpecifier - | ImportDefaultSpecifier - | ImportNamespaceSpecifier - | ExportSpecifier - | Super - | TemplateElement; /** * Options object for node compatibility features. @@ -8194,7 +8312,6 @@ declare interface NodeTemplatePluginOptions { */ asyncChunkLoading?: boolean; } -type NodeWebpackOptions = false | NodeOptions; declare class NormalModule extends Module { constructor(__0: NormalModuleCreateData); request: string; @@ -12806,7 +12923,7 @@ declare interface UserResolveOptions { } declare abstract class VariableInfo { declaredScope: ScopeInfo; - freeName: string | true; + freeName?: string | true; tagInfo?: TagInfo; } declare interface VariableInfoInterface { @@ -13034,12 +13151,12 @@ declare class WebpackError extends Error { * Creates an instance of WebpackError. */ constructor(message?: string); - details: any; - module: Module; - loc: DependencyLocation; - hideStack: boolean; - chunk: Chunk; - file: string; + details?: string; + module?: null | Module; + loc?: SyntheticDependencyLocation | RealDependencyLocation; + hideStack?: boolean; + chunk?: Chunk; + file?: string; serialize(__0: ObjectSerializerContext): void; deserialize(__0: ObjectDeserializerContext): void; @@ -13087,7 +13204,7 @@ declare class WebpackOptionsApply extends OptionsApply { } declare class WebpackOptionsDefaulter { constructor(); - process(options?: any): any; + process(options: Configuration): WebpackOptionsNormalized; } /** @@ -13211,7 +13328,7 @@ declare interface WebpackOptionsNormalized { /** * Include polyfills or mocks for various node stuff. */ - node: NodeWebpackOptions; + node: Node; /** * Enables/Disables integrated optimizations. From 0df63a1a2588d8d207d27b780d28fd116ce3d049 Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Mon, 12 Jun 2023 21:09:12 +0300 Subject: [PATCH 3/5] test: fix --- lib/json/JsonGenerator.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/json/JsonGenerator.js b/lib/json/JsonGenerator.js index 2c8c49dedbe..d7074fc0ca7 100644 --- a/lib/json/JsonGenerator.js +++ b/lib/json/JsonGenerator.js @@ -172,7 +172,6 @@ class JsonGenerator extends Generator { ); } const exportsInfo = moduleGraph.getExportsInfo(module); - console.log(exportsInfo); /** @type {RawJsonData} */ let finalJson = typeof data === "object" && From fb93153a2e761514be05d27b1bb5b180d87e641f Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Mon, 12 Jun 2023 21:20:12 +0300 Subject: [PATCH 4/5] test: fix --- lib/wasm-async/AsyncWebAssemblyParser.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/wasm-async/AsyncWebAssemblyParser.js b/lib/wasm-async/AsyncWebAssemblyParser.js index 0b9c256c0d9..4a9632cbd56 100644 --- a/lib/wasm-async/AsyncWebAssemblyParser.js +++ b/lib/wasm-async/AsyncWebAssemblyParser.js @@ -12,6 +12,7 @@ const StaticExportsDependency = require("../dependencies/StaticExportsDependency const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); /** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ @@ -46,8 +47,9 @@ class WebAssemblyParser extends Parser { // flag it as async module const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo); buildInfo.strict = true; - buildInfo.exportsType = "namespace"; - buildInfo.async = true; + const BuildMeta = /** @type {BuildMeta} */ (state.module.buildMeta); + BuildMeta.exportsType = "namespace"; + BuildMeta.async = true; // parse it const program = decode(source, decoderOpts); From 5efc30a0b013bb2572ac2ddd78816ae20382a718 Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Wed, 14 Jun 2023 19:47:52 +0300 Subject: [PATCH 5/5] refactor: rebase --- lib/runtime/LoadScriptRuntimeModule.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/runtime/LoadScriptRuntimeModule.js b/lib/runtime/LoadScriptRuntimeModule.js index 2231a3b191a..b8e31a299dc 100644 --- a/lib/runtime/LoadScriptRuntimeModule.js +++ b/lib/runtime/LoadScriptRuntimeModule.js @@ -141,7 +141,7 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule { "if(!script) {", Template.indent([ "needAttach = true;", - createScript.call(code, this.chunk) + createScript.call(code, /** @type {Chunk} */ (this.chunk)) ]), "}", "inProgress[url] = [done];",