chore(types): more

This commit is contained in:
alexander.akait 2024-01-26 19:17:45 +03:00
parent 1c4bcfa36c
commit 3295f6c36f
20 changed files with 239 additions and 136 deletions

View File

@ -24,9 +24,9 @@ const ChunkNameRuntimeModule = require("./runtime/ChunkNameRuntimeModule");
const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule"); const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule");
/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */ /** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** /**
* @param {boolean | undefined} module true if ES module * @param {boolean | undefined} module true if ES module
@ -251,7 +251,7 @@ class APIPlugin {
? new BasicEvaluatedExpression().setNull() ? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString( : new BasicEvaluatedExpression().setString(
parser.state.module.layer parser.state.module.layer
) )
).setRange(/** @type {Range} */ (expr.range)) ).setRange(/** @type {Range} */ (expr.range))
); );
parser.hooks.evaluateTypeof parser.hooks.evaluateTypeof

View File

@ -1087,7 +1087,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
} }
/** /**
* @param {StatsOptions | string} optionsOrPreset stats option value * @param {StatsOptions | string | undefined} optionsOrPreset stats option value
* @param {CreateStatsOptionsContext} context context * @param {CreateStatsOptionsContext} context context
* @returns {NormalizedStatsOptions} normalized options * @returns {NormalizedStatsOptions} normalized options
*/ */

View File

