fix: types

This commit is contained in:
Alexander Akait 2025-09-11 03:10:10 +03:00 committed by GitHub
parent 6b70c4ac52
commit 16c6966b14
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
109 changed files with 814 additions and 685 deletions

8
declarations.d.ts vendored
View File

@ -370,6 +370,12 @@ declare module "watchpack" {
} }
declare module "eslint-scope/lib/referencer" { declare module "eslint-scope/lib/referencer" {
class Referencer {} type Property = import("estree").Property;
type PropertyDefinition = import("estree").PropertyDefinition;
class Referencer {
Property(node: PropertyDefinition | Property): void;
PropertyDefinition(node: PropertyDefinition): void;
}
export = Referencer; export = Referencer;
} }

View File

@ -82,10 +82,7 @@ export type EntryFilename = FilenameTemplate;
*/ */
export type FilenameTemplate = export type FilenameTemplate =
| string | string
| (( | import("../lib/TemplatedPathPlugin").TemplatePathFn;
pathData: import("../lib/Compilation").PathData,
assetInfo?: import("../lib/Compilation").AssetInfo
) => string);
/** /**
* Specifies the layer in which modules of this entrypoint are placed. * Specifies the layer in which modules of this entrypoint are placed.
*/ */
@ -144,10 +141,7 @@ export type PublicPath = "auto" | RawPublicPath;
*/ */
export type RawPublicPath = export type RawPublicPath =
| string | string
| (( | import("../lib/TemplatedPathPlugin").TemplatePathFn;
pathData: import("../lib/Compilation").PathData,
assetInfo?: import("../lib/Compilation").AssetInfo
) => string);
/** /**
* The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime. * The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.
*/ */
@ -466,10 +460,7 @@ export type OptimizationSplitChunksSizes =
*/ */
export type AssetModuleFilename = export type AssetModuleFilename =
| string | string
| (( | import("../lib/TemplatedPathPlugin").TemplatePathFn;
pathData: import("../lib/Compilation").PathData,
assetInfo?: import("../lib/Compilation").AssetInfo
) => string);
/** /**
* Add charset attribute for script tag. * Add charset attribute for script tag.
*/ */
@ -729,10 +720,7 @@ export type WarningFilterTypes =
export type WarningFilterItemTypes = export type WarningFilterItemTypes =
| RegExp | RegExp
| string | string
| (( | import("../lib/stats/DefaultStatsPresetPlugin").WarningFilterFn;
warning: import("../lib/stats/DefaultStatsFactoryPlugin").StatsError,
value: string
) => boolean);
/** /**
* Environment to build for. An array of environments to build for all of them when possible. * Environment to build for. An array of environments to build for all of them when possible.
*/ */
@ -764,10 +752,7 @@ export type AssetGeneratorOptions = AssetInlineGeneratorOptions &
*/ */
export type AssetModuleOutputPath = export type AssetModuleOutputPath =
| string | string
| (( | import("../lib/TemplatedPathPlugin").TemplatePathFn;
pathData: import("../lib/Compilation").PathData,
assetInfo?: import("../lib/Compilation").AssetInfo
) => string);
/** /**
* Function that executes for module and should return whenever asset should be inlined as DataUrl. * Function that executes for module and should return whenever asset should be inlined as DataUrl.
*/ */
@ -1901,7 +1886,7 @@ export interface OptimizationSplitChunksOptions {
chunks?: chunks?:
| ("initial" | "async" | "all") | ("initial" | "async" | "all")
| RegExp | RegExp
| ((chunk: import("../lib/Chunk")) => boolean); | import("../lib/optimize/SplitChunksPlugin").ChunkFilterFn;
/** /**
* Sets the size types which are used when a number is used for sizes. * Sets the size types which are used when a number is used for sizes.
*/ */
@ -1924,7 +1909,7 @@ export interface OptimizationSplitChunksOptions {
chunks?: chunks?:
| ("initial" | "async" | "all") | ("initial" | "async" | "all")
| RegExp | RegExp
| ((chunk: import("../lib/Chunk")) => boolean); | import("../lib/optimize/SplitChunksPlugin").ChunkFilterFn;
/** /**
* Maximal size hint for the on-demand chunks. * Maximal size hint for the on-demand chunks.
*/ */
@ -1949,12 +1934,7 @@ export interface OptimizationSplitChunksOptions {
/** /**
* Sets the template for the filename for created chunks. * Sets the template for the filename for created chunks.
*/ */
filename?: filename?: string | import("../lib/TemplatedPathPlugin").TemplatePathFn;
| string
| ((
pathData: import("../lib/Compilation").PathData,
assetInfo?: import("../lib/Compilation").AssetInfo
) => string);
/** /**
* Prevents exposing path info when creating names for parts splitted by maxSize. * Prevents exposing path info when creating names for parts splitted by maxSize.
*/ */
@ -1998,14 +1978,7 @@ export interface OptimizationSplitChunksOptions {
/** /**
* Give chunks created a name (chunks with equal name are merged). * Give chunks created a name (chunks with equal name are merged).
*/ */
name?: name?: false | string | import("../lib/optimize/SplitChunksPlugin").GetNameFn;
| false
| string
| ((
module: import("../lib/Module"),
chunks: import("../lib/Chunk")[],
key: string
) => string | undefined);
/** /**
* Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal. * Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.
*/ */
@ -2025,7 +1998,7 @@ export interface OptimizationSplitChunksCacheGroup {
chunks?: chunks?:
| ("initial" | "async" | "all") | ("initial" | "async" | "all")
| RegExp | RegExp
| ((chunk: import("../lib/Chunk")) => boolean); | import("../lib/optimize/SplitChunksPlugin").ChunkFilterFn;
/** /**
* Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group. * Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group.
*/ */
@ -2037,12 +2010,7 @@ export interface OptimizationSplitChunksCacheGroup {
/** /**
* Sets the template for the filename for created chunks. * Sets the template for the filename for created chunks.
*/ */
filename?: filename?: string | import("../lib/TemplatedPathPlugin").TemplatePathFn;
| string
| ((
pathData: import("../lib/Compilation").PathData,
assetInfo?: import("../lib/Compilation").AssetInfo
) => string);
/** /**
* Sets the hint for chunk id. * Sets the hint for chunk id.
*/ */
@ -2090,14 +2058,7 @@ export interface OptimizationSplitChunksCacheGroup {
/** /**
* Give chunks for this cache group a name (chunks with equal name are merged). * Give chunks for this cache group a name (chunks with equal name are merged).
*/ */
name?: name?: false | string | import("../lib/optimize/SplitChunksPlugin").GetNameFn;
| false
| string
| ((
module: import("../lib/Module"),
chunks: import("../lib/Chunk")[],
key: string
) => string | undefined);
/** /**
* Priority of this cache group. * Priority of this cache group.
*/ */
@ -2361,7 +2322,7 @@ export interface CleanOptions {
/** /**
* Keep these assets. * Keep these assets.
*/ */
keep?: RegExp | string | ((filename: string) => boolean); keep?: RegExp | string | import("../lib/CleanPlugin").KeepFn;
} }
/** /**
* The abilities of the environment where the webpack generated code should run. * The abilities of the environment where the webpack generated code should run.
@ -3465,9 +3426,7 @@ export interface JsonParserOptions {
/** /**
* Function to parser content and return JSON. * Function to parser content and return JSON.
*/ */
parse?: ( parse?: import("../lib/json/JsonParser").ParseFn;
input: string
) => Buffer | import("../lib/json/JsonParser").JsonValue;
} }
/** /**
* Options for the default backend. * Options for the default backend.
@ -3496,7 +3455,7 @@ export interface LazyCompilationDefaultBackendOptions {
| import("../lib/hmr/lazyCompilationBackend").HttpsServerOptions | import("../lib/hmr/lazyCompilationBackend").HttpsServerOptions
| import("../lib/hmr/lazyCompilationBackend").HttpServerOptions | import("../lib/hmr/lazyCompilationBackend").HttpServerOptions
) )
| (() => import("../lib/hmr/lazyCompilationBackend").Server); | import("../lib/hmr/lazyCompilationBackend").CreateServerFunction;
} }
/** /**
* Options for compiling entrypoints and import()s only when they are accessed. * Options for compiling entrypoints and import()s only when they are accessed.
@ -3506,18 +3465,7 @@ export interface LazyCompilationOptions {
* Specifies the backend that should be used for handling client keep alive. * Specifies the backend that should be used for handling client keep alive.
*/ */
backend?: backend?:
| ( | import("../lib/hmr/LazyCompilationPlugin").BackEnd
| ((
compiler: import("../lib/Compiler"),
callback: (
err: Error | null,
api?: import("../lib/hmr/LazyCompilationPlugin").BackendApi
) => void
) => void)
| ((
compiler: import("../lib/Compiler")
) => Promise<import("../lib/hmr/LazyCompilationPlugin").BackendApi>)
)
| LazyCompilationDefaultBackendOptions; | LazyCompilationDefaultBackendOptions;
/** /**
* Enable/disable lazy compilation for entries. * Enable/disable lazy compilation for entries.
@ -3530,7 +3478,7 @@ export interface LazyCompilationOptions {
/** /**
* Specify which entrypoints or import()ed modules should be lazily compiled. This is matched with the imported module and not the entrypoint name. * Specify which entrypoints or import()ed modules should be lazily compiled. This is matched with the imported module and not the entrypoint name.
*/ */
test?: RegExp | string | ((module: import("../lib/Module")) => boolean); test?: RegExp | string | import("../lib/hmr/LazyCompilationPlugin").TestFn;
} }
/** /**
* Options affecting the normal modules (`NormalModuleFactory`). * Options affecting the normal modules (`NormalModuleFactory`).

View File

@ -19,5 +19,5 @@ export type IgnorePluginOptions =
/** /**
* A filter function for resource and context. * A filter function for resource and context.
*/ */
checkResource: (resource: string, context: string) => boolean; checkResource: import("../../lib/IgnorePlugin").CheckResourceFn;
}; };

View File

@ -8,11 +8,7 @@ export type ProgressPluginArgument = ProgressPluginOptions | HandlerFunction;
/** /**
* Function that executes for every progress step. * Function that executes for every progress step.
*/ */
export type HandlerFunction = ( export type HandlerFunction = import("../../lib/ProgressPlugin").HandlerFn;
percentage: number,
msg: string,
...args: string[]
) => void;
/** /**
* Options object for the ProgressPlugin. * Options object for the ProgressPlugin.

View File

@ -20,10 +20,7 @@ export interface SourceMapDevToolPluginOptions {
append?: append?:
| (false | null) | (false | null)
| string | string
| (( | import("../../lib/TemplatedPathPlugin").TemplatePathFn;
pathData: import("../../lib/Compilation").PathData,
assetInfo?: import("../../lib/Compilation").AssetInfo
) => string);
/** /**
* Indicates whether column mappings should be used (defaults to true). * Indicates whether column mappings should be used (defaults to true).
*/ */

View File

@ -10,9 +10,7 @@ export type VirtualUrlPluginOptions = VirtualUrlOptions;
*/ */
export type VirtualModuleContent = export type VirtualModuleContent =
| string | string
| (( | import("../../../lib/schemes/VirtualUrlPlugin").SourceFn
loaderContext: import("webpack").LoaderContext<EXPECTED_ANY>
) => Promise<string> | string)
| VirtualModule; | VirtualModule;
/** /**
@ -37,9 +35,7 @@ export interface VirtualModule {
/** /**
* The source function that provides the virtual content. * The source function that provides the virtual content.
*/ */
source: ( source: import("../../../lib/schemes/VirtualUrlPlugin").SourceFn;
loaderContext: import("webpack").LoaderContext<EXPECTED_ANY>
) => Promise<string> | string;
/** /**
* The module type. * The module type.
*/ */
@ -47,5 +43,8 @@ export interface VirtualModule {
/** /**
* Optional version function or value for cache invalidation. * Optional version function or value for cache invalidation.
*/ */
version?: true | string | (() => string | undefined); version?:
| true
| string
| import("../../../lib/schemes/VirtualUrlPlugin").VersionFn;
} }

View File