@ -62,8 +62,8 @@ class ConditionalInitFragment extends InitFragment {
} }
/** /**
* @param {Context} context context * @param {GenerateContext} context context
* @returns {string|Source} the source code that will be included as initialization code * @returns {string | Source} the source code that will be included as initialization code
*/ */
getContent(context) { getContent(context) {
if (this.runtimeCondition === false || !this.content) return ""; if (this.runtimeCondition === false || !this.content) return "";
@ -79,7 +79,7 @@ class ConditionalInitFragment extends InitFragment {
} }
/** /**
* @param {Context} context context * @param {GenerateContext} context context
* @returns {string|Source=} the source code that will be included at the end of the module * @returns {string|Source=} the source code that will be included at the end of the module
*/ */
getEndContent(context) { getEndContent(context) {

View File

@ -23,9 +23,11 @@ const createHash = require("./util/createHash");
/** @typedef {import("estree").Expression} Expression */ /** @typedef {import("estree").Expression} Expression */
/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./NormalModule")} NormalModule */ /** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./logging/Logger").Logger} Logger */ /** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */ /** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
@ -66,7 +68,7 @@ class RuntimeValue {
* @returns {CodeValuePrimitive} code * @returns {CodeValuePrimitive} code
*/ */
exec(parser, valueCacheVersions, key) { exec(parser, valueCacheVersions, key) {
const buildInfo = parser.state.module.buildInfo; const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
if (this.options === true) { if (this.options === true) {
buildInfo.cacheable = false; buildInfo.cacheable = false;
} else { } else {
@ -136,19 +138,21 @@ const stringifyObj = (
let code; let code;
let arr = Array.isArray(obj); let arr = Array.isArray(obj);
if (arr) { if (arr) {
code = `[${obj code = `[${
.map(code => /** @type {any[]} */ (obj)
toCode( .map(code =>
code, toCode(
parser, code,
valueCacheVersions, parser,
key, valueCacheVersions,
runtimeTemplate, key,
logger, runtimeTemplate,
null logger,
null
)
) )
) .join(",")
.join(",")}]`; }]`;
} else { } else {
let keys = Object.keys(obj); let keys = Object.keys(obj);
if (objKeys) { if (objKeys) {
@ -157,7 +161,7 @@ const stringifyObj = (
} }
code = `{${keys code = `{${keys
.map(key => { .map(key => {
const code = obj[key]; const code = /** @type {{[k: string]: any}} */ (obj)[key];
return ( return (
JSON.stringify(key) + JSON.stringify(key) +
":" + ":" +
@ -263,6 +267,10 @@ const toCode = (
return strCode; return strCode;
}; };
/**
* @param {CodeValue} code code
* @returns {string | undefined} result
*/
const toCacheVersion = code => { const toCacheVersion = code => {
if (code === null) { if (code === null) {
return "null"; return "null";
@ -285,7 +293,7 @@ const toCacheVersion = code => {
if (typeof code === "object") { if (typeof code === "object") {
const items = Object.keys(code).map(key => ({ const items = Object.keys(code).map(key => ({
key, key,
value: toCacheVersion(code[key]) value: toCacheVersion(/** @type {Record<string, any>} */ (code)[key])
})); }));
if (items.some(({ value }) => value === undefined)) return undefined; if (items.some(({ value }) => value === undefined)) return undefined;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`; return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
@ -353,14 +361,21 @@ class DefinePlugin {
const handler = parser => { const handler = parser => {
const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
parser.hooks.program.tap(PLUGIN_NAME, () => { parser.hooks.program.tap(PLUGIN_NAME, () => {
const { buildInfo } = parser.state.module; const buildInfo = /** @type {BuildInfo} */ (
parser.state.module.buildInfo
);
if (!buildInfo.valueDependencies) if (!buildInfo.valueDependencies)
buildInfo.valueDependencies = new Map(); buildInfo.valueDependencies = new Map();
buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
}); });
/**
* @param {string} key key
*/
const addValueDependency = key => { const addValueDependency = key => {
const { buildInfo } = parser.state.module; const buildInfo = /** @type {BuildInfo} */ (
parser.state.module.buildInfo
);
buildInfo.valueDependencies.set( buildInfo.valueDependencies.set(
VALUE_DEP_PREFIX + key, VALUE_DEP_PREFIX + key,
compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key) compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
@ -376,7 +391,7 @@ class DefinePlugin {
/** /**
* Walk definitions * Walk definitions
* @param {Object} definitions Definitions map * @param {Record<string, CodeValue>} definitions Definitions map
* @param {string} prefix Prefix string * @param {string} prefix Prefix string
* @returns {void} * @returns {void}
*/ */
@ -389,7 +404,10 @@ class DefinePlugin {
!(code instanceof RuntimeValue) && !(code instanceof RuntimeValue) &&
!(code instanceof RegExp) !(code instanceof RegExp)
) { ) {
walkDefinitions(code, prefix + key + "."); walkDefinitions(
/** @type {Record<string, CodeValue>} */ (code),
prefix + key + "."
);
applyObjectDefine(prefix + key, code); applyObjectDefine(prefix + key, code);
return; return;
} }
@ -458,7 +476,7 @@ class DefinePlugin {
) )
); );
recurse = false; recurse = false;
res.setRange(expr.range); res.setRange(/** @type {Range} */ (expr.range));
return res; return res;
}); });
parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => { parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
@ -470,7 +488,7 @@ class DefinePlugin {
originalKey, originalKey,
runtimeTemplate, runtimeTemplate,
logger, logger,
!parser.isAsiPosition(expr.range[0]), !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
parser.destructuringAssignmentPropertiesFor(expr) parser.destructuringAssignmentPropertiesFor(expr)
); );
@ -517,7 +535,7 @@ class DefinePlugin {
: "typeof (" + codeCode + ")"; : "typeof (" + codeCode + ")";
const res = parser.evaluate(typeofCode); const res = parser.evaluate(typeofCode);
recurseTypeof = false; recurseTypeof = false;
res.setRange(expr.range); res.setRange(/** @type {Range} */ (expr.range));
return res; return res;
}); });
parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => { parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
@ -559,7 +577,7 @@ class DefinePlugin {
return new BasicEvaluatedExpression() return new BasicEvaluatedExpression()
.setTruthy() .setTruthy()
.setSideEffects(false) .setSideEffects(false)
.setRange(expr.range); .setRange(/** @type {Range} */ (expr.range));
}); });
parser.hooks.evaluateTypeof parser.hooks.evaluateTypeof
.for(key) .for(key)
@ -576,7 +594,7 @@ class DefinePlugin {
key, key,
runtimeTemplate, runtimeTemplate,
logger, logger,
!parser.isAsiPosition(expr.range[0]), !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
parser.destructuringAssignmentPropertiesFor(expr) parser.destructuringAssignmentPropertiesFor(expr)
); );
@ -622,7 +640,7 @@ class DefinePlugin {
/** /**
* Walk definitions * Walk definitions
* @param {Object} definitions Definitions map * @param {Record<string, CodeValue>} definitions Definitions map
* @param {string} prefix Prefix string * @param {string} prefix Prefix string
* @returns {void} * @returns {void}
*/ */
@ -649,7 +667,10 @@ class DefinePlugin {
!(code instanceof RuntimeValue) && !(code instanceof RuntimeValue) &&
!(code instanceof RegExp) !(code instanceof RegExp)
) { ) {
walkDefinitionsForValues(code, prefix + key + "."); walkDefinitionsForValues(
/** @type {Record<string, CodeValue>} */ (code),
prefix + key + "."
);
} }
}); });
}; };

View File

@ -129,7 +129,7 @@ class EvalSourceMapDevToolPlugin {
// Clone (flat) the sourcemap to ensure that the mutations below do not persist. // Clone (flat) the sourcemap to ensure that the mutations below do not persist.
sourceMap = { ...sourceMap }; sourceMap = { ...sourceMap };
const context = compiler.options.context; const context = /** @type {string} */ (compiler.options.context);
const root = compiler.root; const root = compiler.root;
const modules = sourceMap.sources.map(source => { const modules = sourceMap.sources.map(source => {
if (!source.startsWith("webpack://")) return source; if (!source.startsWith("webpack://")) return source;

View File

@ -36,11 +36,11 @@ const sortFragmentWithIndex = ([a, i], [b, j]) => {
}; };
/** /**
* @template Context * @template GenerateContext
*/ */
class InitFragment { class InitFragment {
/** /**
* @param {string | Source | undefined} content the source code that will be included as initialization code * @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} stage category of initialization code (contribute to order)
* @param {number} position position in the category (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=} key unique key to avoid emitting the same initialization code twice
@ -55,15 +55,15 @@ class InitFragment {
} }
/** /**
* @param {Context} context context * @param {GenerateContext} context context
* @returns {string | Source | undefined} the source code that will be included as initialization code * @returns {string | Source} the source code that will be included as initialization code
*/ */
getContent(context) { getContent(context) {
return this.content; return this.content;
} }
/** /**
* @param {Context} context context * @param {GenerateContext} context context
* @returns {string|Source=} the source code that will be included at the end of the module * @returns {string|Source=} the source code that will be included at the end of the module
*/ */
getEndContent(context) { getEndContent(context) {

View File

@ -65,6 +65,10 @@ class Stats {
}); });
} }
/**
* @param {(string|StatsOptions)=} options stats options
* @returns {string} string output
*/
toString(options) { toString(options) {
options = this.compilation.createStatsOptions(options, { options = this.compilation.createStatsOptions(options, {
forToString: true forToString: true

View File

@ -42,8 +42,8 @@ class AwaitDependenciesInitFragment extends InitFragment {
} }
/** /**
* @param {Context} context context * @param {GenerateContext} context context
* @returns {string|Source} the source code that will be included as initialization code * @returns {string | Source} the source code that will be included as initialization code
*/ */
getContent({ runtimeRequirements }) { getContent({ runtimeRequirements }) {
runtimeRequirements.add(RuntimeGlobals.module); runtimeRequirements.add(RuntimeGlobals.module);

View File

@ -35,7 +35,9 @@ const UnsupportedDependency = require("./UnsupportedDependency");
/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ /** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../javascript/JavascriptParser")} Parser */ /** @typedef {import("../javascript/JavascriptParser")} Parser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */
const PLUGIN_NAME = "AMDPlugin"; const PLUGIN_NAME = "AMDPlugin";
@ -135,6 +137,11 @@ class AMDPlugin {
const handler = (parser, parserOptions) => { const handler = (parser, parserOptions) => {
if (parserOptions.amd !== undefined && !parserOptions.amd) return; if (parserOptions.amd !== undefined && !parserOptions.amd) return;
/**
* @param {string} optionExpr option expression
* @param {string} rootName root name
* @param {function(): TODO} getMembers callback
*/
const tapOptionsHooks = (optionExpr, rootName, getMembers) => { const tapOptionsHooks = (optionExpr, rootName, getMembers) => {
parser.hooks.expression parser.hooks.expression
.for(optionExpr) .for(optionExpr)
@ -177,10 +184,10 @@ class AMDPlugin {
parser.hooks.expression.for("define").tap(PLUGIN_NAME, expr => { parser.hooks.expression.for("define").tap(PLUGIN_NAME, expr => {
const dep = new ConstDependency( const dep = new ConstDependency(
RuntimeGlobals.amdDefine, RuntimeGlobals.amdDefine,
expr.range, /** @type {Range} */ (expr.range),
[RuntimeGlobals.amdDefine] [RuntimeGlobals.amdDefine]
); );
dep.loc = expr.loc; dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep); parser.state.module.addPresentationalDependency(dep);
return true; return true;
}); });
@ -197,10 +204,10 @@ class AMDPlugin {
parser.hooks.rename.for("define").tap(PLUGIN_NAME, expr => { parser.hooks.rename.for("define").tap(PLUGIN_NAME, expr => {
const dep = new ConstDependency( const dep = new ConstDependency(
RuntimeGlobals.amdDefine, RuntimeGlobals.amdDefine,
expr.range, /** @type {Range} */ (expr.range),
[RuntimeGlobals.amdDefine] [RuntimeGlobals.amdDefine]
); );
dep.loc = expr.loc; dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep); parser.state.module.addPresentationalDependency(dep);
return false; return false;
}); });

View File

@ -18,7 +18,7 @@ const NullDependency = require("./NullDependency");
class AMDRequireArrayDependency extends NullDependency { class AMDRequireArrayDependency extends NullDependency {
/** /**
* @param {TODO} depsArray deps array * @param {TODO[]} depsArray deps array
* @param {Range} range range * @param {Range} range range
*/ */
constructor(depsArray, range) { constructor(depsArray, range) {
@ -81,6 +81,11 @@ AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate ext
source.replace(dep.range[0], dep.range[1] - 1, content); source.replace(dep.range[0], dep.range[1] - 1, content);
} }
/**
* @param {AMDRequireArrayDependency} dep the dependency for which the template should be applied
* @param {DependencyTemplateContext} templateContext the context object
* @returns {string} content
*/
getContent(dep, templateContext) { getContent(dep, templateContext) {
const requires = dep.depsArray.map(dependency => { const requires = dep.depsArray.map(dependency => {
return this.contentForDependency(dependency, templateContext); return this.contentForDependency(dependency, templateContext);
@ -88,6 +93,11 @@ AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate ext
return `[${requires.join(", ")}]`; return `[${requires.join(", ")}]`;
} }
/**
* @param {TODO} dep the dependency for which the template should be applied
* @param {DependencyTemplateContext} templateContext the context object
* @returns {string} content
*/
contentForDependency( contentForDependency(
dep, dep,
{ runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements }

View File

@ -19,13 +19,22 @@ const { getLocalModule } = require("./LocalModulesHelpers");
const UnsupportedDependency = require("./UnsupportedDependency"); const UnsupportedDependency = require("./UnsupportedDependency");
const getFunctionExpression = require("./getFunctionExpression"); const getFunctionExpression = require("./getFunctionExpression");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */
class AMDRequireDependenciesBlockParserPlugin { class AMDRequireDependenciesBlockParserPlugin {
constructor(options) { constructor(options) {
this.options = options; this.options = options;
} }
/**
* @param {JavascriptParser} parser the parser
* @param {Expression} expression expression
* @returns {boolean} need bind this
*/
processFunctionArgument(parser, expression) { processFunctionArgument(parser, expression) {
let bindThis = true; let bindThis = true;
const fnData = getFunctionExpression(expression); const fnData = getFunctionExpression(expression);
@ -259,9 +268,22 @@ class AMDRequireDependenciesBlockParserPlugin {
} }
} }
/**
* @param {DependencyLocation} loc location
* @param {string} request request
* @returns {AMDRequireDependenciesBlock} AMDRequireDependenciesBlock
*/
newRequireDependenciesBlock(loc, request) { newRequireDependenciesBlock(loc, request) {
return new AMDRequireDependenciesBlock(loc, request); return new AMDRequireDependenciesBlock(loc, request);
} }
/**
* @param {Range} outerRange outer range
* @param {Range} arrayRange array range
* @param {Range} functionRange function range
* @param {Range} errorCallbackRange error callback range
* @returns {AMDRequireDependency} dependency
*/
newRequireDependency( newRequireDependency(
outerRange, outerRange,
arrayRange, arrayRange,
@ -275,9 +297,21 @@ class AMDRequireDependenciesBlockParserPlugin {
errorCallbackRange errorCallbackRange
); );
} }
/**
* @param {string} request request
* @param {Range=} range range
* @returns {AMDRequireItemDependency} AMDRequireItemDependency
*/
newRequireItemDependency(request, range) { newRequireItemDependency(request, range) {
return new AMDRequireItemDependency(request, range); return new AMDRequireItemDependency(request, range);
} }
/**
* @param {TODO[]} depsArray deps array
* @param {Range} range range
* @returns {AMDRequireArrayDependency} AMDRequireArrayDependency
*/
newRequireArrayDependency(depsArray, range) { newRequireArrayDependency(depsArray, range) {
return new AMDRequireArrayDependency(depsArray, range); return new AMDRequireArrayDependency(depsArray, range);
} }

View File

@ -14,7 +14,7 @@ const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateA
class AMDRequireItemDependency extends ModuleDependency { class AMDRequireItemDependency extends ModuleDependency {
/** /**
* @param {string} request the request string * @param {string} request the request string
* @param {Range} range location in source code * @param {Range=} range location in source code
*/ */
constructor(request, range) { constructor(request, range) {
super(request); super(request);

View File

@ -71,7 +71,7 @@ class ExternalModuleInitFragment extends InitFragment {
/** /**
* @param {GenerateContext} context context * @param {GenerateContext} context context
* @returns {string|Source} the source code that will be included as initialization code * @returns {string | Source} the source code that will be included as initialization code
*/ */
getContent({ runtimeRequirements }) { getContent({ runtimeRequirements }) {
const namedImports = []; const namedImports = [];

View File

@ -130,8 +130,8 @@ class HarmonyExportInitFragment extends InitFragment {
} }
/** /**
* @param {Context} context context * @param {GenerateContext} context context
* @returns {string|Source} the source code that will be included as initialization code * @returns {string | Source} the source code that will be included as initialization code
*/ */
getContent({ runtimeTemplate, runtimeRequirements }) { getContent({ runtimeTemplate, runtimeRequirements }) {
runtimeRequirements.add(RuntimeGlobals.exports); runtimeRequirements.add(RuntimeGlobals.exports);

View File

@ -19,7 +19,7 @@ const NullDependency = require("./NullDependency");
class LocalModuleDependency extends NullDependency { class LocalModuleDependency extends NullDependency {
/** /**
* @param {LocalModule} localModule local module * @param {LocalModule} localModule local module
* @param {Range} range range * @param {Range | undefined} range range
* @param {boolean} callNew true, when the local module should be called with new * @param {boolean} callNew true, when the local module should be called with new
*/ */
constructor(localModule, range, callNew) { constructor(localModule, range, callNew) {

View File

@ -184,8 +184,9 @@ class WorkerPlugin {
} }
} }
const insertType = expr.properties.length > 0 ? "comma" : "single"; const insertType = expr.properties.length > 0 ? "comma" : "single";
const insertLocation = const insertLocation = /** @type {Range} */ (
expr.properties[expr.properties.length - 1].range[1]; expr.properties[expr.properties.length - 1].range
)[1];
return { return {
expressions, expressions,
otherElements, otherElements,

View File

@ -10,7 +10,7 @@
/** /**
* @param {Expression} expr expressions * @param {Expression} expr expressions
* @returns {{fn: TODO, expressions: (Expression | SpreadElement)[], needThis: boolean | undefined }} function expression with additional information * @returns {{fn: TODO, expressions: (Expression | SpreadElement)[], needThis: boolean | undefined } | undefined} function expression with additional information
*/ */
module.exports = expr => { module.exports = expr => {
// <FunctionExpression> // <FunctionExpression>

View File

@ -2355,8 +2355,8 @@ class JavascriptParser extends Parser {
} }
/** /**
* @param {Declaration} declaration * @param {Declaration} declaration declaration
* @param {TODO} onIdent * @param {TODO} onIdent on ident callback
*/ */
enterDeclaration(declaration, onIdent) { enterDeclaration(declaration, onIdent) {
switch (declaration.type) { switch (declaration.type) {
@ -4347,7 +4347,7 @@ class JavascriptParser extends Parser {
/** /**
* @param {string} name name * @param {string} name name
* @param {TODO} tag tag info * @param {TODO} tag tag info
* @param {TODO} data data * @param {TODO=} data data
*/ */
tagVariable(name, tag, data) { tagVariable(name, tag, data) {
const oldInfo = this.scope.definitions.get(name); const oldInfo = this.scope.definitions.get(name);

View File

@ -6,6 +6,7 @@
"use strict"; "use strict";
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
@ -17,7 +18,7 @@
* because minifiers treat quoted accessors differently. e.g. import { a } from "./module"; a["b"] vs a.b * because minifiers treat quoted accessors differently. e.g. import { a } from "./module"; a["b"] vs a.b
* @param {string[]} untrimmedIds chained ids * @param {string[]} untrimmedIds chained ids
* @param {Range} untrimmedRange range encompassing allIds * @param {Range} untrimmedRange range encompassing allIds
* @param {Range[]} ranges cumulative range of ids for each of allIds * @param {Range[] | undefined} ranges cumulative range of ids for each of allIds
* @param {ModuleGraph} moduleGraph moduleGraph * @param {ModuleGraph} moduleGraph moduleGraph
* @param {Dependency} dependency dependency * @param {Dependency} dependency dependency
* @returns {{trimmedIds: string[], trimmedRange: Range}} computed trimmed ids and cumulative range of those ids * @returns {{trimmedIds: string[], trimmedRange: Range}} computed trimmed ids and cumulative range of those ids
@ -44,7 +45,7 @@ exports.getTrimmedIdsAndRange = (
ranges === undefined ranges === undefined
? -1 /* trigger failure case below */ ? -1 /* trigger failure case below */
: ranges.length + (trimmedIds.length - untrimmedIds.length); : ranges.length + (trimmedIds.length - untrimmedIds.length);
if (idx < 0 || idx >= ranges.length) { if (idx < 0 || idx >= /** @type {Range[]} */ (ranges).length) {
// cspell:ignore minifiers // cspell:ignore minifiers
// Should not happen but we can't throw an error here because of backward compatibility with // Should not happen but we can't throw an error here because of backward compatibility with
// external plugins in wp5. Instead, we just disable trimming for now. This may break some minifiers. // external plugins in wp5. Instead, we just disable trimming for now. This may break some minifiers.
@ -52,7 +53,7 @@ exports.getTrimmedIdsAndRange = (
// TODO webpack 6 remove the "trimmedIds = ids" above and uncomment the following line instead. // TODO webpack 6 remove the "trimmedIds = ids" above and uncomment the following line instead.
// throw new Error("Missing range starts data for id replacement trimming."); // throw new Error("Missing range starts data for id replacement trimming.");
} else { } else {
trimmedRange = ranges[idx]; trimmedRange = /** @type {Range[]} */ (ranges)[idx];
} }
} }
@ -68,11 +69,11 @@ exports.getTrimmedIdsAndRange = (
* @returns {string[]} trimmed ids * @returns {string[]} trimmed ids
*/ */
function trimIdsToThoseImported(ids, moduleGraph, dependency) { function trimIdsToThoseImported(ids, moduleGraph, dependency) {
/** @type {string[]} */
let trimmedIds = []; let trimmedIds = [];
const exportsInfo = moduleGraph.getExportsInfo( let currentExportsInfo = moduleGraph.getExportsInfo(
moduleGraph.getModule(dependency) /** @type {Module} */ (moduleGraph.getModule(dependency))
); );
let currentExportsInfo = /** @type {ExportsInfo=} */ exportsInfo;
for (let i = 0; i < ids.length; i++) { for (let i = 0; i < ids.length; i++) {
if (i === 0 && ids[i] === "default") { if (i === 0 && ids[i] === "default") {
continue; // ExportInfo for the next level under default is still at the root ExportsInfo, so don't advance currentExportsInfo continue; // ExportInfo for the next level under default is still at the root ExportsInfo, so don't advance currentExportsInfo

173
types.d.ts vendored
View File

@ -1857,7 +1857,7 @@ declare class Compilation {
compilationDependencies: { add: (item?: any) => LazySet<string> }; compilationDependencies: { add: (item?: any) => LazySet<string> };
getStats(): Stats; getStats(): Stats;
createStatsOptions( createStatsOptions(
optionsOrPreset: string | StatsOptions, optionsOrPreset?: string | StatsOptions,
context?: CreateStatsOptionsContext context?: CreateStatsOptionsContext
): NormalizedStatsOptions; ): NormalizedStatsOptions;
createStatsFactory(options?: any): StatsFactory; createStatsFactory(options?: any): StatsFactory;
@ -5237,14 +5237,14 @@ declare interface InfrastructureLogging {
*/ */
stream?: NodeJS.WritableStream; stream?: NodeJS.WritableStream;
} }
declare abstract class InitFragment<Context> { declare abstract class InitFragment<GenerateContext> {
content: string | Source; content: string | Source;
stage: number; stage: number;
position: number; position: number;
key?: string; key?: string;
endContent?: string | Source; endContent?: string | Source;
getContent(context: Context): string | Source; getContent(context: GenerateContext): string | Source;
getEndContent(context: Context): undefined | string | Source; getEndContent(context: GenerateContext): undefined | string | Source;
serialize(context: ObjectSerializerContext): void; serialize(context: ObjectSerializerContext): void;
deserialize(context: ObjectDeserializerContext): void; deserialize(context: ObjectDeserializerContext): void;
merge: any; merge: any;
@ -5680,63 +5680,9 @@ declare class JavascriptParser extends Parser {
sourceType: "module" | "auto" | "script"; sourceType: "module" | "auto" | "script";
scope: ScopeInfo; scope: ScopeInfo;
state: ParserState; state: ParserState;
comments: any; comments?: Comment[];
semicolons: any; semicolons?: Set<number>;
statementPath: ( statementPath: StatementPathItem[];
| 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
| ExpressionStatement
| BlockStatement
| StaticBlock
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration
)[];
prevStatement?: prevStatement?:
| UnaryExpression | UnaryExpression
| ArrayExpression | ArrayExpression
@ -5791,7 +5737,7 @@ declare class JavascriptParser extends Parser {
| ExportNamedDeclaration | ExportNamedDeclaration
| ExportDefaultDeclaration | ExportDefaultDeclaration
| ExportAllDeclaration; | ExportAllDeclaration;
destructuringAssignmentProperties: WeakMap<Expression, Set<string>>; destructuringAssignmentProperties?: WeakMap<Expression, Set<string>>;
currentTagData: any; currentTagData: any;
destructuringAssignmentPropertiesFor( destructuringAssignmentPropertiesFor(
node: Expression node: Expression
@ -6031,7 +5977,7 @@ declare class JavascriptParser extends Parser {
blockPreWalkExpressionStatement(statement: ExpressionStatement): void; blockPreWalkExpressionStatement(statement: ExpressionStatement): void;
preWalkAssignmentExpression(expression: AssignmentExpression): void; preWalkAssignmentExpression(expression: AssignmentExpression): void;
blockPreWalkImportDeclaration(statement?: any): void; blockPreWalkImportDeclaration(statement?: any): void;
enterDeclaration(declaration?: any, onIdent?: any): void; enterDeclaration(declaration: Declaration, onIdent?: any): void;
blockPreWalkExportNamedDeclaration(statement?: any): void; blockPreWalkExportNamedDeclaration(statement?: any): void;
walkExportNamedDeclaration(statement: ExportNamedDeclaration): void; walkExportNamedDeclaration(statement: ExportNamedDeclaration): void;
blockPreWalkExportDefaultDeclaration(statement?: any): void; blockPreWalkExportDefaultDeclaration(statement?: any): void;
@ -6113,16 +6059,20 @@ declare class JavascriptParser extends Parser {
walkCallExpression(expression?: any): void; walkCallExpression(expression?: any): void;
walkMemberExpression(expression: MemberExpression): void; walkMemberExpression(expression: MemberExpression): void;
walkMemberExpressionWithExpressionName( walkMemberExpressionWithExpressionName(
expression?: any, expression: any,
name?: any, name: string,
rootInfo?: any, rootInfo: string | VariableInfo,
members?: any, members: string[],
onUnhandled?: any onUnhandled?: any
): void; ): void;
walkThisExpression(expression: ThisExpression): void; walkThisExpression(expression: ThisExpression): void;
walkIdentifier(expression: Identifier): void; walkIdentifier(expression: Identifier): void;
walkMetaProperty(metaProperty: MetaProperty): void; walkMetaProperty(metaProperty: MetaProperty): void;
callHooksForExpression(hookMap: any, expr: any, ...args: any[]): any; callHooksForExpression<T, R>(
hookMap: HookMap<SyncBailHook<T, R>>,
expr: any,
...args: AsArray<T>
): undefined | R;
callHooksForExpressionWithFallback<T, R>( callHooksForExpressionWithFallback<T, R>(
hookMap: HookMap<SyncBailHook<T, R>>, hookMap: HookMap<SyncBailHook<T, R>>,
expr: MemberExpression, expr: MemberExpression,
@ -6195,8 +6145,29 @@ declare class JavascriptParser extends Parser {
| Directive | Directive
)[] )[]
): void; ): void;
enterPatterns(patterns?: any, onIdent?: any): void; enterPatterns(
enterPattern(pattern?: any, onIdent?: any): void; patterns: (
| Identifier
| MemberExpression
| ObjectPattern
| ArrayPattern
| RestElement
| AssignmentPattern
| Property
)[],
onIdent?: any
): void;
enterPattern(
pattern:
| Identifier
| MemberExpression
| ObjectPattern
| ArrayPattern
| RestElement
| AssignmentPattern
| Property,
onIdent?: any
): void;
enterIdentifier(pattern: Identifier, onIdent?: any): void; enterIdentifier(pattern: Identifier, onIdent?: any): void;
enterObjectPattern(pattern: ObjectPattern, onIdent?: any): void; enterObjectPattern(pattern: ObjectPattern, onIdent?: any): void;
enterArrayPattern(pattern: ArrayPattern, onIdent?: any): void; enterArrayPattern(pattern: ArrayPattern, onIdent?: any): void;
@ -6243,12 +6214,12 @@ declare class JavascriptParser extends Parser {
| PrivateIdentifier, | PrivateIdentifier,
commentsStartPos: number commentsStartPos: number
): boolean; ): boolean;
getComments(range: [number, number]): any[]; getComments(range: [number, number]): Comment[];
isAsiPosition(pos: number): boolean; isAsiPosition(pos: number): boolean;
unsetAsiPosition(pos: number): void; unsetAsiPosition(pos: number): void;
isStatementLevelExpression(expr: Expression): boolean; isStatementLevelExpression(expr: Expression): boolean;
getTagData(name?: any, tag?: any): any; getTagData(name: string, tag?: any): any;
tagVariable(name?: any, tag?: any, data?: any): void; tagVariable(name: string, tag?: any, data?: any): void;
defineVariable(name: string): void; defineVariable(name: string): void;
undefineVariable(name: string): void; undefineVariable(name: string): void;
isVariableDefined(name: string): boolean; isVariableDefined(name: string): boolean;
@ -12323,6 +12294,60 @@ type Statement =
| ForStatement | ForStatement
| ForInStatement | ForInStatement
| ForOfStatement; | ForOfStatement;
type StatementPathItem =
| 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
| ExpressionStatement
| BlockStatement
| StaticBlock
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration;
declare class Stats { declare class Stats {
constructor(compilation: Compilation); constructor(compilation: Compilation);
compilation: Compilation; compilation: Compilation;
@ -12332,7 +12357,7 @@ declare class Stats {
hasWarnings(): boolean; hasWarnings(): boolean;
hasErrors(): boolean; hasErrors(): boolean;
toJson(options?: string | StatsOptions): StatsCompilation; toJson(options?: string | StatsOptions): StatsCompilation;
toString(options?: any): string; toString(options?: string | StatsOptions): string;
} }
type StatsAsset = KnownStatsAsset & Record<string, any>; type StatsAsset = KnownStatsAsset & Record<string, any>;
type StatsChunk = KnownStatsChunk & Record<string, any>; type StatsChunk = KnownStatsChunk & Record<string, any>;