@ -38,7 +38,7 @@ class AsyncDependenciesBlock extends DependenciesBlock {
} }
/** /**
* @returns {string | null | undefined} The name of the chunk * @returns {ChunkGroupOptions["name"]} The name of the chunk
*/ */
get chunkName() { get chunkName() {
return this.groupOptions.name; return this.groupOptions.name;

View File

@ -31,36 +31,41 @@ const { mergeRuntime } = require("./util/runtime");
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string | null} ChunkName */ /** @typedef {string | null} ChunkName */
/** @typedef {number | string} ChunkId */ /** @typedef {string | number} ChunkId */
/** @typedef {SortableSet<string>} IdNameHints */ /** @typedef {SortableSet<string>} IdNameHints */
const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files"); const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files");
/** /**
* @typedef {object} WithId an object who has an id property * * @deprecated
* @property {string | number} id the id of the object * @typedef {object} ChunkMaps
* @property {Record<ChunkId, string>} hash
* @property {Record<ChunkId, Record<string, string>>} contentHash
* @property {Record<ChunkId, string>} name
*/ */
/** /**
* @deprecated * @deprecated
* @typedef {object} ChunkMaps * @typedef {Record<ChunkId, ChunkId[]>} ChunkModuleIdMap
* @property {Record<string | number, string>} hash */
* @property {Record<string | number, Record<string, string>>} contentHash
* @property {Record<string | number, string>} name /**
* @deprecated
* @typedef {Record<ModuleId, string>} chunkModuleHashMap
*/ */
/** /**
* @deprecated * @deprecated
* @typedef {object} ChunkModuleMaps * @typedef {object} ChunkModuleMaps
* @property {Record<string|number, (string|number)[]>} id * @property {ChunkModuleIdMap} id
* @property {Record<string|number, string>} hash * @property {chunkModuleHashMap} hash
*/ */
/** @typedef {Set<Chunk>} Chunks */ /** @typedef {Set<Chunk>} Chunks */
/** @typedef {Set<Entrypoint>} Entrypoints */ /** @typedef {Set<Entrypoint>} Entrypoints */
/** @typedef {Set<ChunkGroup>} Queue */ /** @typedef {Set<ChunkGroup>} Queue */
/** @typedef {SortableSet<ChunkGroup>} SortableChunkGroups */ /** @typedef {SortableSet<ChunkGroup>} SortableChunkGroups */
/** @typedef {Record<string, (string | number)[]>} ChunkChildIdsByOrdersMap */ /** @typedef {Record<string, ChunkId[]>} ChunkChildIdsByOrdersMap */
/** @typedef {Record<string, ChunkChildIdsByOrdersMap>} ChunkChildIdsByOrdersMapByData */ /** @typedef {Record<string, ChunkChildIdsByOrdersMap>} ChunkChildIdsByOrdersMapByData */
let debugId = 1000; let debugId = 1000;
@ -356,9 +361,9 @@ class Chunk {
"Chunk.getChunkModuleMaps", "Chunk.getChunkModuleMaps",
"DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS" "DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS"
); );
/** @type {Record<string|number, (string|number)[]>} */ /** @type {ChunkModuleIdMap} */
const chunkModuleIdMap = Object.create(null); const chunkModuleIdMap = Object.create(null);
/** @type {Record<string|number, string>} */ /** @type {chunkModuleHashMap} */
const chunkModuleHashMap = Object.create(null); const chunkModuleHashMap = Object.create(null);
for (const asyncChunk of this.getAllAsyncChunks()) { for (const asyncChunk of this.getAllAsyncChunks()) {
@ -743,7 +748,7 @@ class Chunk {
} }
} }
} }
/** @type {Record<string, (string | number)[]>} */ /** @type {Record<string, ChunkId[]>} */
const result = Object.create(null); const result = Object.create(null);
for (const [name, list] of lists) { for (const [name, list] of lists) {
list.sort((a, b) => { list.sort((a, b) => {

View File

@ -113,13 +113,12 @@ class ChunkGroup {
* @returns {void} * @returns {void}
*/ */
addOptions(options) { addOptions(options) {
for (const _key of Object.keys(options)) { for (const key of /** @type {(keyof ChunkGroupOptions)[]} */ (
const key = Object.keys(options)
/** @type {keyof ChunkGroupOptions} */ )) {
(_key);
if (this.options[key] === undefined) { if (this.options[key] === undefined) {
/** @type {EXPECTED_ANY} */ /** @type {ChunkGroupOptions[keyof ChunkGroupOptions]} */
(this.options)[key] = options[key]; (this.options[key]) = options[key];
} else if (this.options[key] !== options[key]) { } else if (this.options[key] !== options[key]) {
if (key.endsWith("Order")) { if (key.endsWith("Order")) {
const orderKey = const orderKey =
@ -143,7 +142,7 @@ class ChunkGroup {
/** /**
* returns the name of current ChunkGroup * returns the name of current ChunkGroup
* @returns {string | null | undefined} returns the ChunkGroup name * @returns {ChunkGroupOptions["name"]} returns the ChunkGroup name
*/ */
get name() { get name() {
return this.options.name; return this.options.name;

View File

@ -30,7 +30,7 @@ const processAsyncTree = require("./util/processAsyncTree");
/** /**
* @callback KeepFn * @callback KeepFn
* @param {string} path path * @param {string} path path
* @returns {boolean | void} true, if the path should be kept * @returns {boolean | undefined} true, if the path should be kept
*/ */
const validate = createSchemaValidation( const validate = createSchemaValidation(
@ -170,7 +170,7 @@ const doStat = (fs, filename, callback) => {
* @param {boolean} dry only log instead of fs modification * @param {boolean} dry only log instead of fs modification
* @param {Logger} logger logger * @param {Logger} logger logger
* @param {Diff} diff filenames of the assets that shouldn't be there * @param {Diff} diff filenames of the assets that shouldn't be there
* @param {(path: string) => boolean | void} isKept check if the entry is ignored * @param {KeepFn} isKept check if the entry is ignored
* @param {(err?: Error, assets?: Assets) => void} callback callback * @param {(err?: Error, assets?: Assets) => void} callback callback
* @returns {void} * @returns {void}
*/ */
@ -436,7 +436,7 @@ class CleanPlugin {
/** /**
* @param {string} path path * @param {string} path path
* @returns {boolean | void} true, if needs to be kept * @returns {boolean | undefined} true, if needs to be kept
*/ */
const isKept = (path) => { const isKept = (path) => {
const result = hooks.keep.call(path); const result = hooks.keep.call(path);

View File

@ -108,8 +108,9 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {import("./Compiler").Records} Records */ /** @typedef {import("./Compiler").Records} Records */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module").NameForCondition} NameForCondition */
/** @typedef {import("./Module").BuildInfo} BuildInfo */ /** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */ /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
@ -753,7 +754,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
/** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */
succeedEntry: new SyncHook(["entry", "options", "module"]), succeedEntry: new SyncHook(["entry", "options", "module"]),
/** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ /** @type {SyncWaterfallHook<[ReferencedExports, Dependency, RuntimeSpec]>} */
dependencyReferencedExports: new SyncWaterfallHook([ dependencyReferencedExports: new SyncWaterfallHook([
"referencedExports", "referencedExports",
"dependency", "dependency",
@ -1195,7 +1196,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
); );
/** @type {Record<string, number>} */ /** @type {Record<string, number>} */
this.childrenCounters = {}; this.childrenCounters = {};
/** @type {Set<number | string> | null} */ /** @type {Set<number> | null} */
this.usedChunkIds = null; this.usedChunkIds = null;
/** @type {Set<number> | null} */ /** @type {Set<number> | null} */
this.usedModuleIds = null; this.usedModuleIds = null;
@ -1984,7 +1985,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
{ {
contextInfo: { contextInfo: {
issuer: originModule issuer: originModule
? /** @type {string} */ (originModule.nameForCondition()) ? /** @type {NameForCondition} */ (originModule.nameForCondition())
: "", : "",
issuerLayer: originModule ? originModule.layer : null, issuerLayer: originModule ? originModule.layer : null,
compiler: this.compiler.name, compiler: this.compiler.name,
@ -4144,7 +4145,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
/** /**
* @param {Dependency} dependency the dependency * @param {Dependency} dependency the dependency
* @param {RuntimeSpec} runtime the runtime * @param {RuntimeSpec} runtime the runtime
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getDependencyReferencedExports(dependency, runtime) { getDependencyReferencedExports(dependency, runtime) {
const referencedExports = dependency.getReferencedExports( const referencedExports = dependency.getReferencedExports(

View File

@ -117,7 +117,8 @@ const webpack = require(".");
/** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, memCache: MemCache }} ModuleMemCachesItem */ /** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, memCache: MemCache }} ModuleMemCachesItem */
/** /**
* @param {string[]} array an array * @template T
* @param {T[]} array an array
* @returns {boolean} true, if the array is sorted * @returns {boolean} true, if the array is sorted
*/ */
const isSorted = (array) => { const isSorted = (array) => {

View File

@ -14,13 +14,14 @@ const {
/** @typedef {import("./Module")} Module */ /** @typedef {import("./Module")} Module */
/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */ /** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */ /** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ExportName} Ids */
const MODULE_REFERENCE_REGEXP = const MODULE_REFERENCE_REGEXP =
/^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_deferredImport)?(?:_asiSafe(\d))?__$/; /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_deferredImport)?(?:_asiSafe(\d))?__$/;
/** /**
* @typedef {object} ModuleReferenceOptions * @typedef {object} ModuleReferenceOptions
* @property {string[]} ids the properties/exports of the module * @property {Ids} ids the properties/exports of the module
* @property {boolean} call true, when this referenced export is called * @property {boolean} call true, when this referenced export is called
* @property {boolean} directImport true, when this referenced export is directly imported (not via property access) * @property {boolean} directImport true, when this referenced export is directly imported (not via property access)
* @property {boolean} deferredImport true, when this referenced export is deferred * @property {boolean} deferredImport true, when this referenced export is deferred

View File

@ -33,11 +33,13 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */ /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */ /** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./Chunk").ChunkName} ChunkName */
/** @typedef {import("./ChunkGraph")} ChunkGraph */ /** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ /** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
/** @typedef {import("./Compilation")} Compilation */ /** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */ /** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildCallback} BuildCallback */ /** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").BuildInfo} BuildInfo */ /** @typedef {import("./Module").BuildInfo} BuildInfo */
@ -46,6 +48,7 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./RequestShortener")} RequestShortener */
@ -66,13 +69,13 @@ const makeSerializable = require("./util/makeSerializable");
* @property {RegExp | false | null} regExp * @property {RegExp | false | null} regExp
* @property {"strict" | boolean=} namespaceObject * @property {"strict" | boolean=} namespaceObject
* @property {string=} addon * @property {string=} addon
* @property {string | null=} chunkName * @property {ChunkName=} chunkName
* @property {RegExp | null=} include * @property {RegExp | null=} include
* @property {RegExp | null=} exclude * @property {RegExp | null=} exclude
* @property {RawChunkGroupOptions=} groupOptions * @property {RawChunkGroupOptions=} groupOptions
* @property {string=} typePrefix * @property {string=} typePrefix
* @property {string=} category * @property {string=} category
* @property {string[][] | null=} referencedExports exports referenced from modules (won't be mangled) * @property {RawReferencedExports | null=} referencedExports exports referenced from modules (won't be mangled)
* @property {string | null=} layer * @property {string | null=} layer
* @property {ImportAttributes=} attributes * @property {ImportAttributes=} attributes
*/ */
@ -331,7 +334,7 @@ class ContextModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
let identifier; let identifier;

View File

@ -20,17 +20,20 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */ /** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */ /** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */
/** @typedef {import("./Module").ModuleId} ModuleId */
/** @typedef {import("./Module").BuildCallback} BuildCallback */ /** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").BuildMeta} BuildMeta */ /** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./dependencies/StaticExportsDependency").Exports} Exports */
/** @typedef {import("./util/Hash")} Hash */ /** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
@ -41,8 +44,8 @@ const makeSerializable = require("./util/makeSerializable");
/** /**
* @typedef {object} DelegatedModuleData * @typedef {object} DelegatedModuleData
* @property {BuildMeta=} buildMeta build meta * @property {BuildMeta=} buildMeta build meta
* @property {true | string[]=} exports exports * @property {Exports=} exports exports
* @property {number | string} id module id * @property {ModuleId} id module id
*/ */
const RUNTIME_REQUIREMENTS = new Set([ const RUNTIME_REQUIREMENTS = new Set([
@ -82,7 +85,7 @@ class DelegatedModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return typeof this.originalRequest === "string" return typeof this.originalRequest === "string"

View File

@ -80,6 +80,9 @@ const memoize = require("./util/memoize");
* @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true
*/ */
/** @typedef {string[][]} RawReferencedExports */
/** @typedef {(string[] | ReferencedExport)[]} ReferencedExports */
/** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */ /** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */
const TRANSITIVE = Symbol("transitive"); const TRANSITIVE = Symbol("transitive");
@ -227,7 +230,7 @@ class Dependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return Dependency.EXPORTS_OBJECT_REFERENCED; return Dependency.EXPORTS_OBJECT_REFERENCED;
@ -329,9 +332,9 @@ class Dependency {
} }
} }
/** @type {string[][]} */ /** @type {RawReferencedExports} */
Dependency.NO_EXPORTS_REFERENCED = []; Dependency.NO_EXPORTS_REFERENCED = [];
/** @type {string[][]} */ /** @type {RawReferencedExports} */
Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
// TODO remove in webpack 6 // TODO remove in webpack 6

View File

@ -24,15 +24,16 @@ const { forEachRuntime } = require("./util/runtime");
/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ /** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */
/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ /** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */
/** @typedef {string} ExportInfoName */
/** @typedef {Map<string, RuntimeUsageStateType>} UsedInRuntime */ /** @typedef {Map<string, RuntimeUsageStateType>} UsedInRuntime */
/** @typedef {{ module: Module, export: string[], deferred: boolean }} TargetItemWithoutConnection */ /** @typedef {{ module: Module, export: ExportInfoName[], deferred: boolean }} TargetItemWithoutConnection */
/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} TargetItemWithConnection */ /** @typedef {{ module: Module, connection: ModuleGraphConnection, export: ExportInfoName[] | undefined }} TargetItemWithConnection */
/** @typedef {(target: TargetItemWithConnection) => boolean} ResolveTargetFilter */ /** @typedef {(target: TargetItemWithConnection) => boolean} ResolveTargetFilter */
/** @typedef {(module: Module) => boolean} ValidTargetModuleFilter */ /** @typedef {(module: Module) => boolean} ValidTargetModuleFilter */
/** @typedef {{ connection: ModuleGraphConnection, export: string[], priority: number }} TargetItem */ /** @typedef {{ connection: ModuleGraphConnection, export: ExportInfoName[], priority: number }} TargetItem */
/** @typedef {Map<Dependency | undefined, TargetItem>} Target */ /** @typedef {Map<Dependency | undefined, TargetItem>} Target */
/** @typedef {string} ExportInfoName */
/** @typedef {string | null} ExportInfoUsedName */ /** @typedef {string | null} ExportInfoUsedName */
/** @typedef {boolean | null} ExportInfoProvided */ /** @typedef {boolean | null} ExportInfoProvided */
@ -186,7 +187,7 @@ class ExportsInfo {
*/ */
_sortExportsMap(exports) { _sortExportsMap(exports) {
if (exports.size > 1) { if (exports.size > 1) {
/** @type {string[]} */ /** @type {ExportInfoName[]} */
const namesInOrder = []; const namesInOrder = [];
for (const entry of exports.values()) { for (const entry of exports.values()) {
namesInOrder.push(entry.name); namesInOrder.push(entry.name);
@ -520,7 +521,7 @@ class ExportsInfo {
/** /**
* @param {RuntimeSpec} runtime the runtime * @param {RuntimeSpec} runtime the runtime
* @returns {SortableSet<string> | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) * @returns {SortableSet<ExportInfoName> | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown)
*/ */
getUsedExports(runtime) { getUsedExports(runtime) {
switch (this._otherExportsInfo.getUsed(runtime)) { switch (this._otherExportsInfo.getUsed(runtime)) {
@ -532,6 +533,7 @@ class ExportsInfo {
return true; return true;
} }
/** @type {ExportInfoName[]} */
const array = []; const array = [];
if (!this._exportsAreOrdered) this._sortExports(); if (!this._exportsAreOrdered) this._sortExports();
for (const exportInfo of this._exports.values()) { for (const exportInfo of this._exports.values()) {
@ -563,11 +565,11 @@ class ExportsInfo {
return false; return false;
} }
} }
return /** @type {SortableSet<string>} */ (new SortableSet(array)); return /** @type {SortableSet<ExportInfoName>} */ (new SortableSet(array));
} }
/** /**
* @returns {null | true | string[]} list of exports when known * @returns {null | true | ExportInfoName[]} list of exports when known
*/ */
getProvidedExports() { getProvidedExports() {
switch (this._otherExportsInfo.provided) { switch (this._otherExportsInfo.provided) {
@ -579,7 +581,7 @@ class ExportsInfo {
return true; return true;
} }
/** @type {string[]} */ /** @type {ExportInfoName[]} */
const array = []; const array = [];
if (!this._exportsAreOrdered) this._sortExports(); if (!this._exportsAreOrdered) this._sortExports();
for (const exportInfo of this._exports.values()) { for (const exportInfo of this._exports.values()) {
@ -1055,8 +1057,8 @@ class ExportInfo {
} }
} else { } else {
let changed = false; let changed = false;
forEachRuntime(runtime, (_runtime) => { forEachRuntime(runtime, (runtime_) => {
const runtime = /** @type {string} */ (_runtime); const runtime = /** @type {string} */ (runtime_);
const usedInRuntime = const usedInRuntime =
/** @type {UsedInRuntime} */ /** @type {UsedInRuntime} */
(this._usedInRuntime); (this._usedInRuntime);
@ -1145,7 +1147,7 @@ class ExportInfo {
/** /**
* @param {Dependency} key the key * @param {Dependency} key the key
* @param {ModuleGraphConnection} connection the target module if a single one * @param {ModuleGraphConnection} connection the target module if a single one
* @param {(string[] | null)=} exportName the exported name * @param {ExportInfoName[] | null=} exportName the exported name
* @param {number=} priority priority * @param {number=} priority priority
* @returns {boolean} true, if something has changed * @returns {boolean} true, if something has changed
*/ */
@ -1155,7 +1157,7 @@ class ExportInfo {
this._target = new Map(); this._target = new Map();
this._target.set(key, { this._target.set(key, {
connection, connection,
export: /** @type {string[]} */ (exportName), export: /** @type {ExportInfoName[]} */ (exportName),
priority priority
}); });
return true; return true;
@ -1165,7 +1167,7 @@ class ExportInfo {
if (oldTarget === null && !connection) return false; if (oldTarget === null && !connection) return false;
this._target.set(key, { this._target.set(key, {
connection, connection,
export: /** @type {string[]} */ (exportName), export: /** @type {ExportInfoName[]} */ (exportName),
priority priority
}); });
this._maxTarget = undefined; this._maxTarget = undefined;
@ -1179,7 +1181,7 @@ class ExportInfo {
: oldTarget.export) : oldTarget.export)
) { ) {
oldTarget.connection = connection; oldTarget.connection = connection;
oldTarget.export = /** @type {string[]} */ (exportName); oldTarget.export = /** @type {ExportInfoName[]} */ (exportName);
oldTarget.priority = priority; oldTarget.priority = priority;
this._maxTarget = undefined; this._maxTarget = undefined;
return true; return true;

View File

@ -45,6 +45,7 @@ const { register } = require("./util/serialization");
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ /** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
@ -87,7 +88,7 @@ const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); const EMPTY_RUNTIME_REQUIREMENTS = new Set([]);
/** /**
* @param {string|string[]} variableName the variable name or path * @param {string | string[]} variableName the variable name or path
* @param {string} type the module system * @param {string} type the module system
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
*/ */
@ -107,8 +108,10 @@ const getSourceForGlobalVariableExternal = (variableName, type) => {
}; };
}; };
/** @typedef {string | string[]} ModuleAndSpecifiers */
/** /**
* @param {string|string[]} moduleAndSpecifiers the module request * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
*/ */
const getSourceForCommonJsExternal = (moduleAndSpecifiers) => { const getSourceForCommonJsExternal = (moduleAndSpecifiers) => {
@ -144,7 +147,7 @@ const getExternalModuleNodeCommonjsInitFragment = (runtimeTemplate) => {
}; };
/** /**
* @param {string | string[]} moduleAndSpecifiers the module request * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
*/ */
@ -173,7 +176,7 @@ const getSourceForCommonJsExternalInNodeModule = (
}; };
/** /**
* @param {string|string[]} moduleAndSpecifiers the module request * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {ImportDependencyMeta=} dependencyMeta the dependency meta * @param {ImportDependencyMeta=} dependencyMeta the dependency meta
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
@ -423,7 +426,7 @@ const generateModuleRemapping = (
}; };
/** /**
* @param {string|string[]} moduleAndSpecifiers the module request * @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @param {ExportsInfo} exportsInfo exports info of this module * @param {ExportsInfo} exportsInfo exports info of this module
* @param {RuntimeSpec} runtime the runtime * @param {RuntimeSpec} runtime the runtime
* @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {RuntimeTemplate} runtimeTemplate the runtime template
@ -526,7 +529,7 @@ const getSourceForModuleExternal = (
}; };
/** /**
* @param {string|string[]} urlAndGlobal the script request * @param {string | string[]} urlAndGlobal the script request
* @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
*/ */
@ -576,7 +579,7 @@ const checkExternalVariable = (variableName, request, runtimeTemplate) =>
/** /**
* @param {ModuleId | string} id the module id * @param {ModuleId | string} id the module id
* @param {boolean} optional true, if the module is optional * @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path * @param {string | string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
*/ */
@ -603,7 +606,7 @@ const getSourceForAmdOrUmdExternal = (
/** /**
* @param {boolean} optional true, if the module is optional * @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path * @param {string | string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source * @returns {SourceData} the generated source
*/ */
@ -624,10 +627,11 @@ const getSourceForDefaultCase = (optional, request, runtimeTemplate) => {
}; };
/** @typedef {Record<string, string | string[]>} RequestRecord */ /** @typedef {Record<string, string | string[]>} RequestRecord */
/** @typedef {string | string[] | RequestRecord} ExternalModuleRequest */
class ExternalModule extends Module { class ExternalModule extends Module {
/** /**
* @param {string | string[] | RequestRecord} request request * @param {ExternalModuleRequest} request request
* @param {string} type type * @param {string} type type
* @param {string} userRequest user request * @param {string} userRequest user request
* @param {DependencyMeta=} dependencyMeta dependency meta * @param {DependencyMeta=} dependencyMeta dependency meta
@ -636,7 +640,7 @@ class ExternalModule extends Module {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
// Info from Factory // Info from Factory
/** @type {string | string[] | Record<string, string | string[]>} */ /** @type {ExternalModuleRequest} */
this.request = request; this.request = request;
/** @type {string} */ /** @type {string} */
this.externalType = type; this.externalType = type;
@ -666,7 +670,7 @@ class ExternalModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return this.userRequest; return this.userRequest;

View File

@ -1212,34 +1212,34 @@ class FileSystemInfo {
processor: this._getManagedItemDirectoryInfo.bind(this) processor: this._getManagedItemDirectoryInfo.bind(this)
}); });
const _unmanagedPaths = [...unmanagedPaths]; const _unmanagedPaths = [...unmanagedPaths];
this.unmanagedPathsWithSlash =
/** @type {string[]} */ /** @type {string[]} */
(_unmanagedPaths.filter((p) => typeof p === "string")).map((p) => this.unmanagedPathsWithSlash = _unmanagedPaths
join(fs, p, "_").slice(0, -1) .filter((p) => typeof p === "string")
); .map((p) => join(fs, p, "_").slice(0, -1));
this.unmanagedPathsRegExps =
/** @type {RegExp[]} */ /** @type {RegExp[]} */
(_unmanagedPaths.filter((p) => typeof p !== "string")); this.unmanagedPathsRegExps = _unmanagedPaths.filter(
(p) => typeof p !== "string"
);
this.managedPaths = [...managedPaths]; this.managedPaths = [...managedPaths];
this.managedPathsWithSlash =
/** @type {string[]} */ /** @type {string[]} */
(this.managedPaths.filter((p) => typeof p === "string")).map((p) => this.managedPathsWithSlash = this.managedPaths
join(fs, p, "_").slice(0, -1) .filter((p) => typeof p === "string")
.map((p) => join(fs, p, "_").slice(0, -1));
/** @type {RegExp[]} */
this.managedPathsRegExps = this.managedPaths.filter(
(p) => typeof p !== "string"
); );
this.managedPathsRegExps =
/** @type {RegExp[]} */
(this.managedPaths.filter((p) => typeof p !== "string"));
this.immutablePaths = [...immutablePaths]; this.immutablePaths = [...immutablePaths];
this.immutablePathsWithSlash =
/** @type {string[]} */ /** @type {string[]} */
(this.immutablePaths.filter((p) => typeof p === "string")).map((p) => this.immutablePathsWithSlash = this.immutablePaths
join(fs, p, "_").slice(0, -1) .filter((p) => typeof p === "string")
); .map((p) => join(fs, p, "_").slice(0, -1));
this.immutablePathsRegExps =
/** @type {RegExp[]} */ /** @type {RegExp[]} */
(this.immutablePaths.filter((p) => typeof p !== "string")); this.immutablePathsRegExps = this.immutablePaths.filter(
(p) => typeof p !== "string"
);
this._cachedDeprecatedFileTimestamps = undefined; this._cachedDeprecatedFileTimestamps = undefined;
this._cachedDeprecatedContextTimestamps = undefined; this._cachedDeprecatedContextTimestamps = undefined;

View File

@ -16,6 +16,7 @@ const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
/** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("./ExportsInfo")} ExportsInfo */ /** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Module")} Module */ /** @typedef {import("./Module")} Module */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
@ -59,7 +60,7 @@ class FlagDependencyUsagePlugin {
/** /**
* @param {Module} module module to process * @param {Module} module module to process
* @param {(string[] | ReferencedExport)[]} usedExports list of used exports * @param {ReferencedExports} usedExports list of used exports
* @param {RuntimeSpec} runtime part of which runtime * @param {RuntimeSpec} runtime part of which runtime
* @param {boolean} forceSideEffects always apply side effects * @param {boolean} forceSideEffects always apply side effects
* @returns {void} * @returns {void}
@ -166,7 +167,7 @@ class FlagDependencyUsagePlugin {
* @returns {void} * @returns {void}
*/ */
const processModule = (module, runtime, forceSideEffects) => { const processModule = (module, runtime, forceSideEffects) => {
/** @type {Map<Module, (string[] | ReferencedExport)[] | Map<string, string[] | ReferencedExport>>} */ /** @type {Map<Module, ReferencedExports | Map<string, string[] | ReferencedExport>>} */
const map = new Map(); const map = new Map();
/** @type {ArrayQueue<DependenciesBlock>} */ /** @type {ArrayQueue<DependenciesBlock>} */

View File

@ -59,10 +59,12 @@ const {
/** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */ /** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string[]} Requests */
/** /**
* @typedef {object} HMRJavascriptParserHooks * @typedef {object} HMRJavascriptParserHooks
* @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptCallback * @property {SyncBailHook<[Expression | SpreadElement, Requests], void>} hotAcceptCallback
* @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptWithoutCallback * @property {SyncBailHook<[CallExpression, Requests], void>} hotAcceptWithoutCallback
*/ */
/** @typedef {number} HotIndex */ /** @typedef {number} HotIndex */
@ -147,7 +149,7 @@ class HotModuleReplacementPlugin {
/** @type {BasicEvaluatedExpression[]} */ /** @type {BasicEvaluatedExpression[]} */
(arg.items).filter((param) => param.isString()); (arg.items).filter((param) => param.isString());
} }
/** @type {string[]} */ /** @type {Requests} */
const requests = []; const requests = [];
if (params.length > 0) { if (params.length > 0) {
for (const [idx, param] of params.entries()) { for (const [idx, param] of params.entries()) {
@ -555,7 +557,7 @@ class HotModuleReplacementPlugin {
} }
// List of completely removed modules // List of completely removed modules
/** @type {Set<string | number>} */ /** @type {Set<ModuleId>} */
const completelyRemovedModules = new Set(); const completelyRemovedModules = new Set();
for (const key of Object.keys(records.chunkHashes)) { for (const key of Object.keys(records.chunkHashes)) {

View File

@ -23,6 +23,8 @@ const validate = createSchemaValidation(
} }
); );
/** @typedef {(resource: string, context: string) => boolean} CheckResourceFn */
const PLUGIN_NAME = "IgnorePlugin"; const PLUGIN_NAME = "IgnorePlugin";
class IgnorePlugin { class IgnorePlugin {

View File

@ -15,12 +15,13 @@ const { dirname, mkdirp } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */ /** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./Module").BuildMeta} BuildMeta */ /** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */
/** /**
* @typedef {object} ManifestModuleData * @typedef {object} ManifestModuleData
* @property {string | number} id * @property {ModuleId} id
* @property {BuildMeta=} buildMeta * @property {BuildMeta=} buildMeta
* @property {boolean | string[]=} exports * @property {ExportInfoName[]=} exports
*/ */
/** /**

View File

@ -34,6 +34,7 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */ /** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */ /** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */
/** @typedef {import("./ModuleGraph").OptimizationBailouts} OptimizationBailouts */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
@ -201,6 +202,9 @@ const deprecatedNeedRebuild = util.deprecate(
"DEP_WEBPACK_MODULE_NEED_REBUILD" "DEP_WEBPACK_MODULE_NEED_REBUILD"
); );
/** @typedef {string} LibIdent */
/** @typedef {string} NameForCondition */
/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ /** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */
class Module extends DependenciesBlock { class Module extends DependenciesBlock {
@ -420,7 +424,7 @@ class Module extends DependenciesBlock {
/** /**
* @deprecated * @deprecated
* @returns {(string | OptimizationBailoutFunction)[]} list * @returns {OptimizationBailouts} list
*/ */
get optimizationBailout() { get optimizationBailout() {
return ModuleGraph.getModuleGraphForModule( return ModuleGraph.getModuleGraphForModule(
@ -975,14 +979,14 @@ class Module extends DependenciesBlock {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return null; return null;
} }
/** /**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path) * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
*/ */
nameForCondition() { nameForCondition() {
return null; return null;

View File

@ -17,6 +17,7 @@ const { sortWithSourceOrder } = require("./util/comparators");
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */ /** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("./Module")} Module */ /** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleProfile")} ModuleProfile */ /** @typedef {import("./ModuleProfile")} ModuleProfile */
/** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./RequestShortener")} RequestShortener */
@ -82,6 +83,8 @@ const getConnectionsByModule = (set) =>
/** @typedef {SortableSet<ModuleGraphConnection>} IncomingConnections */ /** @typedef {SortableSet<ModuleGraphConnection>} IncomingConnections */
/** @typedef {SortableSet<ModuleGraphConnection>} OutgoingConnections */ /** @typedef {SortableSet<ModuleGraphConnection>} OutgoingConnections */
/** @typedef {Module | null | undefined} Issuer */
/** @typedef {(string | OptimizationBailoutFunction)[]} OptimizationBailouts */
class ModuleGraphModule { class ModuleGraphModule {
constructor() { constructor() {
@ -89,9 +92,9 @@ class ModuleGraphModule {
this.incomingConnections = new SortableSet(); this.incomingConnections = new SortableSet();
/** @type {OutgoingConnections | undefined} */ /** @type {OutgoingConnections | undefined} */
this.outgoingConnections = undefined; this.outgoingConnections = undefined;
/** @type {Module | null | undefined} */ /** @type {Issuer} */
this.issuer = undefined; this.issuer = undefined;
/** @type {(string | OptimizationBailoutFunction)[]} */ /** @type {OptimizationBailouts} */
this.optimizationBailout = []; this.optimizationBailout = [];
/** @type {ExportsInfo} */ /** @type {ExportsInfo} */
this.exports = new ExportsInfo(); this.exports = new ExportsInfo();
@ -617,7 +620,7 @@ class ModuleGraph {
/** /**
* @param {Module} module the module * @param {Module} module the module
* @returns {Module | null | undefined} the issuer module * @returns {Issuer} the issuer module
*/ */
getIssuer(module) { getIssuer(module) {
const mgm = this._getModuleGraphModule(module); const mgm = this._getModuleGraphModule(module);
@ -646,7 +649,7 @@ class ModuleGraph {
/** /**
* @param {Module} module the module * @param {Module} module the module
* @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts * @returns {OptimizationBailouts} optimization bailouts
*/ */
getOptimizationBailout(module) { getOptimizationBailout(module) {
const mgm = this._getModuleGraphModule(module); const mgm = this._getModuleGraphModule(module);
@ -655,7 +658,7 @@ class ModuleGraph {
/** /**
* @param {Module} module the module * @param {Module} module the module
* @returns {true | string[] | null} the provided exports * @returns {null | true | ExportInfoName[]} the provided exports
*/ */
getProvidedExports(module) { getProvidedExports(module) {
const mgm = this._getModuleGraphModule(module); const mgm = this._getModuleGraphModule(module);
@ -664,7 +667,7 @@ class ModuleGraph {
/** /**
* @param {Module} module the module * @param {Module} module the module
* @param {string | string[]} exportName a name of an export * @param {ExportInfoName | ExportInfoName[]} exportName a name of an export
* @returns {boolean | null} true, if the export is provided by the module. * @returns {boolean | null} true, if the export is provided by the module.
* null, if it's unknown. * null, if it's unknown.
* false, if it's not provided. * false, if it's not provided.

View File

@ -73,6 +73,8 @@ const memoize = require("./util/memoize");
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */ /** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NameForCondition} NameForCondition */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").BuildCallback} BuildCallback */ /** @typedef {import("./Module").BuildCallback} BuildCallback */
@ -222,14 +224,16 @@ makeSerializable(
/** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */ /** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */
/** @typedef {LoaderContext<EXPECTED_ANY>} AnyLoaderContext */
/** /**
* @typedef {object} NormalModuleCompilationHooks * @typedef {object} NormalModuleCompilationHooks
* @property {SyncHook<[LoaderContext<EXPECTED_ANY>, NormalModule]>} loader * @property {SyncHook<[AnyLoaderContext, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext<EXPECTED_ANY>]>} beforeLoaders * @property {SyncHook<[LoaderItem[], NormalModule, AnyLoaderContext]>} beforeLoaders
* @property {SyncHook<[NormalModule]>} beforeParse * @property {SyncHook<[NormalModule]>} beforeParse
* @property {SyncHook<[NormalModule]>} beforeSnapshot * @property {SyncHook<[NormalModule]>} beforeSnapshot
* @property {HookMap<FakeHook<AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>>>} readResourceForScheme * @property {HookMap<FakeHook<AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>>>} readResourceForScheme
* @property {HookMap<AsyncSeriesBailHook<[LoaderContext<EXPECTED_ANY>], string | Buffer | null>>} readResource * @property {HookMap<AsyncSeriesBailHook<[AnyLoaderContext], string | Buffer | null>>} readResource
* @property {SyncWaterfallHook<[Result, NormalModule]>} processResult * @property {SyncWaterfallHook<[Result, NormalModule]>} processResult
* @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
*/ */
@ -255,7 +259,7 @@ makeSerializable(
*/ */
/** /**
* @typedef {(resourcePath: string, getLoaderContext: (resourcePath: string) => LoaderContext<EXPECTED_ANY>) => Promise<string | Buffer<ArrayBufferLike>>} ReadResource * @typedef {(resourcePath: string, getLoaderContext: (resourcePath: string) => AnyLoaderContext) => Promise<string | Buffer<ArrayBufferLike>>} ReadResource
*/ */
/** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */ /** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
@ -438,7 +442,7 @@ class NormalModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
let ident = contextify( let ident = contextify(
@ -451,7 +455,7 @@ class NormalModule extends Module {
} }
/** /**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path) * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
*/ */
nameForCondition() { nameForCondition() {
const resource = /** @type {string} */ (this.getResource()); const resource = /** @type {string} */ (this.getResource());
@ -600,7 +604,8 @@ class NormalModule extends Module {
const { requestShortener } = compilation.runtimeTemplate; const { requestShortener } = compilation.runtimeTemplate;
const getCurrentLoaderName = () => { const getCurrentLoaderName = () => {
const currentLoader = this.getCurrentLoader( const currentLoader = this.getCurrentLoader(
/** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext) /** @type {AnyLoaderContext} */
(loaderContext)
); );
if (!currentLoader) return "(not in loader scope)"; if (!currentLoader) return "(not in loader scope)";
return requestShortener.shorten(currentLoader.loader); return requestShortener.shorten(currentLoader.loader);
@ -611,21 +616,18 @@ class NormalModule extends Module {
const getResolveContext = () => ({ const getResolveContext = () => ({
fileDependencies: { fileDependencies: {
add: (d) => add: (d) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ ( /** @type {AnyLoaderContext} */
loaderContext (loaderContext).addDependency(d)
).addDependency(d)
}, },
contextDependencies: { contextDependencies: {
add: (d) => add: (d) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ ( /** @type {AnyLoaderContext} */
loaderContext (loaderContext).addContextDependency(d)
).addContextDependency(d)
}, },
missingDependencies: { missingDependencies: {
add: (d) => add: (d) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ ( /** @type {AnyLoaderContext} */
loaderContext (loaderContext).addMissingDependency(d)
).addMissingDependency(d)
} }
}); });
const getAbsolutify = memoize(() => const getAbsolutify = memoize(() =>
@ -683,7 +685,8 @@ class NormalModule extends Module {
*/ */
getOptions: (schema) => { getOptions: (schema) => {
const loader = this.getCurrentLoader( const loader = this.getCurrentLoader(
/** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext) /** @type {AnyLoaderContext} */
(loaderContext)
); );
let { options } = /** @type {LoaderItem} */ (loader); let { options } = /** @type {LoaderItem} */ (loader);
@ -745,7 +748,8 @@ class NormalModule extends Module {
}, },
getLogger: (name) => { getLogger: (name) => {
const currentLoader = this.getCurrentLoader( const currentLoader = this.getCurrentLoader(
/** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext) /** @type {AnyLoaderContext} */
(loaderContext)
); );
return compilation.getLogger(() => return compilation.getLogger(() =>
[currentLoader && currentLoader.loader, name, this.identifier()] [currentLoader && currentLoader.loader, name, this.identifier()]
@ -834,19 +838,18 @@ class NormalModule extends Module {
Object.assign(loaderContext, options.loader); Object.assign(loaderContext, options.loader);
// After `hooks.loader.call` is called, the loaderContext is typed as LoaderContext<EXPECTED_ANY>
hooks.loader.call( hooks.loader.call(
/** @type {LoaderContext<EXPECTED_ANY>} */ /** @type {AnyLoaderContext} */
(loaderContext), (loaderContext),
this this
); );
return /** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext); return /** @type {AnyLoaderContext} */ (loaderContext);
} }
// TODO remove `loaderContext` in webpack@6 // TODO remove `loaderContext` in webpack@6
/** /**
* @param {LoaderContext<EXPECTED_ANY>} loaderContext loader context * @param {AnyLoaderContext} loaderContext loader context
* @param {number} index index * @param {number} index index
* @returns {LoaderItem | null} loader * @returns {LoaderItem | null} loader
*/ */
@ -995,7 +998,7 @@ class NormalModule extends Module {
hooks.beforeLoaders.call( hooks.beforeLoaders.call(
this.loaders, this.loaders,
this, this,
/** @type {LoaderContext<EXPECTED_ANY>} */ /** @type {AnyLoaderContext} */
(loaderContext) (loaderContext)
); );
} catch (err) { } catch (err) {
@ -1014,7 +1017,7 @@ class NormalModule extends Module {
loaders: this.loaders, loaders: this.loaders,
context: loaderContext, context: loaderContext,
/** /**
* @param {LoaderContext<EXPECTED_ANY>} loaderContext the loader context * @param {AnyLoaderContext} loaderContext the loader context
* @param {string} resourcePath the resource Path * @param {string} resourcePath the resource Path
* @param {(err: Error | null, result?: string | Buffer, sourceMap?: Result[1]) => void} callback callback * @param {(err: Error | null, result?: string | Buffer, sourceMap?: Result[1]) => void} callback callback
* @returns {Promise<void>} * @returns {Promise<void>}
@ -1062,7 +1065,8 @@ class NormalModule extends Module {
readResource( readResource(
resourcePath, resourcePath,
(resourcePath) => (resourcePath) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ ({ /** @type {AnyLoaderContext} */
({
addDependency(dependency) { addDependency(dependency) {
loaderContext.addDependency(dependency); loaderContext.addDependency(dependency);
}, },

View File

@ -16,7 +16,6 @@ const { contextify } = require("./util/identifier");
* @template T, R, AdditionalOptions * @template T, R, AdditionalOptions
* @typedef {import("tapable").Hook<T, R, AdditionalOptions>} Hook * @typedef {import("tapable").Hook<T, R, AdditionalOptions>} Hook
*/ */
/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
/** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */ /** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */
/** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency")} Dependency */
@ -53,20 +52,18 @@ const validate = createSchemaValidation(
*/ */
const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c); const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
/** @typedef {(percentage: number, msg: string, ...args: string[]) => void} HandlerFn */
/** /**
* @param {boolean | null | undefined} profile need profile * @param {boolean | null | undefined} profile need profile
* @param {Logger} logger logger * @param {Logger} logger logger
* @returns {defaultHandler} default handler * @returns {HandlerFn} default handler
*/ */
const createDefaultHandler = (profile, logger) => { const createDefaultHandler = (profile, logger) => {
/** @type {{ value: string | undefined, time: number }[]} */ /** @type {{ value: string | undefined, time: number }[]} */
const lastStateInfo = []; const lastStateInfo = [];
/** /** @type {HandlerFn} */
* @param {number} percentage percentage
* @param {string} msg message
* @param {...string} args additional arguments
*/
const defaultHandler = (percentage, msg, ...args) => { const defaultHandler = (percentage, msg, ...args) => {
if (profile) { if (profile) {
if (percentage === 0) { if (percentage === 0) {
@ -198,7 +195,7 @@ class ProgressPlugin {
/** /**
* @param {MultiCompiler} compiler webpack multi-compiler * @param {MultiCompiler} compiler webpack multi-compiler
* @param {HandlerFunction} handler function that executes for every progress step * @param {HandlerFn} handler function that executes for every progress step
* @returns {void} * @returns {void}
*/ */
_applyOnMultiCompiler(compiler, handler) { _applyOnMultiCompiler(compiler, handler) {
@ -217,7 +214,7 @@ class ProgressPlugin {
/** /**
* @param {Compiler} compiler webpack compiler * @param {Compiler} compiler webpack compiler
* @param {HandlerFunction} handler function that executes for every progress step * @param {HandlerFn} handler function that executes for every progress step
* @returns {void} * @returns {void}
*/ */
_applyOnCompiler(compiler, handler) { _applyOnCompiler(compiler, handler) {

View File

@ -59,13 +59,11 @@ class ProvidePlugin {
*/ */
const handler = (parser, parserOptions) => { const handler = (parser, parserOptions) => {
for (const name of Object.keys(definitions)) { for (const name of Object.keys(definitions)) {
const request = const request = [
/** @type {string[]} */
([
...(Array.isArray(definitions[name]) ...(Array.isArray(definitions[name])
? definitions[name] ? definitions[name]
: [definitions[name]]) : [definitions[name]])
]); ];
const splittedName = name.split("."); const splittedName = name.split(".");
if (splittedName.length > 0) { if (splittedName.length > 0) {
for (const [i, _] of splittedName.slice(1).entries()) { for (const [i, _] of splittedName.slice(1).entries()) {

View File

@ -110,12 +110,14 @@ class RecordIdsPlugin {
} }
}); });
/** @typedef {string[]} ChunkSources */
/** /**
* @param {Chunk} chunk the chunk * @param {Chunk} chunk the chunk
* @returns {string[]} sources of the chunk * @returns {ChunkSources} sources of the chunk
*/ */
const getChunkSources = (chunk) => { const getChunkSources = (chunk) => {
/** @type {string[]} */ /** @type {ChunkSources} */
const sources = []; const sources = [];
for (const chunkGroup of chunk.groupsIterable) { for (const chunkGroup of chunk.groupsIterable) {
const index = chunkGroup.chunks.indexOf(chunk); const index = chunkGroup.chunks.indexOf(chunk);

View File

@ -221,7 +221,7 @@ class Template {
} }
/** /**
* @param {string|string[]} s string to create prefix for * @param {string | string[]} s string to create prefix for
* @param {string} prefix prefix to compose * @param {string} prefix prefix to compose
* @returns {string} returns new prefix string * @returns {string} returns new prefix string
*/ */
@ -233,7 +233,7 @@ class Template {
} }
/** /**
* @param {string|string[]} str string or string collection * @param {string | string[]} str string or string collection
* @returns {string} returns a single string from array * @returns {string} returns a single string from array
*/ */
static asString(str) { static asString(str) {

View File

@ -133,7 +133,8 @@ const deprecated = (fn, message, code) => {
); );
}; };
/** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} TemplatePath */ /** @typedef {(pathData: PathData, assetInfo?: AssetInfo) => string} TemplatePathFn */
/** @typedef {string | TemplatePathFn} TemplatePath */
/** /**
* @param {TemplatePath} path the raw path * @param {TemplatePath} path the raw path

View File

@ -40,6 +40,7 @@ const getMimeTypes = memoize(() => require("mime-types"));
/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ /** @typedef {import("../Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */ /** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").BuildInfo} BuildInfo */ /** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -412,7 +413,7 @@ class AssetGenerator extends Generator {
(this.dataUrlOptions).mimetype; (this.dataUrlOptions).mimetype;
if (mimeType === undefined) { if (mimeType === undefined) {
const ext = path.extname( const ext = path.extname(
/** @type {string} */ /** @type {NameForCondition} */
(module.nameForCondition()) (module.nameForCondition())
); );
if ( if (

View File

@ -22,6 +22,7 @@ const ContainerExposedDependency = require("./ContainerExposedDependency");
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -78,7 +79,7 @@ class ContainerEntryModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${

View File

@ -21,6 +21,8 @@ const FallbackItemDependency = require("./FallbackItemDependency");
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -29,12 +31,13 @@ const FallbackItemDependency = require("./FallbackItemDependency");
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./RemoteModule").ExternalRequests} ExternalRequests */
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
class FallbackModule extends Module { class FallbackModule extends Module {
/** /**
* @param {string[]} requests list of requests to choose one * @param {ExternalRequests} requests list of requests to choose one
*/ */
constructor(requests) { constructor(requests) {
super(WEBPACK_MODULE_TYPE_FALLBACK); super(WEBPACK_MODULE_TYPE_FALLBACK);
@ -59,7 +62,7 @@ class FallbackModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${

View File

@ -22,6 +22,8 @@ const RemoteToExternalDependency = require("./RemoteToExternalDependency");
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -70,7 +72,7 @@ class RemoteModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${
@ -129,7 +131,7 @@ class RemoteModule extends Module {
} }
/** /**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path) * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
*/ */
nameForCondition() { nameForCondition() {
return this.request; return this.request;

View File

@ -29,6 +29,7 @@ const { addLocalModule, getLocalModule } = require("./LocalModulesHelpers");
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser").ExportedVariableInfo} ExportedVariableInfo */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** /**
@ -67,6 +68,8 @@ const isCallable = (expr) => {
return false; return false;
}; };
/** @typedef {Record<number, string>} Identifiers */
const PLUGIN_NAME = "AMDDefineDependencyParserPlugin"; const PLUGIN_NAME = "AMDDefineDependencyParserPlugin";
class AMDDefineDependencyParserPlugin { class AMDDefineDependencyParserPlugin {
@ -91,7 +94,7 @@ class AMDDefineDependencyParserPlugin {
* @param {JavascriptParser} parser the parser * @param {JavascriptParser} parser the parser
* @param {CallExpression} expr call expression * @param {CallExpression} expr call expression
* @param {BasicEvaluatedExpression} param param * @param {BasicEvaluatedExpression} param param
* @param {Record<number, string>} identifiers identifiers * @param {Identifiers} identifiers identifiers
* @param {string=} namedModule named module * @param {string=} namedModule named module
* @returns {boolean | undefined} result * @returns {boolean | undefined} result
*/ */
@ -105,7 +108,7 @@ class AMDDefineDependencyParserPlugin {
/** @type {string} */ (item.string) /** @type {string} */ (item.string)
) )
) { ) {
identifiers[/** @type {number} */ (idx)] = identifiers[idx] =
/** @type {string} */ /** @type {string} */
(item.string); (item.string);
} }
@ -346,9 +349,10 @@ class AMDDefineDependencyParserPlugin {
} }
} }
} }
/** @type {Map<string, ExportedVariableInfo>} */
const fnRenames = new Map(); const fnRenames = new Map();
if (array) { if (array) {
/** @type {Record<number, string>} */ /** @type {Identifiers} */
const identifiers = {}; const identifiers = {};
const param = parser.evaluateExpression(array); const param = parser.evaluateExpression(array);
const result = this.processArray( const result = this.processArray(

View File

@ -38,6 +38,7 @@ const UnsupportedDependency = require("./UnsupportedDependency");
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../javascript/JavascriptParser")} Parser */ /** @typedef {import("../javascript/JavascriptParser")} Parser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../javascript/BasicEvaluatedExpression").GetMembers} GetMembers */
const PLUGIN_NAME = "AMDPlugin"; const PLUGIN_NAME = "AMDPlugin";
@ -142,7 +143,7 @@ class AMDPlugin {
/** /**
* @param {string} optionExpr option expression * @param {string} optionExpr option expression
* @param {string} rootName root name * @param {string} rootName root name
* @param {() => string[]} getMembers callback * @param {GetMembers} getMembers callback
*/ */
const tapOptionsHooks = (optionExpr, rootName, getMembers) => { const tapOptionsHooks = (optionExpr, rootName, getMembers) => {
parser.hooks.expression parser.hooks.expression

View File

@ -17,11 +17,13 @@ const processExportInfo = require("./processExportInfo");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ExportsInfo")} ExportsInfo */ /** @typedef {import("../ExportsInfo")} ExportsInfo */
/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
@ -30,8 +32,6 @@ const processExportInfo = require("./processExportInfo");
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
/** @typedef {string[]} IDs */
const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); const idsSymbol = Symbol("CommonJsExportRequireDependency.ids");
const EMPTY_OBJECT = {}; const EMPTY_OBJECT = {};
@ -44,9 +44,9 @@ class CommonJsExportRequireDependency extends ModuleDependency {
* @param {Range} range range * @param {Range} range range
* @param {Range | null} valueRange value range * @param {Range | null} valueRange value range
* @param {CommonJSDependencyBaseKeywords} base base * @param {CommonJSDependencyBaseKeywords} base base
* @param {string[]} names names * @param {ExportInfoName[]} names names
* @param {string} request request * @param {string} request request
* @param {IDs} ids ids * @param {ExportInfoName[]} ids ids
* @param {boolean} resultUsed true, when the result is used * @param {boolean} resultUsed true, when the result is used
*/ */
constructor(range, valueRange, base, names, request, ids, resultUsed) { constructor(range, valueRange, base, names, request, ids, resultUsed) {
@ -73,7 +73,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @returns {IDs} the imported id * @returns {ExportInfoName[]} the imported id
*/ */
getIds(moduleGraph) { getIds(moduleGraph) {
return moduleGraph.getMeta(this)[idsSymbol] || this.ids; return moduleGraph.getMeta(this)[idsSymbol] || this.ids;
@ -81,7 +81,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @param {IDs} ids the imported ids * @param {ExportInfoName[]} ids the imported ids
* @returns {void} * @returns {void}
*/ */
setIds(moduleGraph, ids) { setIds(moduleGraph, ids) {
@ -92,7 +92,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
const ids = this.getIds(moduleGraph); const ids = this.getIds(moduleGraph);
@ -113,9 +113,9 @@ class CommonJsExportRequireDependency extends ModuleDependency {
/** @type {Module} */ (moduleGraph.getParentModule(this)) /** @type {Module} */ (moduleGraph.getParentModule(this))
); );
for (const name of this.names) { for (const name of this.names) {
const exportInfo = /** @type {ExportInfo} */ ( const exportInfo =
exportsInfo.getReadOnlyExportInfo(name) /** @type {ExportInfo} */
); (exportsInfo.getReadOnlyExportInfo(name));
const used = exportInfo.getUsed(runtime); const used = exportInfo.getUsed(runtime);
if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED;
if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); if (used !== UsageState.OnlyPropertiesUsed) return getFullResult();
@ -125,7 +125,7 @@ class CommonJsExportRequireDependency extends ModuleDependency {
if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
return getFullResult(); return getFullResult();
} }
/** @type {string[][]} */ /** @type {RawReferencedExports} */
const referencedExports = []; const referencedExports = [];
for (const exportInfo of exportsInfo.orderedExports) { for (const exportInfo of exportsInfo.orderedExports) {
processExportInfo( processExportInfo(

View File

@ -16,6 +16,7 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
@ -28,7 +29,7 @@ class CommonJsExportsDependency extends NullDependency {
* @param {Range} range range * @param {Range} range range
* @param {Range | null} valueRange value range * @param {Range | null} valueRange value range
* @param {CommonJSDependencyBaseKeywords} base base * @param {CommonJSDependencyBaseKeywords} base base
* @param {string[]} names names * @param {ExportInfoName[]} names names
*/ */
constructor(range, valueRange, base, names) { constructor(range, valueRange, base, names) {
super(); super();

View File

@ -22,9 +22,11 @@ const ModuleDecoratorDependency = require("./ModuleDecoratorDependency");
/** @typedef {import("estree").Super} Super */ /** @typedef {import("estree").Super} Super */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../javascript/JavascriptParser").Members} Members */
/** @typedef {import("../javascript/JavascriptParser").StatementPath} StatementPath */ /** @typedef {import("../javascript/JavascriptParser").StatementPath} StatementPath */
/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
@ -94,9 +96,10 @@ const isFalsyLiteral = (expr) => {
/** /**
* @param {JavascriptParser} parser the parser * @param {JavascriptParser} parser the parser
* @param {Expression} expr expression * @param {Expression} expr expression
* @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call * @returns {{ argument: BasicEvaluatedExpression, ids: ExportInfoName[] } | undefined} parsed call
*/ */
const parseRequireCall = (parser, expr) => { const parseRequireCall = (parser, expr) => {
/** @type {ExportInfoName[]} */
const ids = []; const ids = [];
while (expr.type === "MemberExpression") { while (expr.type === "MemberExpression") {
if (expr.object.type === "Super") return; if (expr.object.type === "Super") return;
@ -146,7 +149,7 @@ class CommonJsExportsParserPlugin {
/** /**
* @param {boolean} topLevel true, when the export is on top level * @param {boolean} topLevel true, when the export is on top level
* @param {string[]} members members of the export * @param {Members} members members of the export
* @param {Expression | undefined} valueExpr expression for the value * @param {Expression | undefined} valueExpr expression for the value
* @returns {void} * @returns {void}
*/ */
@ -189,7 +192,7 @@ class CommonJsExportsParserPlugin {
/** /**
* @param {AssignmentExpression} expr expression * @param {AssignmentExpression} expr expression
* @param {CommonJSDependencyBaseKeywords} base commonjs base keywords * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords
* @param {string[]} members members of the export * @param {Members} members members of the export
* @returns {boolean | undefined} true, when the expression was handled * @returns {boolean | undefined} true, when the expression was handled
*/ */
const handleAssignExport = (expr, base, members) => { const handleAssignExport = (expr, base, members) => {
@ -312,7 +315,7 @@ class CommonJsExportsParserPlugin {
/** /**
* @param {Expression | Super} expr expression * @param {Expression | Super} expr expression
* @param {CommonJSDependencyBaseKeywords} base commonjs base keywords * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords
* @param {string[]} members members of the export * @param {Members} members members of the export
* @param {CallExpression=} call call expression * @param {CallExpression=} call call expression
* @returns {boolean | void} true, when the expression was handled * @returns {boolean | void} true, when the expression was handled
*/ */

View File

@ -14,20 +14,22 @@ const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("../util/chainedImports").IdRanges} IdRanges */
class CommonJsFullRequireDependency extends ModuleDependency { class CommonJsFullRequireDependency 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
* @param {string[]} names accessed properties on module * @param {ExportInfoName[]} names accessed properties on module
* @param {Range[]=} idRanges ranges for members of ids; the two arrays are right-aligned * @param {IdRanges=} idRanges ranges for members of ids; the two arrays are right-aligned
*/ */
constructor( constructor(
request, request,
@ -47,7 +49,7 @@ class CommonJsFullRequireDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
if (this.call) { if (this.call) {

View File

@ -38,6 +38,8 @@ const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser").ImportSource} ImportSource */ /** @typedef {import("../javascript/JavascriptParser").ImportSource} ImportSource */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../javascript/JavascriptParser").Members} Members */
/** @typedef {import("../javascript/JavascriptParser").CalleeMembers} CalleeMembers */
/** /**
* @typedef {object} CommonJsImportSettings * @typedef {object} CommonJsImportSettings
@ -76,7 +78,7 @@ class CommonJsImportsParserPlugin {
// #region metadata // #region metadata
/** /**
* @param {string} expression expression * @param {string} expression expression
* @param {() => string[]} getMembers get members * @param {() => Members} getMembers get members
*/ */
const tapRequireExpression = (expression, getMembers) => { const tapRequireExpression = (expression, getMembers) => {
parser.hooks.typeof parser.hooks.typeof
@ -373,9 +375,9 @@ class CommonJsImportsParserPlugin {
// #region Require with property access // #region Require with property access
/** /**
* @param {Expression} expr expression * @param {Expression} expr expression
* @param {string[]} calleeMembers callee members * @param {CalleeMembers} calleeMembers callee members
* @param {CallExpression} callExpr call expression * @param {CallExpression} callExpr call expression
* @param {string[]} members members * @param {Members} members members
* @param {Range[]} memberRanges member ranges * @param {Range[]} memberRanges member ranges
* @returns {boolean | void} true when handled * @returns {boolean | void} true when handled
*/ */
@ -409,9 +411,9 @@ class CommonJsImportsParserPlugin {
}; };
/** /**
* @param {CallExpression} expr expression * @param {CallExpression} expr expression
* @param {string[]} calleeMembers callee members * @param {CalleeMembers} calleeMembers callee members
* @param {CallExpression} callExpr call expression * @param {CallExpression} callExpr call expression
* @param {string[]} members members * @param {Members} members members
* @param {Range[]} memberRanges member ranges * @param {Range[]} memberRanges member ranges
* @returns {boolean | void} true when handled * @returns {boolean | void} true when handled
*/ */

View File

@ -13,9 +13,10 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
@ -26,7 +27,7 @@ class CommonJsSelfReferenceDependency extends NullDependency {
/** /**
* @param {Range} range range * @param {Range} range range
* @param {CommonJSDependencyBaseKeywords} base base * @param {CommonJSDependencyBaseKeywords} base base
* @param {string[]} names names * @param {ExportInfoName[]} names names
* @param {boolean} call is a call * @param {boolean} call is a call
*/ */
constructor(range, base, names, call) { constructor(range, base, names, call) {
@ -56,7 +57,7 @@ class CommonJsSelfReferenceDependency extends NullDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return [this.call ? this.names.slice(0, -1) : this.names]; return [this.call ? this.names.slice(0, -1) : this.names];

View File

@ -9,6 +9,7 @@ const makeSerializable = require("../util/makeSerializable");
const NullDependency = require("./NullDependency"); const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("./NullDependency").RawRuntimeRequirements} RawRuntimeRequirements */
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
@ -23,7 +24,7 @@ class ConstDependency extends NullDependency {
/** /**
* @param {string} expression the expression * @param {string} expression the expression
* @param {number | Range} range the source range * @param {number | Range} range the source range
* @param {(string[] | null)=} runtimeRequirements runtime requirements * @param {RawRuntimeRequirements | null=} runtimeRequirements runtime requirements
*/ */
constructor(expression, range, runtimeRequirements) { constructor(expression, range, runtimeRequirements) {
super(); super();

View File

@ -10,7 +10,8 @@ const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("../ContextModule")} ContextModule */ /** @typedef {import("../ContextModule")} ContextModule */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
@ -24,7 +25,7 @@ class ContextElementDependency extends ModuleDependency {
* @param {string | undefined} userRequest user request * @param {string | undefined} userRequest user request
* @param {string | undefined} typePrefix type prefix * @param {string | undefined} typePrefix type prefix
* @param {string} category category * @param {string} category category
* @param {(string[][] | null)=} referencedExports referenced exports * @param {RawReferencedExports | null=} referencedExports referenced exports
* @param {string=} context context * @param {string=} context context
* @param {ImportAttributes=} attributes import assertions * @param {ImportAttributes=} attributes import assertions
*/ */
@ -66,7 +67,7 @@ class ContextElementDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED;

View File

@ -11,7 +11,7 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
@ -77,7 +77,7 @@ class CssIcssSymbolDependency extends NullDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return [[this.name]]; return [[this.name]];

View File

@ -11,7 +11,7 @@ const CssLocalIdentifierDependency = require("./CssLocalIdentifierDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../css/CssParser").Range} Range */ /** @typedef {import("../css/CssParser").Range} Range */
@ -60,7 +60,7 @@ class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
if (this.declaredSet && !this.declaredSet.has(this.name)) { if (this.declaredSet && !this.declaredSet.has(this.name)) {

View File

@ -14,6 +14,7 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
@ -27,13 +28,13 @@ const NullDependency = require("./NullDependency");
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @param {Module} module the module * @param {Module} module the module
* @param {string[] | null} _exportName name of the export if any * @param {ExportInfoName[] | null} exportName_ name of the export if any
* @param {string | null} property name of the requested property * @param {string | null} property name of the requested property
* @param {RuntimeSpec} runtime for which runtime * @param {RuntimeSpec} runtime for which runtime
* @returns {undefined | null | number | boolean | string[] | SortableSet<string>} value of the property * @returns {undefined | null | boolean | ExportInfoName[]} value of the property
*/ */
const getProperty = (moduleGraph, module, _exportName, property, runtime) => { const getProperty = (moduleGraph, module, exportName_, property, runtime) => {
if (!_exportName) { if (!exportName_) {
switch (property) { switch (property) {
case "usedExports": { case "usedExports": {
const usedExports = moduleGraph const usedExports = moduleGraph
@ -50,7 +51,7 @@ const getProperty = (moduleGraph, module, _exportName, property, runtime) => {
} }
} }
} }
const exportName = /** @type {string[]} */ (_exportName); const exportName = /** @type {ExportInfoName[]} */ (exportName_);
switch (property) { switch (property) {
case "canMangle": { case "canMangle": {
const exportsInfo = moduleGraph.getExportsInfo(module); const exportsInfo = moduleGraph.getExportsInfo(module);
@ -89,7 +90,7 @@ const getProperty = (moduleGraph, module, _exportName, property, runtime) => {
class ExportsInfoDependency extends NullDependency { class ExportsInfoDependency extends NullDependency {
/** /**
* @param {Range} range range * @param {Range} range range
* @param {string[] | null} exportName export name * @param {ExportInfoName[] | null} exportName export name
* @param {string | null} property property * @param {string | null} property property
*/ */
constructor(range, exportName, property) { constructor(range, exportName, property) {

View File

@ -17,6 +17,7 @@ const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDepend
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./HarmonyImportDependency").Ids} Ids */
/** /**
* Dependency for static evaluating import specifier. e.g. * Dependency for static evaluating import specifier. e.g.
@ -29,7 +30,7 @@ class HarmonyEvaluatedImportSpecifierDependency extends HarmonyImportSpecifierDe
/** /**
* @param {string} request the request string * @param {string} request the request string
* @param {number} sourceOrder source order * @param {number} sourceOrder source order
* @param {string[]} ids ids * @param {Ids} ids ids
* @param {string} name name * @param {string} name name
* @param {Range} range location in source code * @param {Range} range location in source code
* @param {ImportAttributes | undefined} attributes import assertions * @param {ImportAttributes | undefined} attributes import assertions

View File

@ -33,7 +33,8 @@ const processExportInfo = require("./processExportInfo");
/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ /** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ExportsInfo")} ExportsInfo */ /** @typedef {import("../ExportsInfo")} ExportsInfo */
@ -54,8 +55,8 @@ const processExportInfo = require("./processExportInfo");
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./HarmonyImportDependency").Ids} Ids */
/** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */ /** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */
/** @typedef {import("./processExportInfo").ReferencedExports} ReferencedExports */
/** @typedef {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ /** @typedef {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */
@ -63,12 +64,10 @@ const { ExportPresenceModes } = HarmonyImportDependency;
const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids");
/** @typedef {string[]} IDs */
class NormalReexportItem { class NormalReexportItem {
/** /**
* @param {string} name export name * @param {string} name export name
* @param {IDs} ids reexported ids from other module * @param {Ids} ids reexported ids from other module
* @param {ExportInfo} exportInfo export info from other module * @param {ExportInfo} exportInfo export info from other module
* @param {boolean} checked true, if it should be checked at runtime if this export exists * @param {boolean} checked true, if it should be checked at runtime if this export exists
* @param {boolean} hidden true, if it is hidden behind another active export in the same module * @param {boolean} hidden true, if it is hidden behind another active export in the same module
@ -121,14 +120,13 @@ class ExportMode {
} }
} }
/** @typedef {string[]} Names */
/** @typedef {number[]} DependencyIndices */ /** @typedef {number[]} DependencyIndices */
/** /**
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {HarmonyExportImportedSpecifierDependency[]} dependencies dependencies * @param {HarmonyExportImportedSpecifierDependency[]} dependencies dependencies
* @param {HarmonyExportImportedSpecifierDependency=} additionalDependency additional dependency * @param {HarmonyExportImportedSpecifierDependency=} additionalDependency additional dependency
* @returns {{ names: Names, dependencyIndices: DependencyIndices }} result * @returns {{ names: ExportInfoName[], dependencyIndices: DependencyIndices }} result
*/ */
const determineExportAssignments = ( const determineExportAssignments = (
moduleGraph, moduleGraph,
@ -137,7 +135,7 @@ const determineExportAssignments = (
) => { ) => {
/** @type {Set<ExportInfoName>} */ /** @type {Set<ExportInfoName>} */
const names = new Set(); const names = new Set();
/** @type {number[]} */ /** @type {DependencyIndices} */
const dependencyIndices = []; const dependencyIndices = [];
if (additionalDependency) { if (additionalDependency) {
@ -169,7 +167,7 @@ const determineExportAssignments = (
/** /**
* @param {object} options options * @param {object} options options
* @param {Names} options.names names * @param {ExportInfoName[]} options.names names
* @param {DependencyIndices} options.dependencyIndices dependency indices * @param {DependencyIndices} options.dependencyIndices dependency indices
* @param {string} name name * @param {string} name name
* @param {ReadonlyArray<HarmonyExportImportedSpecifierDependency>} dependencies dependencies * @param {ReadonlyArray<HarmonyExportImportedSpecifierDependency>} dependencies dependencies
@ -372,7 +370,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {string} request the request string * @param {string} request the request string
* @param {number} sourceOrder the order in the original source file * @param {number} sourceOrder the order in the original source file
* @param {IDs} ids the requested export name of the imported module * @param {Ids} ids the requested export name of the imported module
* @param {string | null} name the export name of for this module * @param {string | null} name the export name of for this module
* @param {Set<string>} activeExports other named exports in the module * @param {Set<string>} activeExports other named exports in the module
* @param {ReadonlyArray<HarmonyExportImportedSpecifierDependency> | null} otherStarExports other star exports in the module before this import * @param {ReadonlyArray<HarmonyExportImportedSpecifierDependency> | null} otherStarExports other star exports in the module before this import
@ -431,7 +429,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @returns {IDs} the imported id * @returns {Ids} the imported id
*/ */
getIds(moduleGraph) { getIds(moduleGraph) {
return moduleGraph.getMeta(this)[idsSymbol] || this.ids; return moduleGraph.getMeta(this)[idsSymbol] || this.ids;
@ -439,7 +437,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @param {IDs} ids the imported ids * @param {Ids} ids the imported ids
* @returns {void} * @returns {void}
*/ */
setIds(moduleGraph, ids) { setIds(moduleGraph, ids) {
@ -568,7 +566,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
const mode = this.getMode(moduleGraph, runtime); const mode = this.getMode(moduleGraph, runtime);
@ -587,7 +585,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
if (!mode.partialNamespaceExportInfo) { if (!mode.partialNamespaceExportInfo) {
return Dependency.EXPORTS_OBJECT_REFERENCED; return Dependency.EXPORTS_OBJECT_REFERENCED;
} }
/** @type {ReferencedExports} */ /** @type {RawReferencedExports} */
const referencedExports = []; const referencedExports = [];
processExportInfo( processExportInfo(
runtime, runtime,
@ -603,7 +601,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
if (!mode.partialNamespaceExportInfo) { if (!mode.partialNamespaceExportInfo) {
return Dependency.EXPORTS_OBJECT_REFERENCED; return Dependency.EXPORTS_OBJECT_REFERENCED;
} }
/** @type {ReferencedExports} */ /** @type {RawReferencedExports} */
const referencedExports = []; const referencedExports = [];
processExportInfo( processExportInfo(
runtime, runtime,
@ -619,7 +617,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
return Dependency.EXPORTS_OBJECT_REFERENCED; return Dependency.EXPORTS_OBJECT_REFERENCED;
case "normal-reexport": { case "normal-reexport": {
/** @type {ReferencedExports} */ /** @type {RawReferencedExports} */
const referencedExports = []; const referencedExports = [];
for (const { for (const {
ids, ids,
@ -639,7 +637,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @returns {{ names: Names, namesSlice: number, dependencyIndices: DependencyIndices, dependencyIndex: number } | undefined} exported names and their origin dependency * @returns {{ names: ExportInfoName[], namesSlice: number, dependencyIndices: DependencyIndices, dependencyIndex: number } | undefined} exported names and their origin dependency
*/ */
_discoverActiveExportsFromOtherStarExports(moduleGraph) { _discoverActiveExportsFromOtherStarExports(moduleGraph) {
if (!this.otherStarExports) return; if (!this.otherStarExports) return;
@ -881,7 +879,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
const importedModule = moduleGraph.getModule(this); const importedModule = moduleGraph.getModule(this);
if (importedModule) { if (importedModule) {
const exportsInfo = moduleGraph.getExportsInfo(importedModule); const exportsInfo = moduleGraph.getExportsInfo(importedModule);
/** @type {Map<string, string[]>} */ /** @type {Map<string, ExportInfoName[]>} */
const conflicts = new Map(); const conflicts = new Map();
for (const exportInfo of exportsInfo.orderedExports) { for (const exportInfo of exportsInfo.orderedExports) {
if (exportInfo.provided !== true) continue; if (exportInfo.provided !== true) continue;
@ -1279,7 +1277,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
* @param {string} comment comment * @param {string} comment comment
* @param {UsedName} key key * @param {UsedName} key key
* @param {string} name name * @param {string} name name
* @param {string | string[] | null | false} valueKey value key * @param {UsedName | null} valueKey value key
* @param {RuntimeRequirements} runtimeRequirements runtime requirements * @param {RuntimeRequirements} runtimeRequirements runtime requirements
* @returns {HarmonyExportInitFragment} harmony export init fragment * @returns {HarmonyExportInitFragment} harmony export init fragment
*/ */
@ -1304,7 +1302,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
/** /**
* @param {Module} module module * @param {Module} module module
* @param {string | string[] | false} key key * @param {UsedName} key key
* @param {string} name name * @param {string} name name
* @param {number} fakeType fake type * @param {number} fakeType fake type
* @param {RuntimeRequirements} runtimeRequirements runtime requirements * @param {RuntimeRequirements} runtimeRequirements runtime requirements
@ -1343,7 +1341,7 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
/** /**
* @param {Module} module module * @param {Module} module module
* @param {ChunkGraph} chunkGraph chunkGraph * @param {ChunkGraph} chunkGraph chunkGraph
* @param {string | false | string[]} key key * @param {UsedName} key key
* @param {string} name name * @param {string} name name
* @param {ExportsType} exportsType exportsType * @param {ExportsType} exportsType exportsType
* @param {RuntimeRequirements} runtimeRequirements runtimeRequirements * @param {RuntimeRequirements} runtimeRequirements runtimeRequirements

View File

@ -15,7 +15,7 @@ const { filterRuntime, mergeRuntime } = require("../util/runtime");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ExportsInfo")} ExportsInfo */ /** @typedef {import("../ExportsInfo")} ExportsInfo */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
@ -54,6 +54,8 @@ const ExportPresenceModes = {
} }
}; };
/** @typedef {string[]} Ids */
class HarmonyImportDependency extends ModuleDependency { class HarmonyImportDependency extends ModuleDependency {
/** /**
* @param {string} request request string * @param {string} request request string
@ -76,7 +78,7 @@ class HarmonyImportDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return Dependency.NO_EXPORTS_REFERENCED; return Dependency.NO_EXPORTS_REFERENCED;
@ -157,7 +159,7 @@ class HarmonyImportDependency extends ModuleDependency {
/** /**
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {string[]} ids imported ids * @param {Ids} ids imported ids
* @param {string} additionalMessage extra info included in the error message * @param {string} additionalMessage extra info included in the error message
* @returns {WebpackError[] | undefined} errors * @returns {WebpackError[] | undefined} errors
*/ */

View File

@ -33,12 +33,15 @@ const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDepend
/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
/** @typedef {import("../javascript/JavascriptParser").ImportDeclaration} ImportDeclaration */ /** @typedef {import("../javascript/JavascriptParser").ImportDeclaration} ImportDeclaration */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../javascript/JavascriptParser").Members} Members */
/** @typedef {import("../javascript/JavascriptParser").MembersOptionals} MembersOptionals */
/** @typedef {import("./HarmonyImportDependency").Ids} Ids */
const harmonySpecifierTag = Symbol("harmony import"); const harmonySpecifierTag = Symbol("harmony import");
/** /**
* @typedef {object} HarmonySettings * @typedef {object} HarmonySettings
* @property {string[]} ids * @property {Ids} ids
* @property {string} source * @property {string} source
* @property {number} sourceOrder * @property {number} sourceOrder
* @property {string} name * @property {string} name
@ -74,9 +77,9 @@ module.exports = class HarmonyImportDependencyParserPlugin {
const { exportPresenceMode } = this; const { exportPresenceMode } = this;
/** /**
* @param {string[]} members members * @param {Members} members members
* @param {boolean[]} membersOptionals members Optionals * @param {MembersOptionals} membersOptionals members Optionals
* @returns {string[]} a non optional part * @returns {Ids} a non optional part
*/ */
function getNonOptionalPart(members, membersOptionals) { function getNonOptionalPart(members, membersOptionals) {
let i = 0; let i = 0;
@ -188,7 +191,7 @@ module.exports = class HarmonyImportDependencyParserPlugin {
/** @type {HarmonySettings} */ /** @type {HarmonySettings} */
(rootInfo.tagInfo.data); (rootInfo.tagInfo.data);
const members = const members =
/** @type {(() => string[])} */ /** @type {(() => Members)} */
(rightPart.getMembers)(); (rightPart.getMembers)();
const dep = new HarmonyEvaluatedImportSpecifierDependency( const dep = new HarmonyEvaluatedImportSpecifierDependency(
settings.source, settings.source,

View File

@ -17,7 +17,8 @@ const HarmonyImportDependency = require("./HarmonyImportDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ /** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
@ -31,9 +32,9 @@ const HarmonyImportDependency = require("./HarmonyImportDependency");
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("../util/chainedImports").IdRanges} IdRanges */
/** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */ /** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */
/** @typedef {HarmonyImportDependency.Ids} Ids */
/** @typedef {string[]} IDs */
const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids");
@ -43,12 +44,12 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {string} request request * @param {string} request request
* @param {number} sourceOrder source order * @param {number} sourceOrder source order
* @param {IDs} ids ids * @param {Ids} ids ids
* @param {string} name name * @param {string} name name
* @param {Range} range range * @param {Range} range range
* @param {ExportPresenceMode} exportPresenceMode export presence mode * @param {ExportPresenceMode} exportPresenceMode export presence mode
* @param {ImportAttributes | undefined} attributes import attributes * @param {ImportAttributes | undefined} attributes import attributes
* @param {Range[] | undefined} idRanges ranges for members of ids; the two arrays are right-aligned * @param {IdRanges | undefined} idRanges ranges for members of ids; the two arrays are right-aligned
* @param {boolean=} defer is defer phase * @param {boolean=} defer is defer phase
*/ */
constructor( constructor(
@ -100,7 +101,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @returns {IDs} the imported ids * @returns {Ids} the imported ids
*/ */
getIds(moduleGraph) { getIds(moduleGraph) {
const meta = moduleGraph.getMetaIfExisting(this); const meta = moduleGraph.getMetaIfExisting(this);
@ -111,7 +112,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @param {IDs} ids the imported ids * @param {Ids} ids the imported ids
* @returns {void} * @returns {void}
*/ */
setIds(moduleGraph, ids) { setIds(moduleGraph, ids) {
@ -142,7 +143,7 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
let ids = this.getIds(moduleGraph); let ids = this.getIds(moduleGraph);
@ -188,12 +189,12 @@ class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
} }
/** /**
* @param {IDs=} ids ids * @param {Ids=} ids ids
* @returns {IDs[]} referenced exports * @returns {RawReferencedExports} referenced exports
*/ */
_getReferencedExportsInDestructuring(ids) { _getReferencedExportsInDestructuring(ids) {
if (this.referencedPropertiesInDestructuring) { if (this.referencedPropertiesInDestructuring) {
/** @type {string[][]} */ /** @type {RawReferencedExports} */
const refs = []; const refs = [];
for (const { id } of this.referencedPropertiesInDestructuring) { for (const { id } of this.referencedPropertiesInDestructuring) {
refs.push(ids ? [...ids, id] : [id]); refs.push(ids ? [...ids, id] : [id]);
@ -378,7 +379,7 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
shorthand, shorthand,
range range
} of dep.referencedPropertiesInDestructuring) { } of dep.referencedPropertiesInDestructuring) {
/** @type {IDs} */ /** @type {Ids} */
const concatedIds = [...prefixedIds, id]; const concatedIds = [...prefixedIds, id];
const module = /** @type {Module} */ (moduleGraph.getModule(dep)); const module = /** @type {Module} */ (moduleGraph.getModule(dep));
const used = moduleGraph const used = moduleGraph
@ -406,7 +407,7 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
* @param {HarmonyImportSpecifierDependency} dep dependency * @param {HarmonyImportSpecifierDependency} dep dependency
* @param {ReplaceSource} source source * @param {ReplaceSource} source source
* @param {DependencyTemplateContext} templateContext context * @param {DependencyTemplateContext} templateContext context
* @param {IDs} ids ids * @param {Ids} ids ids
* @returns {string} generated code * @returns {string} generated code
*/ */
_getCodeForIds(dep, source, templateContext, ids) { _getCodeForIds(dep, source, templateContext, ids) {

View File

@ -11,7 +11,8 @@ const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
@ -26,7 +27,7 @@ class ImportDependency extends ModuleDependency {
/** /**
* @param {string} request the request * @param {string} request the request
* @param {Range} range expression range * @param {Range} range expression range
* @param {(string[][] | null)=} referencedExports list of referenced exports * @param {RawReferencedExports | null=} referencedExports list of referenced exports
* @param {ImportAttributes=} attributes import attributes * @param {ImportAttributes=} attributes import attributes
*/ */
constructor(request, range, referencedExports, attributes) { constructor(request, range, referencedExports, attributes) {
@ -48,7 +49,7 @@ class ImportDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED;

View File

@ -15,12 +15,13 @@ const ImportDependency = require("./ImportDependency");
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {ImportDependency.RawReferencedExports} RawReferencedExports */
class ImportEagerDependency extends ImportDependency { class ImportEagerDependency extends ImportDependency {
/** /**
* @param {string} request the request * @param {string} request the request
* @param {Range} range expression range * @param {Range} range expression range
* @param {(string[][] | null)=} referencedExports list of referenced exports * @param {RawReferencedExports | null=} referencedExports list of referenced exports
* @param {ImportAttributes=} attributes import attributes * @param {ImportAttributes=} attributes import attributes
*/ */
constructor(request, range, referencedExports, attributes) { constructor(request, range, referencedExports, attributes) {

View File

@ -18,10 +18,14 @@ const ImportMetaContextDependency = require("./ImportMetaContextDependency");
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../ContextModule").ContextModuleOptions} ContextModuleOptions */ /** @typedef {import("../ContextModule").ContextModuleOptions} ContextModuleOptions */
/** @typedef {import("../ContextModule").ContextMode} ContextMode */
/** @typedef {import("../Chunk").ChunkName} ChunkName */
/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ /** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {Pick<ContextModuleOptions, 'mode'|'recursive'|'regExp'|'include'|'exclude'|'chunkName'>&{groupOptions: RawChunkGroupOptions, exports?: ContextModuleOptions["referencedExports"]}} ImportMetaContextOptions */
/** @typedef {Pick<ContextModuleOptions, 'mode' | 'recursive' | 'regExp' | 'include' | 'exclude' | 'chunkName'> & { groupOptions: RawChunkGroupOptions, exports?: RawReferencedExports }} ImportMetaContextOptions */
/** /**
* @param {Property} prop property * @param {Property} prop property
@ -83,7 +87,7 @@ module.exports = class ImportMetaContextDependencyParserPlugin {
const errors = []; const errors = [];
let regExp = /^\.\/.*$/; let regExp = /^\.\/.*$/;
let recursive = true; let recursive = true;
/** @type {ContextModuleOptions["mode"]} */ /** @type {ContextMode} */
let mode = "sync"; let mode = "sync";
/** @type {ContextModuleOptions["include"]} */ /** @type {ContextModuleOptions["include"]} */
let include; let include;
@ -91,9 +95,9 @@ module.exports = class ImportMetaContextDependencyParserPlugin {
let exclude; let exclude;
/** @type {RawChunkGroupOptions} */ /** @type {RawChunkGroupOptions} */
const groupOptions = {}; const groupOptions = {};
/** @type {ContextModuleOptions["chunkName"]} */ /** @type {ChunkName | undefined} */
let chunkName; let chunkName;
/** @type {ContextModuleOptions["referencedExports"]} */ /** @type {RawReferencedExports | undefined} */
let exports; let exports;
if (optionsNode) { if (optionsNode) {
for (const prop of /** @type {ObjectExpression} */ (optionsNode) for (const prop of /** @type {ObjectExpression} */ (optionsNode)

View File

@ -30,6 +30,7 @@ const ConstDependency = require("./ConstDependency");
/** @typedef {import("../NormalModule")} NormalModule */ /** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../javascript/JavascriptParser")} Parser */ /** @typedef {import("../javascript/JavascriptParser")} Parser */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../javascript/JavascriptParser").Members} Members */
const getCriticalDependencyWarning = memoize(() => const getCriticalDependencyWarning = memoize(() =>
require("./CriticalDependencyWarning") require("./CriticalDependencyWarning")
@ -83,7 +84,7 @@ class ImportMetaPlugin {
JSON.stringify(getUrl(parser.state.module)); JSON.stringify(getUrl(parser.state.module));
const importMetaWebpackVersion = () => JSON.stringify(webpackVersion); const importMetaWebpackVersion = () => JSON.stringify(webpackVersion);
/** /**
* @param {string[]} members members * @param {Members} members members
* @returns {string} error message * @returns {string} error message
*/ */
const importMetaUnknownProperty = (members) => const importMetaUnknownProperty = (members) =>

View File

@ -19,14 +19,17 @@ const ImportWeakDependency = require("./ImportWeakDependency");
/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ /** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
/** @typedef {import("../ContextModule").ContextMode} ContextMode */ /** @typedef {import("../ContextModule").ContextMode} ContextMode */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../javascript/JavascriptParser").ImportExpression} ImportExpression */ /** @typedef {import("../javascript/JavascriptParser").ImportExpression} ImportExpression */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../javascript/JavascriptParser").ParserState} ParserState */ /** @typedef {import("../javascript/JavascriptParser").ParserState} ParserState */
/** @typedef {import("../javascript/JavascriptParser").Members} Members */
/** @typedef {import("../javascript/JavascriptParser").MembersOptionals} MembersOptionals */
/** @typedef {{ references: string[][], expression: ImportExpression }} ImportSettings */ /** @typedef {{ references: RawReferencedExports, expression: ImportExpression }} ImportSettings */
/** @typedef {WeakMap<ImportExpression, string[][]>} State */ /** @typedef {WeakMap<ImportExpression, RawReferencedExports>} State */
/** @type {WeakMap<ParserState, State>} */ /** @type {WeakMap<ParserState, State>} */
const parserStateMap = new WeakMap(); const parserStateMap = new WeakMap();
@ -67,8 +70,8 @@ class ImportParserPlugin {
Array.from(enumerable, (e) => [e]); Array.from(enumerable, (e) => [e]);
/** /**
* @param {string[]} members members * @param {Members} members members
* @param {boolean[]} membersOptionals members Optionals * @param {MembersOptionals} membersOptionals members Optionals
* @returns {string[]} a non optional part * @returns {string[]} a non optional part
*/ */
function getNonOptionalPart(members, membersOptionals) { function getNonOptionalPart(members, membersOptionals) {
@ -92,7 +95,7 @@ class ImportParserPlugin {
) { ) {
const importCall = decl.init.argument; const importCall = decl.init.argument;
const state = getState(parser); const state = getState(parser);
/** @type {string[][]} */ /** @type {RawReferencedExports} */
const references = []; const references = [];
state.set(importCall, references); state.set(importCall, references);
parser.tagVariable( parser.tagVariable(
@ -140,7 +143,7 @@ class ImportParserPlugin {
let mode = /** @type {ContextMode} */ (this.options.dynamicImportMode); let mode = /** @type {ContextMode} */ (this.options.dynamicImportMode);
let include = null; let include = null;
let exclude = null; let exclude = null;
/** @type {string[][] | null} */ /** @type {RawReferencedExports | null} */
let exports = null; let exports = null;
/** @type {RawChunkGroupOptions} */ /** @type {RawChunkGroupOptions} */
const groupOptions = {}; const groupOptions = {};
@ -326,7 +329,7 @@ class ImportParserPlugin {
!( !(
typeof importOptions.webpackExports === "string" || typeof importOptions.webpackExports === "string" ||
(Array.isArray(importOptions.webpackExports) && (Array.isArray(importOptions.webpackExports) &&
/** @type {string[]} */ (importOptions.webpackExports).every( importOptions.webpackExports.every(
(item) => typeof item === "string" (item) => typeof item === "string"
)) ))
) )

View File

@ -15,12 +15,13 @@ const ImportDependency = require("./ImportDependency");
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {ImportDependency.RawReferencedExports} RawReferencedExports */
class ImportWeakDependency extends ImportDependency { class ImportWeakDependency extends ImportDependency {
/** /**
* @param {string} request the request * @param {string} request the request
* @param {Range} range expression range * @param {Range} range expression range
* @param {(string[][] | null)=} referencedExports list of referenced exports * @param {RawReferencedExports | null=} referencedExports list of referenced exports
* @param {ImportAttributes=} attributes import attributes * @param {ImportAttributes=} attributes import attributes
*/ */
constructor(request, range, referencedExports, attributes) { constructor(request, range, referencedExports, attributes) {

View File

@ -12,7 +12,7 @@ const makeSerializable = require("../util/makeSerializable");
const NullDependency = require("./NullDependency"); const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
@ -55,7 +55,7 @@ class ModuleDecoratorDependency extends NullDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return this.allowExportsAccess return this.allowExportsAccess

View File

@ -12,6 +12,8 @@ const DependencyTemplate = require("../DependencyTemplate");
/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {string[]} RawRuntimeRequirements */
class NullDependency extends Dependency { class NullDependency extends Dependency {
get type() { get type() {
return "null"; return "null";

View File

@ -11,11 +11,12 @@ const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
@ -23,7 +24,7 @@ const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** /**
* @param {string[]|null} path the property path array * @param {string[] | null} path the property path array
* @returns {string} the converted path * @returns {string} the converted path
*/ */
const pathToString = (path) => const pathToString = (path) =>
@ -35,7 +36,7 @@ class ProvidedDependency extends ModuleDependency {
/** /**
* @param {string} request request * @param {string} request request
* @param {string} identifier identifier * @param {string} identifier identifier
* @param {string[]} ids ids * @param {ExportInfoName[]} ids ids
* @param {Range} range range * @param {Range} range range
*/ */
constructor(request, identifier, ids, range) { constructor(request, identifier, ids, range) {
@ -58,7 +59,7 @@ class ProvidedDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
const ids = this.ids; const ids = this.ids;
@ -139,7 +140,7 @@ class ProvidedDependencyTemplate extends ModuleDependency.Template {
chunkGraph, chunkGraph,
request: dep.request, request: dep.request,
runtimeRequirements runtimeRequirements
})}${pathToString(/** @type {string[]} */ (usedName))};\n`, })}${pathToString(/** @type {string[] | null} */ (usedName))};\n`,
InitFragment.STAGE_PROVIDES, InitFragment.STAGE_PROVIDES,
1, 1,
`provided ${dep.identifier}` `provided ${dep.identifier}`

View File

@ -11,7 +11,7 @@ const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
@ -32,7 +32,7 @@ class RequireIncludeDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
// This doesn't use any export // This doesn't use any export

View File

@ -10,7 +10,7 @@ const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId"); const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId");
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
@ -40,7 +40,7 @@ class RequireResolveDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
// This doesn't use any export // This doesn't use any export

View File

@ -9,6 +9,7 @@ const makeSerializable = require("../util/makeSerializable");
const NullDependency = require("./NullDependency"); const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("./NullDependency").RawRuntimeRequirements} RawRuntimeRequirements */
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
@ -18,7 +19,7 @@ const NullDependency = require("./NullDependency");
class RuntimeRequirementsDependency extends NullDependency { class RuntimeRequirementsDependency extends NullDependency {
/** /**
* @param {string[]} runtimeRequirements runtime requirements * @param {RawRuntimeRequirements} runtimeRequirements runtime requirements
*/ */
constructor(runtimeRequirements) { constructor(runtimeRequirements) {
super(); super();

View File

@ -13,9 +13,11 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {string[] | true} Exports */
class StaticExportsDependency extends NullDependency { class StaticExportsDependency extends NullDependency {
/** /**
* @param {string[] | true} exports export names * @param {Exports} exports export names
* @param {boolean} canMangle true, if mangling exports names is allowed * @param {boolean} canMangle true, if mangling exports names is allowed
*/ */
constructor(exports, canMangle) { constructor(exports, canMangle) {

View File

@ -9,7 +9,7 @@ const Dependency = require("../Dependency");
const makeSerializable = require("../util/makeSerializable"); const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
@ -44,7 +44,7 @@ class WebAssemblyExportImportedDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return [[this.name]]; return [[this.name]];

View File

@ -10,7 +10,7 @@ const UnsupportedWebAssemblyFeatureError = require("../wasm-sync/UnsupportedWebA
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ /** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../WebpackError")} WebpackError */ /** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
@ -46,7 +46,7 @@ class WebAssemblyImportDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return [[this.name]]; return [[this.name]];

View File

@ -11,7 +11,7 @@ const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency"); const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
@ -33,7 +33,7 @@ class WebpackIsIncludedDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
// This doesn't use any export // This doesn't use any export

View File

@ -12,7 +12,7 @@ const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Entrypoint")} Entrypoint */ /** @typedef {import("../Entrypoint")} Entrypoint */
@ -44,7 +44,7 @@ class WorkerDependency extends ModuleDependency {
* Returns list of exports referenced by this dependency * Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph * @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed * @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {ReferencedExports} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
return Dependency.NO_EXPORTS_REFERENCED; return Dependency.NO_EXPORTS_REFERENCED;

View File

@ -288,8 +288,8 @@ class WorkerPlugin {
} = arg2 && arg2.type === "ObjectExpression" } = arg2 && arg2.type === "ObjectExpression"
? parseObjectExpression(parser, arg2) ? parseObjectExpression(parser, arg2)
: { : {
/** @type {Record<string, Expression | Pattern>} */ expressions:
expressions: {}, /** @type {Record<string, Expression | Pattern>} */ ({}),
otherElements: [], otherElements: [],
/** @type {Values} */ /** @type {Values} */
values: {}, values: {},

View File

@ -7,14 +7,13 @@
const { UsageState } = require("../ExportsInfo"); const { UsageState } = require("../ExportsInfo");
/** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string[][]} ReferencedExports */
/** /**
* @param {RuntimeSpec} runtime the runtime * @param {RuntimeSpec} runtime the runtime
* @param {ReferencedExports} referencedExports list of referenced exports, will be added to * @param {RawReferencedExports} referencedExports list of referenced exports, will be added to
* @param {string[]} prefix export prefix * @param {string[]} prefix export prefix
* @param {ExportInfo=} exportInfo the export info * @param {ExportInfo=} exportInfo the export info
* @param {boolean} defaultPointsToSelf when true, using default will reference itself * @param {boolean} defaultPointsToSelf when true, using default will reference itself

View File

@ -28,6 +28,7 @@ const { registerNotSerializable } = require("../util/serialization");
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -160,7 +161,7 @@ class LazyCompilationProxyModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return `${this.originalModule.libIdent( return `${this.originalModule.libIdent(
@ -344,12 +345,14 @@ class LazyCompilationDependencyFactory extends ModuleFactory {
/** @typedef {BackendHandler | PromiseBackendHandler} BackEnd */ /** @typedef {BackendHandler | PromiseBackendHandler} BackEnd */
/** @typedef {(module: Module) => boolean} TestFn */
/** /**
* @typedef {object} Options options * @typedef {object} Options options
* @property {BackEnd} backend the backend * @property {BackEnd} backend the backend
* @property {boolean=} entries * @property {boolean=} entries
* @property {boolean=} imports * @property {boolean=} imports
* @property {(RegExp | string | ((module: Module) => boolean))=} test additional filter for lazy compiled entrypoint modules * @property {RegExp | string | TestFn=} test additional filter for lazy compiled entrypoint modules
*/ */
const PLUGIN_NAME = "LazyCompilationPlugin"; const PLUGIN_NAME = "LazyCompilationPlugin";

View File

@ -16,6 +16,7 @@
/** @typedef {HttpServer | HttpsServer} Server */ /** @typedef {HttpServer | HttpsServer} Server */
/** @typedef {(server: Server) => void} Listen */ /** @typedef {(server: Server) => void} Listen */
/** @typedef {() => Server} CreateServerFunction */
/** /**
* @param {Omit<LazyCompilationDefaultBackendOptions, "client"> & { client: NonNullable<LazyCompilationDefaultBackendOptions["client"]>}} options additional options for the backend * @param {Omit<LazyCompilationDefaultBackendOptions, "client"> & { client: NonNullable<LazyCompilationDefaultBackendOptions["client"]>}} options additional options for the backend
@ -31,7 +32,7 @@ module.exports = (options) => (compiler, callback) => {
(typeof options.server === "object" && (typeof options.server === "object" &&
("key" in options.server || "pfx" in options.server)); ("key" in options.server || "pfx" in options.server));
/** @type {() => Server} */ /** @type {CreateServerFunction} */
const createServer = const createServer =
typeof options.server === "function" typeof options.server === "function"
? options.server ? options.server

View File

@ -10,6 +10,7 @@ const { getUsedModuleIdsAndModules } = require("./IdHelpers");
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").ModuleId} ModuleId */
/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ /** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */
const plugin = "SyncModuleIdsPlugin"; const plugin = "SyncModuleIdsPlugin";
@ -42,7 +43,7 @@ class SyncModuleIdsPlugin {
* @returns {void} * @returns {void}
*/ */
apply(compiler) { apply(compiler) {
/** @type {Map<string, string | number>} */ /** @type {Map<string, ModuleId>} */
let data; let data;
let dataChanged = false; let dataChanged = false;
if (this._read) { if (this._read) {
@ -70,7 +71,7 @@ class SyncModuleIdsPlugin {
if (this._write) { if (this._write) {
compiler.hooks.emitRecords.tapAsync(plugin, (callback) => { compiler.hooks.emitRecords.tapAsync(plugin, (callback) => {
if (!data || !dataChanged) return callback(); if (!data || !dataChanged) return callback();
/** @type {{[key: string]: string | number}} */ /** @type {{[key: string]: ModuleId}} */
const json = {}; const json = {};
const sorted = [...data].sort(([a], [b]) => (a < b ? -1 : 1)); const sorted = [...data].sort(([a], [b]) => (a < b ? -1 : 1));
for (const [key, value] of sorted) { for (const [key, value] of sorted) {
@ -108,7 +109,7 @@ class SyncModuleIdsPlugin {
err.module = module; err.module = module;
compilation.errors.push(err); compilation.errors.push(err);
} }
chunkGraph.setModuleId(module, /** @type {string | number} */ (id)); chunkGraph.setModuleId(module, /** @type {ModuleId} */ (id));
usedIds.add(idAsString); usedIds.add(idAsString);
} }
}); });

View File

@ -8,6 +8,9 @@
/** @typedef {import("estree").Node} Node */ /** @typedef {import("estree").Node} Node */
/** @typedef {import("./JavascriptParser").Range} Range */ /** @typedef {import("./JavascriptParser").Range} Range */
/** @typedef {import("./JavascriptParser").VariableInfo} VariableInfo */ /** @typedef {import("./JavascriptParser").VariableInfo} VariableInfo */
/** @typedef {import("./JavascriptParser").Members} Members */
/** @typedef {import("./JavascriptParser").MembersOptionals} MembersOptionals */
/** @typedef {import("./JavascriptParser").MemberRanges} MemberRanges */
const TypeUnknown = 0; const TypeUnknown = 0;
const TypeUndefined = 1; const TypeUndefined = 1;
@ -24,6 +27,10 @@ const TypeWrapped = 11;
const TypeTemplateString = 12; const TypeTemplateString = 12;
const TypeBigInt = 13; const TypeBigInt = 13;
/** @typedef {() => Members} GetMembers */
/** @typedef {() => MembersOptionals} GetMembersOptionals */
/** @typedef {() => MemberRanges} GetMemberRanges */
class BasicEvaluatedExpression { class BasicEvaluatedExpression {
constructor() { constructor() {
this.type = TypeUnknown; this.type = TypeUnknown;
@ -67,11 +74,11 @@ class BasicEvaluatedExpression {
this.identifier = undefined; this.identifier = undefined;
/** @type {string | VariableInfo | undefined} */ /** @type {string | VariableInfo | undefined} */
this.rootInfo = undefined; this.rootInfo = undefined;
/** @type {(() => string[]) | undefined} */ /** @type {GetMembers | undefined} */
this.getMembers = undefined; this.getMembers = undefined;
/** @type {(() => boolean[]) | undefined} */ /** @type {GetMembersOptionals | undefined} */
this.getMembersOptionals = undefined; this.getMembersOptionals = undefined;
/** @type {(() => Range[]) | undefined} */ /** @type {GetMemberRanges | undefined} */
this.getMemberRanges = undefined; this.getMemberRanges = undefined;
/** @type {Node | undefined} */ /** @type {Node | undefined} */
this.expression = undefined; this.expression = undefined;
@ -388,9 +395,9 @@ class BasicEvaluatedExpression {
* Set's the value of this expression to a particular identifier and its members. * Set's the value of this expression to a particular identifier and its members.
* @param {string | VariableInfo} identifier identifier to set * @param {string | VariableInfo} identifier identifier to set
* @param {string | VariableInfo} rootInfo root info * @param {string | VariableInfo} rootInfo root info
* @param {() => string[]} getMembers members * @param {GetMembers} getMembers members
* @param {() => boolean[]=} getMembersOptionals optional members * @param {GetMembersOptionals=} getMembersOptionals optional members
* @param {() => Range[]=} getMemberRanges ranges of progressively increasing sub-expressions * @param {GetMemberRanges=} getMemberRanges ranges of progressively increasing sub-expressions
* @returns {this} this * @returns {this} this
*/ */
setIdentifier( setIdentifier(

View File

@ -97,7 +97,7 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
/** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[] }} GetInfoResult */ /** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} GetInfoResult */
/** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */ /** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */
/** @typedef {(ident: string) => void} OnIdentString */ /** @typedef {(ident: string) => void} OnIdentString */
/** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */ /** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */
@ -308,7 +308,7 @@ class VariableInfo {
/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ /** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */
/** @typedef {HarmonySettings | ImportSettings | CommonJsImportSettings | TopLevelSymbol | CompatibilitySettings} KnownTagData */ /** @typedef {HarmonySettings | ImportSettings | CommonJsImportSettings | TopLevelSymbol | CompatibilitySettings} KnownTagData */
/** @typedef {KnownTagData & Record<string, EXPECTED_ANY>} TagData */ /** @typedef {KnownTagData | Record<string, EXPECTED_ANY>} TagData */
/** /**
* @typedef {object} TagInfo * @typedef {object} TagInfo
@ -317,6 +317,11 @@ class VariableInfo {
* @property {TagInfo | undefined} next * @property {TagInfo | undefined} next
*/ */
/** @typedef {string[]} CalleeMembers */
/** @typedef {string[]} Members */
/** @typedef {boolean[]} MembersOptionals */
/** @typedef {Range[]} MemberRanges */
const SCOPE_INFO_TERMINATED_RETURN = 1; const SCOPE_INFO_TERMINATED_RETURN = 1;
const SCOPE_INFO_TERMINATED_THROW = 2; const SCOPE_INFO_TERMINATED_THROW = 2;
@ -366,7 +371,7 @@ const joinRanges = (startRange, endRange) => {
* Helper function used to generate a string representation of a * Helper function used to generate a string representation of a
* [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression). * [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression).
* @param {string} object object to name * @param {string} object object to name
* @param {string[]} membersReversed reversed list of members * @param {Members} membersReversed reversed list of members
* @returns {string} member expression as a string * @returns {string} member expression as a string
* @example * @example
* ```js * ```js
@ -539,7 +544,7 @@ class JavascriptParser extends Parser {
rename: new HookMap(() => new SyncBailHook(["initExpression"])), rename: new HookMap(() => new SyncBailHook(["initExpression"])),
/** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */
assign: new HookMap(() => new SyncBailHook(["expression"])), assign: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[AssignmentExpression, string[]], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[AssignmentExpression, Members], boolean | void>>} */
assignMemberChain: new HookMap( assignMemberChain: new HookMap(
() => new SyncBailHook(["expression", "members"]) () => new SyncBailHook(["expression", "members"])
), ),
@ -552,7 +557,7 @@ class JavascriptParser extends Parser {
/** @type {HookMap<SyncBailHook<[CallExpression], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[CallExpression], boolean | void>>} */
call: new HookMap(() => new SyncBailHook(["expression"])), call: new HookMap(() => new SyncBailHook(["expression"])),
/** Something like "a.b()" */ /** Something like "a.b()" */
/** @type {HookMap<SyncBailHook<[CallExpression, string[], boolean[], Range[]], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[CallExpression, Members, MembersOptionals, MemberRanges], boolean | void>>} */
callMemberChain: new HookMap( callMemberChain: new HookMap(
() => () =>
new SyncBailHook([ new SyncBailHook([
@ -563,7 +568,7 @@ class JavascriptParser extends Parser {
]) ])
), ),
/** Something like "a.b().c.d" */ /** Something like "a.b().c.d" */
/** @type {HookMap<SyncBailHook<[Expression, string[], CallExpression, string[], Range[]], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[Expression, CalleeMembers, CallExpression, Members, MemberRanges], boolean | void>>} */
memberChainOfCallMemberChain: new HookMap( memberChainOfCallMemberChain: new HookMap(
() => () =>
new SyncBailHook([ new SyncBailHook([
@ -575,7 +580,7 @@ class JavascriptParser extends Parser {
]) ])
), ),
/** Something like "a.b().c.d()"" */ /** Something like "a.b().c.d()"" */
/** @type {HookMap<SyncBailHook<[CallExpression, string[], CallExpression, string[], Range[]], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[CallExpression, CalleeMembers, CallExpression, Members, MemberRanges], boolean | void>>} */
callMemberChainOfCallMemberChain: new HookMap( callMemberChainOfCallMemberChain: new HookMap(
() => () =>
new SyncBailHook([ new SyncBailHook([
@ -594,7 +599,7 @@ class JavascriptParser extends Parser {
binaryExpression: new SyncBailHook(["binaryExpression"]), binaryExpression: new SyncBailHook(["binaryExpression"]),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
expression: new HookMap(() => new SyncBailHook(["expression"])), expression: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[MemberExpression, string[], boolean[], Range[]], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[MemberExpression, Members, MembersOptionals, MemberRanges], boolean | void>>} */
expressionMemberChain: new HookMap( expressionMemberChain: new HookMap(
() => () =>
new SyncBailHook([ new SyncBailHook([
@ -604,7 +609,7 @@ class JavascriptParser extends Parser {
"memberRanges" "memberRanges"
]) ])
), ),
/** @type {HookMap<SyncBailHook<[MemberExpression, string[]], boolean | void>>} */ /** @type {HookMap<SyncBailHook<[MemberExpression, Members], boolean | void>>} */
unhandledExpressionMemberChain: new HookMap( unhandledExpressionMemberChain: new HookMap(
() => new SyncBailHook(["expression", "members"]) () => new SyncBailHook(["expression", "members"])
), ),
@ -3949,7 +3954,7 @@ class JavascriptParser extends Parser {
* @param {MemberExpression} expression member expression * @param {MemberExpression} expression member expression
* @param {string} name name * @param {string} name name
* @param {string | VariableInfo} rootInfo root info * @param {string | VariableInfo} rootInfo root info
* @param {string[]} members members * @param {Members} members members
* @param {() => R | undefined} onUnhandled on unhandled callback * @param {() => R | undefined} onUnhandled on unhandled callback
*/ */
walkMemberExpressionWithExpressionName( walkMemberExpressionWithExpressionName(
@ -4031,7 +4036,7 @@ class JavascriptParser extends Parser {
* @template R * @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {Expression | Super} expr expression info * @param {Expression | Super} expr expression info
* @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => R) | undefined} fallback callback when variable in not handled by hooks * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => Members) => R) | undefined} fallback callback when variable in not handled by hooks
* @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook * @param {AsArray<T>} args args for the hook
* @returns {R | undefined} result of hook * @returns {R | undefined} result of hook
@ -4964,7 +4969,7 @@ class JavascriptParser extends Parser {
/** /**
* @param {string} name variable name * @param {string} name variable name
* @returns {string | ExportedVariableInfo} info for this variable * @returns {ExportedVariableInfo} info for this variable
*/ */
getVariableInfo(name) { getVariableInfo(name) {
const value = this.scope.definitions.get(name); const value = this.scope.definitions.get(name);
@ -4976,7 +4981,7 @@ class JavascriptParser extends Parser {
/** /**
* @param {string} name variable name * @param {string} name variable name
* @param {string | ExportedVariableInfo} variableInfo new info for this variable * @param {ExportedVariableInfo} variableInfo new info for this variable
* @returns {void} * @returns {void}
*/ */
setVariable(name, variableInfo) { setVariable(name, variableInfo) {
@ -5057,7 +5062,7 @@ class JavascriptParser extends Parser {
/** /**
* @param {Expression | Super} expression a member expression * @param {Expression | Super} expression a member expression
* @returns {{ members: string[], object: Expression | Super, membersOptionals: boolean[], memberRanges: Range[] }} member names (reverse order) and remaining object * @returns {{ members: Members, object: Expression | Super, membersOptionals: MembersOptionals, memberRanges: MemberRanges }} member names (reverse order) and remaining object
*/ */
extractMemberExpressionChain(expression) { extractMemberExpressionChain(expression) {
/** @type {Node} */ /** @type {Node} */
@ -5123,8 +5128,8 @@ class JavascriptParser extends Parser {
return { info, name }; return { info, name };
} }
/** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} CallExpressionInfo */ /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => CalleeMembers, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges}} CallExpressionInfo */
/** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} ExpressionExpressionInfo */ /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges}} ExpressionExpressionInfo */
/** /**
* @param {Expression | Super} expression a member expression * @param {Expression | Super} expression a member expression
@ -5185,7 +5190,7 @@ class JavascriptParser extends Parser {
/** /**
* @param {Expression} expression an expression * @param {Expression} expression an expression
* @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]} | undefined} name info * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => Members} | undefined} name info
*/ */
getNameForExpression(expression) { getNameForExpression(expression) {
return this.getMemberExpressionInfo( return this.getMemberExpressionInfo(

View File

@ -13,6 +13,7 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
/** @typedef {import("estree").SourceLocation} SourceLocation */ /** @typedef {import("estree").SourceLocation} SourceLocation */
/** @typedef {import("./JavascriptParser")} JavascriptParser */ /** @typedef {import("./JavascriptParser")} JavascriptParser */
/** @typedef {import("./JavascriptParser").Range} Range */ /** @typedef {import("./JavascriptParser").Range} Range */
/** @typedef {import("./BasicEvaluatedExpression").GetMembers} GetMembers */
module.exports.approve = () => true; module.exports.approve = () => true;
@ -30,7 +31,7 @@ module.exports.evaluateToBoolean = (value) =>
/** /**
* @param {string} identifier identifier * @param {string} identifier identifier
* @param {string} rootInfo rootInfo * @param {string} rootInfo rootInfo
* @param {() => string[]} getMembers getMembers * @param {GetMembers} getMembers getMembers
* @param {boolean | null=} truthy is truthy, null if nullish * @param {boolean | null=} truthy is truthy, null if nullish
* @returns {(expression: Expression) => BasicEvaluatedExpression} callback * @returns {(expression: Expression) => BasicEvaluatedExpression} callback
*/ */

View File

@ -17,6 +17,8 @@ const JsonData = require("./JsonData");
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {import("../util/fs").JsonValue} JsonValue */ /** @typedef {import("../util/fs").JsonValue} JsonValue */
/** @typedef {(input: string) => Buffer | JsonValue} ParseFn */
const getParseJson = memoize(() => require("json-parse-even-better-errors")); const getParseJson = memoize(() => require("json-parse-even-better-errors"));
class JsonParser extends Parser { class JsonParser extends Parser {
@ -38,7 +40,7 @@ class JsonParser extends Parser {
source = source.toString("utf8"); source = source.toString("utf8");
} }
/** @type {NonNullable<JsonModulesPluginParserOptions["parse"]>} */ /** @type {ParseFn} */
const parseFn = const parseFn =
typeof this.options.parse === "function" typeof this.options.parse === "function"
? this.options.parse ? this.options.parse

View File

@ -16,15 +16,21 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */
/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
/** @typedef {import("../util/Hash")} Hash */ /** @typedef {import("../util/Hash")} Hash */
/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */
/**
* @template T
* @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T>
*/
const KEYWORD_REGEX = const KEYWORD_REGEX =
/^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/;
@ -90,19 +96,23 @@ const accessWithInit = (accessor, existingLength, initLast = false) => {
return current; return current;
}; };
/** @typedef {string[] | "global"} LibraryPrefix */
/** /**
* @typedef {object} AssignLibraryPluginOptions * @typedef {object} AssignLibraryPluginOptions
* @property {LibraryType} type * @property {LibraryType} type
* @property {string[] | "global"} prefix name prefix * @property {LibraryPrefix} prefix name prefix
* @property {string | false} declare declare name as variable * @property {string | false} declare declare name as variable
* @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name * @property {"error" | "static" | "copy" | "assign"} unnamed behavior for unnamed library name
* @property {"copy"|"assign"=} named behavior for named library name * @property {"copy" | "assign"=} named behavior for named library name
*/ */
/** @typedef {string | string[]} LibraryName */
/** /**
* @typedef {object} AssignLibraryPluginParsed * @typedef {object} AssignLibraryPluginParsed
* @property {string | string[]} name * @property {LibraryName} name
* @property {string | string[] | undefined} export * @property {LibraryExport=} export
*/ */
/** /**
@ -141,7 +151,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
`Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
); );
} }
const _name = /** @type {string | string[]} */ (name); const _name = /** @type {LibraryName} */ (name);
return { return {
name: _name, name: _name,
export: library.export export: library.export
@ -176,7 +186,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
/** /**
* @param {Compilation} compilation the compilation * @param {Compilation} compilation the compilation
* @returns {string[]} the prefix * @returns {LibraryPrefix} the prefix
*/ */
_getPrefix(compilation) { _getPrefix(compilation) {
return this.prefix === "global" return this.prefix === "global"
@ -197,7 +207,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
...prefix, ...prefix,
...(Array.isArray(options.name) ? options.name : [options.name]) ...(Array.isArray(options.name) ? options.name : [options.name])
] ]
: prefix; : /** @type {string[]} */ (prefix);
return fullName.map((n) => return fullName.map((n) =>
compilation.getPath(n, { compilation.getPath(n, {
chunk chunk
@ -312,7 +322,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
true true
); );
/** @type {string[]} */ /** @type {ExportInfoName[]} */
const provided = []; const provided = [];
for (const exportInfo of exportsInfo.orderedExports) { for (const exportInfo of exportsInfo.orderedExports) {
if (!exportInfo.provided) continue; if (!exportInfo.provided) continue;

View File

@ -15,6 +15,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */
/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
@ -23,7 +24,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** /**
* @typedef {object} ExportPropertyLibraryPluginParsed * @typedef {object} ExportPropertyLibraryPluginParsed
* @property {string | string[]} export * @property {LibraryExport=} export
*/ */
/** /**
@ -51,7 +52,7 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
*/ */
parseOptions(library) { parseOptions(library) {
return { return {
export: /** @type {string | string[]} */ (library.export) export: library.export
}; };
} }

View File

@ -17,6 +17,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */
/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
@ -37,7 +38,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** /**
* @typedef {object} ModuleLibraryPluginParsed * @typedef {object} ModuleLibraryPluginParsed
* @property {string} name * @property {string} name
* @property {string | string[]=} export * @property {LibraryExport=} export
*/ */
const PLUGIN_NAME = "ModuleLibraryPlugin"; const PLUGIN_NAME = "ModuleLibraryPlugin";

View File

@ -31,9 +31,11 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
const accessorToObjectAccess = (accessor) => const accessorToObjectAccess = (accessor) =>
accessor.map((a) => `[${JSON.stringify(a)}]`).join(""); accessor.map((a) => `[${JSON.stringify(a)}]`).join("");
/** @typedef {string | string[]} Accessor */
/** /**
* @param {string|undefined} base the path prefix * @param {string|undefined} base the path prefix
* @param {string|string[]} accessor the accessor * @param {Accessor} accessor the accessor
* @param {string=} joinWith the element separator * @param {string=} joinWith the element separator
* @returns {string} the path * @returns {string} the path
*/ */
@ -53,8 +55,6 @@ const accessorAccess = (base, accessor, joinWith = ", ") => {
.join(joinWith); .join(joinWith);
}; };
/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */
/** /**
* @typedef {object} UmdLibraryPluginOptions * @typedef {object} UmdLibraryPluginOptions
* @property {LibraryType} type * @property {LibraryType} type
@ -192,10 +192,9 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin {
/** @type {RequestRecord} */ /** @type {RequestRecord} */
(request).root; (request).root;
} }
return `root${accessorToObjectAccess( return `root${accessorToObjectAccess([
/** @type {string[]} */ ...(Array.isArray(request) ? request : [request])
([...(Array.isArray(request) ? request : [request])]) ])}`;
)}`;
}) })
.join(", ") .join(", ")
); );
@ -248,17 +247,14 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin {
.join(", "); .join(", ");
/** /**
* @param {string| string[]} library library name * @param {Accessor} library library name
* @returns {string} stringified library name * @returns {string} stringified library name
*/ */
const libraryName = (library) => const libraryName = (library) =>
JSON.stringify( JSON.stringify(
replaceKeys( replaceKeys(
/** @type {string} */ /** @type {string} */
( ([...(Array.isArray(library) ? library : [library])].pop())
/** @type {string[]} */
([...(Array.isArray(library) ? library : [library])]).pop()
)
) )
); );
@ -322,7 +318,7 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin {
"commonjs" "commonjs"
)} else if(typeof exports === 'object')\n` + )} else if(typeof exports === 'object')\n` +
` exports[${libraryName( ` exports[${libraryName(
/** @type {string | string[]} */ /** @type {Accessor} */
(names.commonjs || names.root) (names.commonjs || names.root)
)}] = factory(${externalsRequireArray( )}] = factory(${externalsRequireArray(
"commonjs" "commonjs"
@ -330,7 +326,7 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin {
` ${replaceKeys( ` ${replaceKeys(
accessorAccess( accessorAccess(
"root", "root",
/** @type {string | string[]} */ /** @type {Accessor} */
(names.root || names.commonjs) (names.root || names.commonjs)
) )
)} = factory(${externalsRootArray(externals)});\n` )} = factory(${externalsRootArray(externals)});\n`

View File

@ -35,9 +35,11 @@ const LOG_SYMBOL = Symbol("webpack logger raw log method");
const TIMERS_SYMBOL = Symbol("webpack logger times"); const TIMERS_SYMBOL = Symbol("webpack logger times");
const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times");
/** @typedef {EXPECTED_ANY[]} Args */
class WebpackLogger { class WebpackLogger {
/** /**
* @param {(type: LogTypeEnum, args?: EXPECTED_ANY[]) => void} log log function * @param {(type: LogTypeEnum, args?: Args) => void} log log function
* @param {(name: string | (() => string)) => WebpackLogger} getChildLogger function to create child logger * @param {(name: string | (() => string)) => WebpackLogger} getChildLogger function to create child logger
*/ */
constructor(log, getChildLogger) { constructor(log, getChildLogger) {
@ -46,35 +48,35 @@ class WebpackLogger {
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
error(...args) { error(...args) {
this[LOG_SYMBOL](LogType.error, args); this[LOG_SYMBOL](LogType.error, args);
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
warn(...args) { warn(...args) {
this[LOG_SYMBOL](LogType.warn, args); this[LOG_SYMBOL](LogType.warn, args);
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
info(...args) { info(...args) {
this[LOG_SYMBOL](LogType.info, args); this[LOG_SYMBOL](LogType.info, args);
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
log(...args) { log(...args) {
this[LOG_SYMBOL](LogType.log, args); this[LOG_SYMBOL](LogType.log, args);
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
debug(...args) { debug(...args) {
this[LOG_SYMBOL](LogType.debug, args); this[LOG_SYMBOL](LogType.debug, args);
@ -82,7 +84,7 @@ class WebpackLogger {
/** /**
* @param {EXPECTED_ANY} assertion assertion * @param {EXPECTED_ANY} assertion assertion
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
assert(assertion, ...args) { assert(assertion, ...args) {
if (!assertion) { if (!assertion) {
@ -99,21 +101,21 @@ class WebpackLogger {
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
status(...args) { status(...args) {
this[LOG_SYMBOL](LogType.status, args); this[LOG_SYMBOL](LogType.status, args);
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
group(...args) { group(...args) {
this[LOG_SYMBOL](LogType.group, args); this[LOG_SYMBOL](LogType.group, args);
} }
/** /**
* @param {...EXPECTED_ANY} args args * @param {Args} args args
*/ */
groupCollapsed(...args) { groupCollapsed(...args) {
this[LOG_SYMBOL](LogType.groupCollapsed, args); this[LOG_SYMBOL](LogType.groupCollapsed, args);

View File

@ -10,26 +10,27 @@ const { LogType } = require("./Logger");
/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ /** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */
/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ /** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */
/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ /** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */
/** @typedef {import("./Logger").Args} Args */
/** @typedef {(item: string) => boolean} FilterFunction */ /** @typedef {(item: string) => boolean} FilterFunction */
/** @typedef {(value: string, type: LogTypeEnum, args?: EXPECTED_ANY[]) => void} LoggingFunction */ /** @typedef {(value: string, type: LogTypeEnum, args?: Args) => void} LoggingFunction */
/** /**
* @typedef {object} LoggerConsole * @typedef {object} LoggerConsole
* @property {() => void} clear * @property {() => void} clear
* @property {() => void} trace * @property {() => void} trace
* @property {(...args: EXPECTED_ANY[]) => void} info * @property {(...args: Args) => void} info
* @property {(...args: EXPECTED_ANY[]) => void} log * @property {(...args: Args) => void} log
* @property {(...args: EXPECTED_ANY[]) => void} warn * @property {(...args: Args) => void} warn
* @property {(...args: EXPECTED_ANY[]) => void} error * @property {(...args: Args) => void} error
* @property {(...args: EXPECTED_ANY[]) => void=} debug * @property {(...args: Args) => void=} debug
* @property {(...args: EXPECTED_ANY[]) => void=} group * @property {(...args: Args) => void=} group
* @property {(...args: EXPECTED_ANY[]) => void=} groupCollapsed * @property {(...args: Args) => void=} groupCollapsed
* @property {(...args: EXPECTED_ANY[]) => void=} groupEnd * @property {(...args: Args) => void=} groupEnd
* @property {(...args: EXPECTED_ANY[]) => void=} status * @property {(...args: Args) => void=} status
* @property {(...args: EXPECTED_ANY[]) => void=} profile * @property {(...args: Args) => void=} profile
* @property {(...args: EXPECTED_ANY[]) => void=} profileEnd * @property {(...args: Args) => void=} profileEnd
* @property {(...args: EXPECTED_ANY[]) => void=} logTime * @property {(...args: Args) => void=} logTime
*/ */
/** /**
@ -94,7 +95,7 @@ module.exports = ({ level = "info", debug = false, console }) => {
/** /**
* @param {string} name name of the logger * @param {string} name name of the logger
* @param {LogTypeEnum} type type of the log entry * @param {LogTypeEnum} type type of the log entry
* @param {EXPECTED_ANY[]=} args arguments of the log entry * @param {Args=} args arguments of the log entry
* @returns {void} * @returns {void}
*/ */
const logger = (name, type, args) => { const logger = (name, type, args) => {

View File

@ -71,6 +71,8 @@ const {
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -102,27 +104,23 @@ const {
// fix eslint-scope to support class properties correctly // fix eslint-scope to support class properties correctly
// cspell:word Referencer // cspell:word Referencer
const ReferencerClass = /** @type {EXPECTED_ANY} */ (Referencer); const ReferencerClass = Referencer;
if (!ReferencerClass.prototype.PropertyDefinition) { if (!ReferencerClass.prototype.PropertyDefinition) {
ReferencerClass.prototype.PropertyDefinition = ReferencerClass.prototype.PropertyDefinition =
ReferencerClass.prototype.Property; ReferencerClass.prototype.Property;
} }
/**
* @typedef {object} ReexportInfo
* @property {Module} module
* @property {string[]} export
*/
/** @typedef {RawBinding | SymbolBinding} Binding */ /** @typedef {RawBinding | SymbolBinding} Binding */
/** @typedef {string[]} ExportName */
/** /**
* @typedef {object} RawBinding * @typedef {object} RawBinding
* @property {ModuleInfo} info * @property {ModuleInfo} info
* @property {string} rawName * @property {string} rawName
* @property {string=} comment * @property {string=} comment
* @property {string[]} ids * @property {ExportName} ids
* @property {string[]} exportName * @property {ExportName} exportName
*/ */
/** /**
@ -130,8 +128,8 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
* @property {ConcatenatedModuleInfo} info * @property {ConcatenatedModuleInfo} info
* @property {string} name * @property {string} name
* @property {string=} comment * @property {string=} comment
* @property {string[]} ids * @property {ExportName} ids
* @property {string[]} exportName * @property {ExportName} exportName
*/ */
/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */
@ -269,7 +267,7 @@ const joinIterableWithComma = (iterable) => {
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @param {ModuleInfo} info module info * @param {ModuleInfo} info module info
* @param {string[]} exportName exportName * @param {ExportName} exportName exportName
* @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap * @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap
* @param {RuntimeSpec} runtime for which runtime * @param {RuntimeSpec} runtime for which runtime
* @param {RequestShortener} requestShortener the request shortener * @param {RequestShortener} requestShortener the request shortener
@ -478,7 +476,7 @@ const getFinalBinding = (
} }
const directExport = info.exportMap && info.exportMap.get(exportId); const directExport = info.exportMap && info.exportMap.get(exportId);
if (directExport) { if (directExport) {
const usedName = /** @type {string[]} */ ( const usedName = /** @type {ExportName} */ (
exportsInfo.getUsedName(exportName, runtime) exportsInfo.getUsedName(exportName, runtime)
); );
if (!usedName) { if (!usedName) {
@ -541,7 +539,7 @@ const getFinalBinding = (
); );
} }
if (info.namespaceExportSymbol) { if (info.namespaceExportSymbol) {
const usedName = /** @type {string[]} */ ( const usedName = /** @type {ExportName} */ (
exportsInfo.getUsedName(exportName, runtime) exportsInfo.getUsedName(exportName, runtime)
); );
return { return {
@ -559,7 +557,7 @@ const getFinalBinding = (
} }
case "external": { case "external": {
const used = /** @type {string[]} */ ( const used = /** @type {ExportName} */ (
exportsInfo.getUsedName(exportName, runtime) exportsInfo.getUsedName(exportName, runtime)
); );
if (!used) { if (!used) {
@ -589,7 +587,7 @@ const getFinalBinding = (
/** /**
* @param {ModuleGraph} moduleGraph the module graph * @param {ModuleGraph} moduleGraph the module graph
* @param {ModuleInfo} info module info * @param {ModuleInfo} info module info
* @param {string[]} exportName exportName * @param {ExportName} exportName exportName
* @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap * @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap
* @param {RuntimeSpec} runtime for which runtime * @param {RuntimeSpec} runtime for which runtime
* @param {RequestShortener} requestShortener the request shortener * @param {RequestShortener} requestShortener the request shortener
@ -795,14 +793,14 @@ class ConcatenatedModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return this.rootModule.libIdent(options); return this.rootModule.libIdent(options);
} }
/** /**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path) * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
*/ */
nameForCondition() { nameForCondition() {
return this.rootModule.nameForCondition(); return this.rootModule.nameForCondition();

View File

@ -36,11 +36,7 @@ const formatLocation = require("../formatLocation");
* @property {boolean} checked if the export is conditional * @property {boolean} checked if the export is conditional
*/ */
/** /** @typedef {string | boolean | string[] | undefined} SideEffectsFlagValue */
* @typedef {object} ReexportInfo
* @property {Map<string, ExportInModule[]>} static
* @property {Map<Module, Set<string>>} dynamic
*/
/** @typedef {Map<string, RegExp>} CacheItem */ /** @typedef {Map<string, RegExp>} CacheItem */
@ -104,9 +100,7 @@ class SideEffectsFlagPlugin {
} }
const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects(
resolveData.relativePath, resolveData.relativePath,
/** @type {string | boolean | string[] | undefined} */ ( /** @type {SideEffectsFlagValue} */ (sideEffects),
sideEffects
),
/** @type {CacheItem} */ (cache) /** @type {CacheItem} */ (cache)
); );
module.factoryMeta.sideEffectFree = !hasSideEffects; module.factoryMeta.sideEffectFree = !hasSideEffects;
@ -396,7 +390,7 @@ class SideEffectsFlagPlugin {
/** /**
* @param {string} moduleName the module name * @param {string} moduleName the module name
* @param {undefined | boolean | string | string[]} flagValue the flag value * @param {SideEffectsFlagValue} flagValue the flag value
* @param {Map<string, RegExp>} cache cache for glob to regexp * @param {Map<string, RegExp>} cache cache for glob to regexp
* @returns {boolean | undefined} true, when the module has side effects, undefined or false when not * @returns {boolean | undefined} true, when the module has side effects, undefined or false when not
*/ */

View File

@ -36,10 +36,8 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
/** @typedef {import("../util/deterministicGrouping").GroupedItems<Module>} DeterministicGroupingGroupedItemsForModule */ /** @typedef {import("../util/deterministicGrouping").GroupedItems<Module>} DeterministicGroupingGroupedItemsForModule */
/** @typedef {import("../util/deterministicGrouping").Options<Module>} DeterministicGroupingOptionsForModule */ /** @typedef {import("../util/deterministicGrouping").Options<Module>} DeterministicGroupingOptionsForModule */
/** @typedef {Record<string, number>} SplitChunksSizes */
/** /**
* @callback ChunkFilterFunction * @callback ChunkFilterFn
* @param {Chunk} chunk * @param {Chunk} chunk
* @returns {boolean | undefined} * @returns {boolean | undefined}
*/ */
@ -51,12 +49,17 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
* @returns {number} * @returns {number}
*/ */
/** @typedef {string} SourceType */
/** @typedef {SourceType[]} SourceTypes */
/** @typedef {SourceType[]} DefaultSizeTypes */
/** @typedef {Record<SourceType, number>} SplitChunksSizes */
/** /**
* @typedef {object} CacheGroupSource * @typedef {object} CacheGroupSource
* @property {string} key * @property {string} key
* @property {number=} priority * @property {number=} priority
* @property {GetName=} getName * @property {GetNameFn=} getName
* @property {ChunkFilterFunction=} chunksFilter * @property {ChunkFilterFn=} chunksFilter
* @property {boolean=} enforce * @property {boolean=} enforce
* @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSize
* @property {SplitChunksSizes} minSizeReduction * @property {SplitChunksSizes} minSizeReduction
@ -78,8 +81,8 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
* @typedef {object} CacheGroup * @typedef {object} CacheGroup
* @property {string} key * @property {string} key
* @property {number} priority * @property {number} priority
* @property {GetName=} getName * @property {GetNameFn=} getName
* @property {ChunkFilterFunction} chunksFilter * @property {ChunkFilterFn} chunksFilter
* @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSize
* @property {SplitChunksSizes} minSizeReduction * @property {SplitChunksSizes} minSizeReduction
* @property {SplitChunksSizes} minRemainingSize * @property {SplitChunksSizes} minRemainingSize
@ -102,7 +105,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
/** /**
* @typedef {object} FallbackCacheGroup * @typedef {object} FallbackCacheGroup
* @property {ChunkFilterFunction} chunksFilter * @property {ChunkFilterFn} chunksFilter
* @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSize
* @property {SplitChunksSizes} maxAsyncSize * @property {SplitChunksSizes} maxAsyncSize
* @property {SplitChunksSizes} maxInitialSize * @property {SplitChunksSizes} maxInitialSize
@ -123,17 +126,17 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
*/ */
/** /**
* @callback GetName * @callback GetNameFn
* @param {Module} module * @param {Module} module
* @param {Chunk[]} chunks * @param {Chunk[]} chunks
* @param {string} key * @param {string} key
* @returns {string=} * @returns {string | undefined}
*/ */
/** /**
* @typedef {object} SplitChunksOptions * @typedef {object} SplitChunksOptions
* @property {ChunkFilterFunction} chunksFilter * @property {ChunkFilterFn} chunksFilter
* @property {string[]} defaultSizeTypes * @property {DefaultSizeTypes} defaultSizeTypes
* @property {SplitChunksSizes} minSize * @property {SplitChunksSizes} minSize
* @property {SplitChunksSizes} minSizeReduction * @property {SplitChunksSizes} minSizeReduction
* @property {SplitChunksSizes} minRemainingSize * @property {SplitChunksSizes} minRemainingSize
@ -147,7 +150,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
* @property {TemplatePath=} filename * @property {TemplatePath=} filename
* @property {string} automaticNameDelimiter * @property {string} automaticNameDelimiter
* @property {GetCacheGroups} getCacheGroups * @property {GetCacheGroups} getCacheGroups
* @property {GetName} getName * @property {GetNameFn} getName
* @property {boolean} usedExports * @property {boolean} usedExports
* @property {FallbackCacheGroup} fallbackCacheGroup * @property {FallbackCacheGroup} fallbackCacheGroup
*/ */
@ -158,13 +161,13 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
* @property {CacheGroup} cacheGroup * @property {CacheGroup} cacheGroup
* @property {number} cacheGroupIndex * @property {number} cacheGroupIndex
* @property {string=} name * @property {string=} name
* @property {Record<string, number>} sizes * @property {Record<SourceType, number>} sizes
* @property {Set<Chunk>} chunks * @property {Set<Chunk>} chunks
* @property {Set<Chunk>} reusableChunks * @property {Set<Chunk>} reusableChunks
* @property {Set<bigint | Chunk>} chunksKeys * @property {Set<bigint | Chunk>} chunksKeys
*/ */
/** @type {GetName} */ /** @type {GetNameFn} */
const defaultGetName = () => undefined; const defaultGetName = () => undefined;
const deterministicGroupingForModules = const deterministicGroupingForModules =
@ -285,7 +288,7 @@ const ALL_CHUNK_FILTER = (_chunk) => true;
/** /**
* @param {OptimizationSplitChunksSizes | undefined} value the sizes * @param {OptimizationSplitChunksSizes | undefined} value the sizes
* @param {string[]} defaultSizeTypes the default size types * @param {DefaultSizeTypes} defaultSizeTypes the default size types
* @returns {SplitChunksSizes} normalized representation * @returns {SplitChunksSizes} normalized representation
*/ */
const normalizeSizes = (value, defaultSizeTypes) => { const normalizeSizes = (value, defaultSizeTypes) => {
@ -378,7 +381,7 @@ const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => {
/** /**
* @param {SplitChunksSizes} sizes the sizes * @param {SplitChunksSizes} sizes the sizes
* @param {SplitChunksSizes} minSize the min sizes * @param {SplitChunksSizes} minSize the min sizes
* @returns {undefined | string[]} list of size types that are below min size * @returns {undefined | SourceTypes} list of size types that are below min size
*/ */
const getViolatingMinSizes = (sizes, minSize) => { const getViolatingMinSizes = (sizes, minSize) => {
let list; let list;
@ -407,20 +410,20 @@ const totalSize = (sizes) => {
/** /**
* @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name * @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name
* @returns {GetName | undefined} a function to get the name of the chunk * @returns {GetNameFn | undefined} a function to get the name of the chunk
*/ */
const normalizeName = (name) => { const normalizeName = (name) => {
if (typeof name === "string") { if (typeof name === "string") {
return () => name; return () => name;
} }
if (typeof name === "function") { if (typeof name === "function") {
return /** @type {GetName} */ (name); return /** @type {GetNameFn} */ (name);
} }
}; };
/** /**
* @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option
* @returns {ChunkFilterFunction | undefined} the chunk filter function * @returns {ChunkFilterFn | undefined} the chunk filter function
*/ */
const normalizeChunksFilter = (chunks) => { const normalizeChunksFilter = (chunks) => {
if (chunks === "initial") { if (chunks === "initial") {
@ -442,7 +445,7 @@ const normalizeChunksFilter = (chunks) => {
/** /**
* @param {undefined | GetCacheGroups | Record<string, false | string | RegExp | OptimizationSplitChunksGetCacheGroups | OptimizationSplitChunksCacheGroup>} cacheGroups the cache group options * @param {undefined | GetCacheGroups | Record<string, false | string | RegExp | OptimizationSplitChunksGetCacheGroups | OptimizationSplitChunksCacheGroup>} cacheGroups the cache group options
* @param {string[]} defaultSizeTypes the default size types * @param {DefaultSizeTypes} defaultSizeTypes the default size types
* @returns {GetCacheGroups} a function to get the cache groups * @returns {GetCacheGroups} a function to get the cache groups
*/ */
const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => {
@ -585,7 +588,7 @@ const checkModuleLayer = (test, module) => {
/** /**
* @param {OptimizationSplitChunksCacheGroup} options the group options * @param {OptimizationSplitChunksCacheGroup} options the group options
* @param {string} key key of cache group * @param {string} key key of cache group
* @param {string[]} defaultSizeTypes the default size types * @param {DefaultSizeTypes} defaultSizeTypes the default size types
* @returns {CacheGroupSource} the normalized cached group * @returns {CacheGroupSource} the normalized cached group
*/ */
const createCacheGroupSource = (options, key, defaultSizeTypes) => { const createCacheGroupSource = (options, key, defaultSizeTypes) => {
@ -652,7 +655,7 @@ module.exports = class SplitChunksPlugin {
/** @type {SplitChunksOptions} */ /** @type {SplitChunksOptions} */
this.options = { this.options = {
chunksFilter: chunksFilter:
/** @type {ChunkFilterFunction} */ /** @type {ChunkFilterFn} */
(normalizeChunksFilter(options.chunks || "all")), (normalizeChunksFilter(options.chunks || "all")),
defaultSizeTypes, defaultSizeTypes,
minSize, minSize,
@ -683,13 +686,13 @@ module.exports = class SplitChunksPlugin {
defaultSizeTypes defaultSizeTypes
), ),
getName: options.name getName: options.name
? /** @type {GetName} */ (normalizeName(options.name)) ? /** @type {GetNameFn} */ (normalizeName(options.name))
: defaultGetName, : defaultGetName,
automaticNameDelimiter: options.automaticNameDelimiter || "-", automaticNameDelimiter: options.automaticNameDelimiter || "-",
usedExports: options.usedExports || false, usedExports: options.usedExports || false,
fallbackCacheGroup: { fallbackCacheGroup: {
chunksFilter: chunksFilter:
/** @type {ChunkFilterFunction} */ /** @type {ChunkFilterFn} */
( (
normalizeChunksFilter( normalizeChunksFilter(
fallbackCacheGroup.chunks || options.chunks || "all" fallbackCacheGroup.chunks || options.chunks || "all"
@ -1067,14 +1070,14 @@ module.exports = class SplitChunksPlugin {
* @property {bigint | Chunk} key a key of the list * @property {bigint | Chunk} key a key of the list
*/ */
/** @type {WeakMap<Set<Chunk> | Chunk, WeakMap<ChunkFilterFunction, SelectedChunksResult>>} */ /** @type {WeakMap<Set<Chunk> | Chunk, WeakMap<ChunkFilterFn, SelectedChunksResult>>} */
const selectedChunksCacheByChunksSet = new WeakMap(); const selectedChunksCacheByChunksSet = new WeakMap();
/** /**
* get list and key by applying the filter function to the list * get list and key by applying the filter function to the list
* It is cached for performance reasons * It is cached for performance reasons
* @param {Set<Chunk> | Chunk} chunks list of chunks * @param {Set<Chunk> | Chunk} chunks list of chunks
* @param {ChunkFilterFunction} chunkFilter filter function for chunks * @param {ChunkFilterFn} chunkFilter filter function for chunks
* @returns {SelectedChunksResult} list and key * @returns {SelectedChunksResult} list and key
*/ */
const getSelectedChunks = (chunks, chunkFilter) => { const getSelectedChunks = (chunks, chunkFilter) => {
@ -1135,7 +1138,7 @@ module.exports = class SplitChunksPlugin {
// Determine name for split chunk // Determine name for split chunk
const name = const name =
/** @type {GetName} */ /** @type {GetNameFn} */
(cacheGroup.getName)(module, selectedChunks, cacheGroup.key); (cacheGroup.getName)(module, selectedChunks, cacheGroup.key);
// Check if the name is ok // Check if the name is ok
const existingChunk = name && compilation.namedChunks.get(name); const existingChunk = name && compilation.namedChunks.get(name);
@ -1297,7 +1300,7 @@ module.exports = class SplitChunksPlugin {
const { chunks: selectedChunks, key: selectedChunksKey } = const { chunks: selectedChunks, key: selectedChunksKey } =
getSelectedChunks( getSelectedChunks(
chunkCombination, chunkCombination,
/** @type {ChunkFilterFunction} */ /** @type {ChunkFilterFn} */
(cacheGroup.chunksFilter) (cacheGroup.chunksFilter)
); );
@ -1319,7 +1322,7 @@ module.exports = class SplitChunksPlugin {
/** /**
* @param {ChunksInfoItem} info entry * @param {ChunksInfoItem} info entry
* @param {string[]} sourceTypes source types to be removed * @param {SourceTypes} sourceTypes source types to be removed
*/ */
const removeModulesWithSourceType = (info, sourceTypes) => { const removeModulesWithSourceType = (info, sourceTypes) => {
for (const module of info.modules) { for (const module of info.modules) {

View File

@ -31,6 +31,7 @@ const NoAsyncChunksWarning = require("./NoAsyncChunksWarning");
* @property {string[]} files * @property {string[]} files
*/ */
/** @type {WeakSet<Entrypoint | ChunkGroup | Source>} */
const isOverSizeLimitSet = new WeakSet(); const isOverSizeLimitSet = new WeakSet();
/** /**
@ -55,7 +56,7 @@ module.exports = class SizeLimitsPlugin {
} }
/** /**
* @param {ChunkGroup | Source} thing the resource to test * @param {Entrypoint | ChunkGroup | Source} thing the resource to test
* @returns {boolean} true if over the limit * @returns {boolean} true if over the limit
*/ */
static isOverSizeLimit(thing) { static isOverSizeLimit(thing) {

View File

@ -20,18 +20,21 @@ const { parseResourceWithoutFragment } = require("../util/identifier");
const PLUGIN_NAME = "VirtualUrlPlugin"; const PLUGIN_NAME = "VirtualUrlPlugin";
const DEFAULT_SCHEME = "virtual"; const DEFAULT_SCHEME = "virtual";
/** @typedef {(loaderContext: LoaderContext<EXPECTED_ANY>) => Promise<string | Buffer> | string | Buffer} SourceFn */
/** @typedef {() => string} VersionFn */
/** /**
* @typedef {object} VirtualModuleConfig * @typedef {object} VirtualModuleConfig
* @property {string=} type - The module type * @property {string=} type the module type
* @property {(loaderContext: LoaderContext<EXPECTED_ANY>) => Promise<string> | string} source - The source function * @property {SourceFn} source the source function
* @property {(() => string) | true | string=} version - Optional version function or value * @property {VersionFn | true | string=} version optional version function or value
*/ */
/** /**
* @typedef {string | ((loaderContext: LoaderContext<EXPECTED_ANY>) => Promise<string> | string) | VirtualModuleConfig} VirtualModuleInput * @typedef {string | SourceFn | VirtualModuleConfig} VirtualModuleInput
*/ */
/** @typedef {{[key: string]: VirtualModuleInput}} VirtualModules */ /** @typedef {{ [key: string]: VirtualModuleInput }} VirtualModules */
/** /**
* Normalizes a virtual module definition into a standard format * Normalizes a virtual module definition into a standard format
@ -59,13 +62,13 @@ function normalizeModule(virtualConfig) {
* Normalizes all virtual modules with the given scheme * Normalizes all virtual modules with the given scheme
* @param {VirtualModules} virtualConfigs The virtual modules to normalize * @param {VirtualModules} virtualConfigs The virtual modules to normalize
* @param {string} scheme The URL scheme to use * @param {string} scheme The URL scheme to use
* @returns {{[key: string]: VirtualModuleConfig}} The normalized virtual modules * @returns {{ [key: string]: VirtualModuleConfig }} The normalized virtual modules
*/ */
function normalizeModules(virtualConfigs, scheme) { function normalizeModules(virtualConfigs, scheme) {
return Object.keys(virtualConfigs).reduce((pre, id) => { return Object.keys(virtualConfigs).reduce((pre, id) => {
pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]); pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]);
return pre; return pre;
}, /** @type {{[key: string]: VirtualModuleConfig}} */ ({})); }, /** @type {{ [key: string]: VirtualModuleConfig }} */ ({}));
} }
/** /**
@ -204,7 +207,7 @@ class VirtualUrlPlugin {
/** /**
* Get the cache version for a given version value * Get the cache version for a given version value
* @param {(() => string) | true | string} version The version value or function * @param {VersionFn | true | string} version The version value or function
* @returns {string | undefined} The cache version * @returns {string | undefined} The cache version
*/ */
getCacheVersion(version) { getCacheVersion(version) {

View File

@ -7,6 +7,8 @@
/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ /** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {string[]} Keys */
class NullPrototypeObjectSerializer { class NullPrototypeObjectSerializer {
/** /**
* @template {object} T * @template {object} T
@ -14,7 +16,7 @@ class NullPrototypeObjectSerializer {
* @param {ObjectSerializerContext} context context * @param {ObjectSerializerContext} context context
*/ */
serialize(obj, context) { serialize(obj, context) {
/** @type {string[]} */ /** @type {Keys} */
const keys = Object.keys(obj); const keys = Object.keys(obj);
for (const key of keys) { for (const key of keys) {
context.write(key); context.write(key);
@ -33,9 +35,9 @@ class NullPrototypeObjectSerializer {
deserialize(context) { deserialize(context) {
/** @type {T} */ /** @type {T} */
const obj = Object.create(null); const obj = Object.create(null);
/** @type {string[]} */ /** @type {Keys} */
const keys = []; const keys = [];
/** @type {string | null} */ /** @type {Keys[number] | null} */
let key = context.read(); let key = context.read();
while (key !== null) { while (key !== null) {
keys.push(key); keys.push(key);

View File

@ -24,6 +24,7 @@ const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependen
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -101,7 +102,7 @@ class ConsumeSharedModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
const { shareKey, shareScope, import: request } = this.options; const { shareKey, shareScope, import: request } = this.options;

View File

@ -19,6 +19,7 @@ const ProvideForSharedDependency = require("./ProvideForSharedDependency");
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").LibIdent} LibIdent */
/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */ /** @typedef {import("../Module").SourceTypes} SourceTypes */
@ -64,7 +65,7 @@ class ProvideSharedModule extends Module {
/** /**
* @param {LibIdentOptions} options options * @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion * @returns {LibIdent | null} an identifier for library inclusion
*/ */
libIdent(options) { libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${

View File

@ -44,10 +44,12 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../Module")} Module */ /** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").BuildInfo} BuildInfo */ /** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
/** @typedef {import("../ModuleProfile")} ModuleProfile */ /** @typedef {import("../ModuleProfile")} ModuleProfile */
/** @typedef {import("../WebpackError")} WebpackError */ /** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
/** /**
* @template T * @template T
@ -109,6 +111,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
*/ */
/** @typedef {KnownStatsAsset & Record<string, EXPECTED_ANY>} StatsAsset */ /** @typedef {KnownStatsAsset & Record<string, EXPECTED_ANY>} StatsAsset */
/** @typedef {string[]} ChunkIdHints */
/** /**
* @typedef {object} KnownStatsAsset * @typedef {object} KnownStatsAsset
* @property {string} type * @property {string} type
@ -121,10 +124,10 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {StatsAsset[]=} related * @property {StatsAsset[]=} related
* @property {ChunkId[]=} chunks * @property {ChunkId[]=} chunks
* @property {ChunkName[]=} chunkNames * @property {ChunkName[]=} chunkNames
* @property {string[]=} chunkIdHints * @property {ChunkIdHints=} chunkIdHints
* @property {ChunkId[]=} auxiliaryChunks * @property {ChunkId[]=} auxiliaryChunks
* @property {ChunkName[]=} auxiliaryChunkNames * @property {ChunkName[]=} auxiliaryChunkNames
* @property {string[]=} auxiliaryChunkIdHints * @property {ChunkIdHints=} auxiliaryChunkIdHints
* @property {number=} filteredRelated * @property {number=} filteredRelated
* @property {boolean=} isOverSizeLimit * @property {boolean=} isOverSizeLimit
*/ */
@ -133,7 +136,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
/** /**
* @typedef {object} KnownStatsChunkGroup * @typedef {object} KnownStatsChunkGroup
* @property {ChunkName=} name * @property {ChunkName=} name
* @property {(string | number)[]=} chunks * @property {ChunkId[]=} chunks
* @property {({ name: string, size?: number })[]=} assets * @property {({ name: string, size?: number })[]=} assets
* @property {number=} filteredAssets * @property {number=} filteredAssets
* @property {number=} assetsSize * @property {number=} assetsSize
@ -154,7 +157,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {(string | null)=} layer * @property {(string | null)=} layer
* @property {string=} identifier * @property {string=} identifier
* @property {string=} name * @property {string=} name
* @property {(string | null)=} nameForCondition * @property {NameForCondition | null=} nameForCondition
* @property {number=} index * @property {number=} index
* @property {number=} preOrderIndex * @property {number=} preOrderIndex
* @property {number=} index2 * @property {number=} index2
@ -168,10 +171,10 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {boolean=} cached * @property {boolean=} cached
* @property {boolean=} optional * @property {boolean=} optional
* @property {boolean=} orphan * @property {boolean=} orphan
* @property {string | number=} id * @property {ModuleId=} id
* @property {string | number | null=} issuerId * @property {ModuleId | null=} issuerId
* @property {(string | number)[]=} chunks * @property {ChunkId[]=} chunks
* @property {(string | number)[]=} assets * @property {string[]=} assets
* @property {boolean=} dependent * @property {boolean=} dependent
* @property {(string | null)=} issuer * @property {(string | null)=} issuer
* @property {(string | null)=} issuerName * @property {(string | null)=} issuerName
@ -181,8 +184,8 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {number=} warnings * @property {number=} warnings
* @property {StatsProfile=} profile * @property {StatsProfile=} profile
* @property {StatsModuleReason[]=} reasons * @property {StatsModuleReason[]=} reasons
* @property {(boolean | null | string[])=} usedExports * @property {boolean | null | ExportInfoName[]=} usedExports
* @property {(string[] | null)=} providedExports * @property {ExportInfoName[] | null=} providedExports
* @property {string[]=} optimizationBailout * @property {string[]=} optimizationBailout
* @property {(number | null)=} depth * @property {(number | null)=} depth
* @property {StatsModule[]=} modules * @property {StatsModule[]=} modules
@ -265,7 +268,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {string} moduleName * @property {string} moduleName
* @property {string} loc * @property {string} loc
* @property {string} request * @property {string} request
* @property {(string | number)=} moduleId * @property {ModuleId=} moduleId
*/ */
/** @typedef {KnownStatsModuleTraceItem & Record<string, EXPECTED_ANY>} StatsModuleTraceItem */ /** @typedef {KnownStatsModuleTraceItem & Record<string, EXPECTED_ANY>} StatsModuleTraceItem */
@ -550,6 +553,7 @@ const SIMPLE_EXTRACTORS = {
); );
} }
if (!context.cachedGetErrors) { if (!context.cachedGetErrors) {
/** @type {WeakMap<Compilation, Error[]>} */
const map = new WeakMap(); const map = new WeakMap();
context.cachedGetErrors = (compilation) => context.cachedGetErrors = (compilation) =>
map.get(compilation) || map.get(compilation) ||
@ -559,6 +563,7 @@ const SIMPLE_EXTRACTORS = {
); );
} }
if (!context.cachedGetWarnings) { if (!context.cachedGetWarnings) {
/** @type {WeakMap<Compilation, Error[]>} */
const map = new WeakMap(); const map = new WeakMap();
context.cachedGetWarnings = (compilation) => context.cachedGetWarnings = (compilation) =>
map.get(compilation) || map.get(compilation) ||
@ -905,7 +910,10 @@ const SIMPLE_EXTRACTORS = {
let filtered = 0; let filtered = 0;
if (options.errorDetails === "auto" && rawErrors.length >= 3) { if (options.errorDetails === "auto" && rawErrors.length >= 3) {
filtered = rawErrors filtered = rawErrors
.map((e) => typeof e !== "string" && e.details) .map(
(e) =>
typeof e !== "string" && /** @type {WebpackError} */ (e).details
)
.filter(Boolean).length; .filter(Boolean).length;
} }
if ( if (
@ -939,7 +947,10 @@ const SIMPLE_EXTRACTORS = {
let filtered = 0; let filtered = 0;
if (options.errorDetails === "auto") { if (options.errorDetails === "auto") {
filtered = cachedGetWarnings(compilation) filtered = cachedGetWarnings(compilation)
.map((e) => typeof e !== "string" && e.details) .map(
(e) =>
typeof e !== "string" && /** @type {WebpackError} */ (e).details
)
.filter(Boolean).length; .filter(Boolean).length;
} }
if ( if (
@ -1518,7 +1529,7 @@ const SIMPLE_EXTRACTORS = {
object.id = /** @type {ChunkId} */ (chunk.id); object.id = /** @type {ChunkId} */ (chunk.id);
}, },
chunkRelations: (object, chunk, _context) => { chunkRelations: (object, chunk, _context) => {
/** @typedef {Set<string | number>} ChunkRelations */ /** @typedef {Set<ChunkId>} ChunkRelations */
/** @type {ChunkRelations} */ /** @type {ChunkRelations} */
const parents = new Set(); const parents = new Set();
/** @type {ChunkRelations} */ /** @type {ChunkRelations} */

View File

@ -284,10 +284,15 @@ const DEFAULTS = {
colors: () => false colors: () => false
}; };
/**
* @template T
* @typedef {(value: T, ...args: EXPECTED_ANY[]) => boolean} NormalizeFunction
*/
/** /**
* @template {string} T * @template {string} T
* @param {string | ({ test: (value: T) => boolean }) | ((value: T, ...args: EXPECTED_ANY[]) => boolean) | boolean} item item to normalize * @param {string | ({ test: (value: T) => boolean }) | NormalizeFunction<T> | boolean} item item to normalize
* @returns {(value: T, ...args: EXPECTED_ANY[]) => boolean} normalize fn * @returns {NormalizeFunction<T>} normalize fn
*/ */
const normalizeFilter = (item) => { const normalizeFilter = (item) => {
if (typeof item === "string") { if (typeof item === "string") {
@ -303,12 +308,19 @@ const normalizeFilter = (item) => {
return () => item; return () => item;
} }
return /** @type {(value: T, ...args: EXPECTED_ANY[]) => boolean} */ (item); return /** @type {NormalizeFunction<T>} */ (item);
}; };
/** @typedef {keyof (KnownNormalizedStatsOptions | StatsOptions)} NormalizerKeys */ /** @typedef {keyof (KnownNormalizedStatsOptions | StatsOptions)} NormalizerKeys */
/** @typedef {{ [Key in NormalizerKeys]?: (value: StatsOptions[Key]) => KnownNormalizedStatsOptions[Key] }} Normalizers */ /** @typedef {{ [Key in NormalizerKeys]?: (value: StatsOptions[Key]) => KnownNormalizedStatsOptions[Key] }} Normalizers */
/**
* @callback WarningFilterFn
* @param {StatsError} warning warning
* @param {string} warningString warning string
* @returns {boolean} result
*/
/** @type {Normalizers} */ /** @type {Normalizers} */
const NORMALIZER = { const NORMALIZER = {
excludeModules: (value) => { excludeModules: (value) => {
@ -329,12 +341,6 @@ const NORMALIZER = {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {
value = value ? [value] : []; value = value ? [value] : [];
} }
/**
* @callback WarningFilterFn
* @param {StatsError} warning warning
* @param {string} warningString warning string
* @returns {boolean} result
*/
return value.map( return value.map(
/** /**
* @param {StatsOptions["warningsFilter"]} filter a warning filter * @param {StatsOptions["warningsFilter"]} filter a warning filter

View File

@ -50,8 +50,8 @@ const smartGrouping = require("../util/smartGrouping");
* @property {Map<string, Chunk[]>} compilationFileToChunks * @property {Map<string, Chunk[]>} compilationFileToChunks
* @property {Map<string, Chunk[]>} compilationAuxiliaryFileToChunks * @property {Map<string, Chunk[]>} compilationAuxiliaryFileToChunks
* @property {RuntimeSpec} runtime * @property {RuntimeSpec} runtime
* @property {(compilation: Compilation) => WebpackError[]} cachedGetErrors * @property {(compilation: Compilation) => Error[]} cachedGetErrors
* @property {(compilation: Compilation) => WebpackError[]} cachedGetWarnings * @property {(compilation: Compilation) => Error[]} cachedGetWarnings
*/ */
/** @typedef {KnownStatsFactoryContext & Record<string, EXPECTED_ANY>} StatsFactoryContext */ /** @typedef {KnownStatsFactoryContext & Record<string, EXPECTED_ANY>} StatsFactoryContext */

View File

@ -10,6 +10,8 @@
/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
/** @typedef {Range[]} IdRanges */
/** /**
* @summary Get the subset of ids and their corresponding range in an id chain that should be re-rendered by webpack. * @summary Get the subset of ids and their corresponding range in an id chain that should be re-rendered by webpack.
* Only those in the chain that are actually referring to namespaces or imports should be re-rendered. * Only those in the chain that are actually referring to namespaces or imports should be re-rendered.
@ -18,7 +20,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[] | undefined} ranges cumulative range of ids for each of allIds * @param {IdRanges | 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

View File

@ -56,11 +56,13 @@ const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => {
return (value) => `!/^${negativeRegexp}$/.test(${value})`; return (value) => `!/^${negativeRegexp}$/.test(${value})`;
}; };
/** @typedef {string[][]} ListOfCommonItems */
/** /**
* @param {Set<string>} itemsSet items set * @param {Set<string>} itemsSet items set
* @param {(str: string) => string | false} getKey get key function * @param {(str: string) => string | false} getKey get key function
* @param {(str: string[]) => boolean} condition condition * @param {(str: string[]) => boolean} condition condition
* @returns {string[][]} list of common items * @returns {ListOfCommonItems} list of common items
*/ */
const popCommonItems = (itemsSet, getKey, condition) => { const popCommonItems = (itemsSet, getKey, condition) => {
/** @type {Map<string, string[]>} */ /** @type {Map<string, string[]>} */
@ -77,7 +79,7 @@ const popCommonItems = (itemsSet, getKey, condition) => {
list.push(item); list.push(item);
} }
} }
/** @type {string[][]} */ /** @type {ListOfCommonItems} */
const result = []; const result = [];
for (const list of map.values()) { for (const list of map.values()) {
if (condition(list)) { if (condition(list)) {

View File

@ -70,9 +70,11 @@ const getName = (a, b, usedNames) => {
return a; return a;
}; };
/** @typedef {Record<string, number>} Sizes */
/** /**
* @param {Record<string, number>} total total size * @param {Sizes} total total size
* @param {Record<string, number>} size single size * @param {Sizes} size single size
* @returns {void} * @returns {void}
*/ */
const addSizeTo = (total, size) => { const addSizeTo = (total, size) => {
@ -82,8 +84,8 @@ const addSizeTo = (total, size) => {
}; };
/** /**
* @param {Record<string, number>} total total size * @param {Sizes} total total size
* @param {Record<string, number>} size single size * @param {Sizes} size single size
* @returns {void} * @returns {void}
*/ */
const subtractSizeFrom = (total, size) => { const subtractSizeFrom = (total, size) => {
@ -95,7 +97,7 @@ const subtractSizeFrom = (total, size) => {
/** /**
* @template T * @template T
* @param {Iterable<Node<T>>} nodes some nodes * @param {Iterable<Node<T>>} nodes some nodes
* @returns {Record<string, number>} total size * @returns {Sizes} total size
*/ */
const sumSize = (nodes) => { const sumSize = (nodes) => {
const sum = Object.create(null); const sum = Object.create(null);
@ -106,8 +108,8 @@ const sumSize = (nodes) => {
}; };
/** /**
* @param {Record<string, number>} size size * @param {Sizes} size size
* @param {Record<string, number>} maxSize minimum size * @param {Sizes} maxSize minimum size
* @returns {boolean} true, when size is too big * @returns {boolean} true, when size is too big
*/ */
const isTooBig = (size, maxSize) => { const isTooBig = (size, maxSize) => {
@ -121,8 +123,8 @@ const isTooBig = (size, maxSize) => {
}; };
/** /**
* @param {Record<string, number>} size size * @param {Sizes} size size
* @param {Record<string, number>} minSize minimum size * @param {Sizes} minSize minimum size
* @returns {boolean} true, when size is too small * @returns {boolean} true, when size is too small
*/ */
const isTooSmall = (size, minSize) => { const isTooSmall = (size, minSize) => {
@ -136,8 +138,8 @@ const isTooSmall = (size, minSize) => {
}; };
/** /**
* @param {Record<string, number>} size size * @param {Sizes} size size
* @param {Record<string, number>} minSize minimum size * @param {Sizes} minSize minimum size
* @returns {Set<string>} set of types that are too small * @returns {Set<string>} set of types that are too small
*/ */
const getTooSmallTypes = (size, minSize) => { const getTooSmallTypes = (size, minSize) => {
@ -166,7 +168,7 @@ const getNumberOfMatchingSizeTypes = (size, types) => {
}; };
/** /**
* @param {Record<string, number>} size size * @param {Sizes} size size
* @param {Set<string>} types types * @param {Set<string>} types types
* @returns {number} selective size sum * @returns {number} selective size sum
*/ */
@ -185,7 +187,7 @@ class Node {
/** /**
* @param {T} item item * @param {T} item item
* @param {string} key key * @param {string} key key
* @param {Record<string, number>} size size * @param {Sizes} size size
*/ */
constructor(item, key, size) { constructor(item, key, size) {
this.item = item; this.item = item;
@ -194,14 +196,16 @@ class Node {
} }
} }
/** @typedef {number[]} Similarities */
/** /**
* @template T * @template T
*/ */
class Group { class Group {
/** /**
* @param {Node<T>[]} nodes nodes * @param {Node<T>[]} nodes nodes
* @param {number[] | null} similarities similarities between the nodes (length = nodes.length - 1) * @param {Similarities | null} similarities similarities between the nodes (length = nodes.length - 1)
* @param {Record<string, number>=} size size of the group * @param {Sizes=} size size of the group
*/ */
constructor(nodes, similarities, size) { constructor(nodes, similarities, size) {
this.nodes = nodes; this.nodes = nodes;
@ -228,7 +232,7 @@ class Group {
if (newNodes.length > 0) { if (newNodes.length > 0) {
newSimilarities.push( newSimilarities.push(
lastNode === this.nodes[i - 1] lastNode === this.nodes[i - 1]
? /** @type {number[]} */ (this.similarities)[i - 1] ? /** @type {Similarities} */ (this.similarities)[i - 1]
: similarity(/** @type {Node<T>} */ (lastNode).key, node.key) : similarity(/** @type {Node<T>} */ (lastNode).key, node.key)
); );
} }
@ -247,11 +251,11 @@ class Group {
/** /**
* @template T * @template T
* @param {Iterable<Node<T>>} nodes nodes * @param {Iterable<Node<T>>} nodes nodes
* @returns {number[]} similarities * @returns {Similarities} similarities
*/ */
const getSimilarities = (nodes) => { const getSimilarities = (nodes) => {
// calculate similarities between lexically adjacent nodes // calculate similarities between lexically adjacent nodes
/** @type {number[]} */ /** @type {Similarities} */
const similarities = []; const similarities = [];
let last; let last;
for (const node of nodes) { for (const node of nodes) {
@ -268,16 +272,16 @@ const getSimilarities = (nodes) => {
* @typedef {object} GroupedItems<T> * @typedef {object} GroupedItems<T>
* @property {string} key * @property {string} key
* @property {T[]} items * @property {T[]} items
* @property {Record<string, number>} size * @property {Sizes} size
*/ */
/** /**
* @template T * @template T
* @typedef {object} Options * @typedef {object} Options
* @property {Record<string, number>} maxSize maximum size of a group * @property {Sizes} maxSize maximum size of a group
* @property {Record<string, number>} minSize minimum size of a group (preferred over maximum size) * @property {Sizes} minSize minimum size of a group (preferred over maximum size)
* @property {Iterable<T>} items a list of items * @property {Iterable<T>} items a list of items
* @property {(item: T) => Record<string, number>} getSize function to get size of an item * @property {(item: T) => Sizes} getSize function to get size of an item
* @property {(item: T) => string} getKey function to get the key of an item * @property {(item: T) => string} getKey function to get the key of an item
*/ */
@ -320,7 +324,7 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => {
/** /**
* @param {Group<T>} group group * @param {Group<T>} group group
* @param {Record<string, number>} consideredSize size of the group to consider * @param {Sizes} consideredSize size of the group to consider
* @returns {boolean} true, if the group was modified * @returns {boolean} true, if the group was modified
*/ */
const removeProblematicNodes = (group, consideredSize = group.size) => { const removeProblematicNodes = (group, consideredSize = group.size) => {
@ -455,9 +459,9 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => {
// rightSize ^^^^^^^^^^^^^^^ // rightSize ^^^^^^^^^^^^^^^
while (pos <= right + 1) { while (pos <= right + 1) {
const similarity = /** @type {number[]} */ (group.similarities)[ const similarity =
pos - 1 /** @type {Similarities} */
]; (group.similarities)[pos - 1];
if ( if (
similarity < bestSimilarity && similarity < bestSimilarity &&
!isTooSmall(leftSize, minSize) && !isTooSmall(leftSize, minSize) &&
@ -484,22 +488,22 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => {
// create two new groups for left and right area // create two new groups for left and right area
// and queue them up // and queue them up
const rightNodes = [group.nodes[right + 1]]; const rightNodes = [group.nodes[right + 1]];
/** @type {number[]} */ /** @type {Similarities} */
const rightSimilarities = []; const rightSimilarities = [];
for (let i = right + 2; i < group.nodes.length; i++) { for (let i = right + 2; i < group.nodes.length; i++) {
rightSimilarities.push( rightSimilarities.push(
/** @type {number[]} */ (group.similarities)[i - 1] /** @type {Similarities} */ (group.similarities)[i - 1]
); );
rightNodes.push(group.nodes[i]); rightNodes.push(group.nodes[i]);
} }
queue.push(new Group(rightNodes, rightSimilarities)); queue.push(new Group(rightNodes, rightSimilarities));
const leftNodes = [group.nodes[0]]; const leftNodes = [group.nodes[0]];
/** @type {number[]} */ /** @type {Similarities} */
const leftSimilarities = []; const leftSimilarities = [];
for (let i = 1; i < left; i++) { for (let i = 1; i < left; i++) {
leftSimilarities.push( leftSimilarities.push(
/** @type {number[]} */ (group.similarities)[i - 1] /** @type {Similarities} */ (group.similarities)[i - 1]
); );
leftNodes.push(group.nodes[i]); leftNodes.push(group.nodes[i]);
} }

View File

@ -6,7 +6,8 @@
"use strict"; "use strict";
/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
/** @typedef {string | number | undefined} SemVerRangeItem */ /** @typedef {string | number} VersionValue */
/** @typedef {VersionValue | undefined} SemVerRangeItem */
/** @typedef {(SemVerRangeItem | SemVerRangeItem[])[]} SemVerRange */ /** @typedef {(SemVerRangeItem | SemVerRangeItem[])[]} SemVerRange */
/** /**
@ -16,12 +17,12 @@
const parseVersion = (str) => { const parseVersion = (str) => {
/** /**
* @param {str} str str * @param {str} str str
* @returns {(string | number)[]} result * @returns {VersionValue[]} result
*/ */
var splitAndConvert = function (str) { var splitAndConvert = function (str) {
return str.split(".").map(function (item) { return str.split(".").map(function (item) {
// eslint-disable-next-line eqeqeq // eslint-disable-next-line eqeqeq
return +item == /** @type {EXPECTED_ANY} */ (item) ? +item : item; return +item == /** @type {string | number} */ (item) ? +item : item;
}); });
}; };
@ -29,7 +30,7 @@ const parseVersion = (str) => {
/** @type {RegExpExecArray} */ /** @type {RegExpExecArray} */
(/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str)); (/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str));
/** @type {(string | number | undefined | [])[]} */ /** @type {(VersionValue | undefined | [])[]} */
var ver = match[1] ? splitAndConvert(match[1]) : []; var ver = match[1] ? splitAndConvert(match[1]) : [];
if (match[2]) { if (match[2]) {
@ -103,7 +104,7 @@ module.exports.versionLt = versionLt;
module.exports.parseRange = (str) => { module.exports.parseRange = (str) => {
/** /**
* @param {string} str str * @param {string} str str
* @returns {(string | number)[]} result * @returns {VersionValue[]} result
*/ */
const splitAndConvert = (str) => { const splitAndConvert = (str) => {
return str return str
@ -429,7 +430,7 @@ const satisfy = (range, version) => {
/** @type {"s" | "n" | "u" | ""} */ /** @type {"s" | "n" | "u" | ""} */
(j < range.length ? (typeof range[j])[0] : ""); (j < range.length ? (typeof range[j])[0] : "");
/** @type {number | string | undefined} */ /** @type {VersionValue | undefined} */
var versionValue; var versionValue;
/** @type {"n" | "s" | "u" | "o" | undefined} */ /** @type {"n" | "s" | "u" | "o" | undefined} */
var versionType; var versionType;
@ -470,8 +471,8 @@ const satisfy = (range, version) => {
// Handles "cmp" cases // Handles "cmp" cases
if ( if (
negated negated
? versionValue > /** @type {(number | string)[]} */ (range)[j] ? versionValue > /** @type {VersionValue[]} */ (range)[j]
: versionValue < /** @type {(number | string)[]} */ (range)[j] : versionValue < /** @type {VersionValue[]} */ (range)[j]
) { ) {
return false; return false;
} }

Some files were not shown because too many files have changed in this diff Show More