fix: less `any` types (#19382)

This commit is contained in:
Alexander Akait 2025-04-04 16:38:51 +03:00 committed by GitHub
parent 05b39c2c60
commit b8b90d6ee9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 355 additions and 197 deletions

View File

@ -358,6 +358,12 @@ export default [
"JsdocBlock:has(JsdocTag[tag!=/^(typedef|template|param)$/]:has(JsdocTypeName[value=/^(Object|object)$/]))",
message:
"Please use provide types for object - `{ property: number:, result: () => number}` instead `Object`/`object` or use `EXPECTED_OBJECT` type"
},
{
comment:
"JsdocBlock:has(JsdocTag[tag=typedef][parsedType.type!=JsdocTypeName]:has(JsdocTypeName[value=/^(Object|object)$/]))",
message:
"Please use provide types for object - `{ property: number:, result: () => number}` instead `Object`/`object` or use `EXPECTED_OBJECT` type"
}
]
}

View File

@ -220,7 +220,7 @@ const { isSourceEqual } = require("./util/source");
* @property {EntryOptions=} entryOptions
*/
/** @typedef {Record<string, any>} ExecuteModuleExports */
/** @typedef {Record<string, EXPECTED_ANY>} ExecuteModuleExports */
/**
* @typedef {object} ExecuteModuleResult
@ -276,7 +276,7 @@ const { isSourceEqual } = require("./util/source");
/**
* @typedef {object} LogEntry
* @property {string} type
* @property {any[]=} args
* @property {EXPECTED_ANY[]=} args
* @property {number} time
* @property {string[]=} trace
*/
@ -372,17 +372,17 @@ const { isSourceEqual } = require("./util/source");
* @property {false | "none" | "error" | "warn" | "info" | "log" | "verbose"} logging
* @property {((value: string) => boolean)[]} loggingDebug
* @property {boolean} loggingTrace
* @property {any} _env
* @property {TODO} _env
*/
/** @typedef {KnownNormalizedStatsOptions & Omit<StatsOptions, keyof KnownNormalizedStatsOptions> & Record<string, any>} NormalizedStatsOptions */
/** @typedef {KnownNormalizedStatsOptions & Omit<StatsOptions, keyof KnownNormalizedStatsOptions> & Record<string, EXPECTED_ANY>} NormalizedStatsOptions */
/**
* @typedef {object} KnownCreateStatsOptionsContext
* @property {boolean=} forToString
*/
/** @typedef {KnownCreateStatsOptionsContext & Record<string, any>} CreateStatsOptionsContext */
/** @typedef {KnownCreateStatsOptionsContext & Record<string, EXPECTED_ANY>} CreateStatsOptionsContext */
/** @typedef {{ module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}} CodeGenerationJob */
@ -465,7 +465,7 @@ const compareErrors = concatComparators(byModule, byLocation, byMessage);
* @property {GeneratorOptions} [generatorOptions]
*/
/** @typedef {KnownUnsafeCacheData & Record<string, any>} UnsafeCacheData */
/** @typedef {KnownUnsafeCacheData & Record<string, EXPECTED_ANY>} UnsafeCacheData */
/**
* @typedef {Module & { restoreFromUnsafeCache?: (unsafeCacheData: UnsafeCacheData, moduleFactory: ModuleFactory, compilationParams: CompilationParams) => void }} ModuleWithRestoreFromUnsafeCache
@ -477,6 +477,8 @@ const unsafeCacheDependencies = new WeakMap();
/** @type {WeakMap<ModuleWithRestoreFromUnsafeCache, UnsafeCacheData>} */
const unsafeCacheData = new WeakMap();
/** @typedef {Map<Module, WeakTupleMap<any, any>>} ModuleMemCaches */
class Compilation {
/**
* Creates an instance of Compilation.
@ -1047,9 +1049,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
};
defineRemovedModuleTemplates(this.moduleTemplates);
/** @type {Map<Module, WeakTupleMap<any, any>> | undefined} */
/** @type {ModuleMemCaches | undefined} */
this.moduleMemCaches = undefined;
/** @type {Map<Module, WeakTupleMap<any, any>> | undefined} */
/** @type {ModuleMemCaches | undefined} */
this.moduleMemCaches2 = undefined;
this.moduleGraph = new ModuleGraph();
/** @type {ChunkGraph} */
@ -3096,7 +3098,12 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
const entryModules = new Set();
for (const dep of [...this.globalEntry.dependencies, ...dependencies]) {
entrypoint.addOrigin(null, { name }, /** @type {any} */ (dep).request);
entrypoint.addOrigin(
null,
{ name },
/** @type {Dependency & { request: string }} */
(dep).request
);
const module = this.moduleGraph.getModule(dep);
if (module) {
@ -5626,7 +5633,7 @@ Object.defineProperty(compilationPrototype, "cache", {
),
set: util.deprecate(
/**
* @param {any} v value
* @param {EXPECTED_ANY} v value
*/
v => {},
"Compilation.cache was removed in favor of Compilation.getCache()",

View File

@ -53,12 +53,6 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */
/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
/**
* @template {any[]} T
* @template V
* @typedef {import("./util/WeakTupleMap")<T, V>} WeakTupleMap
*/
/**
* @typedef {object} CompilationParams
* @property {NormalModuleFactory} normalModuleFactory
@ -97,9 +91,9 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {{ sizeOnlySource: SizeOnlySource | undefined, writtenTo: Map<string, number> }} CacheEntry */
/** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: any, file: string }[] | undefined) }} SimilarEntry */
/** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: CacheEntry, file: string }[] | undefined) }} SimilarEntry */
/** @typedef {{ buildInfo: BuildInfo, references: References | undefined, memCache: WeakTupleMap<any, any> }} ModuleMemCachesItem */
/** @typedef {{ buildInfo: BuildInfo, references: References | undefined, memCache: import("./util/WeakTupleMap")<Module[], string> }} ModuleMemCachesItem */
/**
* @param {string[]} array an array

View File

@ -11,8 +11,14 @@ const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ModuleFilenameHelpers").Matcher} Matcher */
/** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */
/**
* @template T
* @typedef {import("../declarations/LoaderContext").LoaderContext<T>} LoaderContext
*/
const validate = createSchemaValidation(
require("../schemas/plugins/LoaderOptionsPlugin.check.js"),
() => require("../schemas/plugins/LoaderOptionsPlugin.json"),
@ -31,10 +37,7 @@ class LoaderOptionsPlugin {
// If no options are set then generate empty options object
if (typeof options !== "object") options = {};
if (!options.test) {
// This is mocking a RegExp object which always returns true
// TODO: Figure out how to do `as unknown as RegExp` for this line
// in JSDoc equivalent
/** @type {any} */
/** @type {TODO} */
const defaultTrueMockRegExp = {
test: () => true
};

View File

@ -11,6 +11,7 @@ const ModuleGraphConnection = require("./ModuleGraphConnection");
const SortableSet = require("./util/SortableSet");
const WeakTupleMap = require("./util/WeakTupleMap");
/** @typedef {import("./Compilation").ModuleMemCaches} ModuleMemCaches */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */
@ -124,8 +125,6 @@ class ModuleGraphModule {
/** @typedef {EXPECTED_OBJECT} MetaKey */
/** @typedef {TODO} Meta */
/** @typedef {Map<Module, WeakTupleMap<any, any>>} ModuleMemCaches */
class ModuleGraph {
constructor() {
/**

View File

@ -135,7 +135,7 @@ class MultiStats {
/**
* @param {StatsCompilation} j stats error
* @param {StatsError} obj Stats error
* @returns {TODO} result
* @returns {StatsError} result
*/
const mapError = (j, obj) => ({
...obj,

View File

@ -80,6 +80,7 @@ const memoize = require("./util/memoize");
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */
/** @typedef {import("./Parser")} Parser */
/** @typedef {import("./Parser").PreparsedAst} PreparsedAst */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
@ -97,8 +98,8 @@ const memoize = require("./util/memoize");
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook
*/
/** @typedef {{[k: string]: any}} ParserOptions */
/** @typedef {{[k: string]: any}} GeneratorOptions */
/** @typedef {{ [k: string]: EXPECTED_ANY }} ParserOptions */
/** @typedef {{ [k: string]: EXPECTED_ANY }} GeneratorOptions */
/**
* @template T
@ -132,7 +133,7 @@ const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
/**
* @typedef {object} LoaderItem
* @property {string} loader
* @property {any} options
* @property {string | null | undefined | Record<string, EXPECTED_ANY>} options
* @property {string?} ident
* @property {string?} type
*/
@ -208,7 +209,7 @@ const asBuffer = input => {
class NonErrorEmittedError extends WebpackError {
/**
* @param {any} error value which is not an instance of Error
* @param {EXPECTED_ANY} error value which is not an instance of Error
*/
constructor(error) {
super();
@ -224,16 +225,16 @@ makeSerializable(
"NonErrorEmittedError"
);
/** @typedef {[string | Buffer, string | SourceMapSource, Record<string, any>]} Result */
/** @typedef {[string | Buffer, string | SourceMapSource, PreparsedAst]} Result */
/**
* @typedef {object} NormalModuleCompilationHooks
* @property {SyncHook<[LoaderContext<any>, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext<any>]>} beforeLoaders
* @property {SyncHook<[LoaderContext<EXPECTED_ANY>, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext<EXPECTED_ANY>]>} beforeLoaders
* @property {SyncHook<[NormalModule]>} beforeParse
* @property {SyncHook<[NormalModule]>} beforeSnapshot
* @property {HookMap<FakeHook<AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>>>} readResourceForScheme
* @property {HookMap<AsyncSeriesBailHook<[LoaderContext<any>], string | Buffer | null>>} readResource
* @property {HookMap<AsyncSeriesBailHook<[LoaderContext<EXPECTED_ANY>], string | Buffer | null>>} readResource
* @property {SyncWaterfallHook<[Result, NormalModule]>} processResult
* @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
*/
@ -247,7 +248,7 @@ makeSerializable(
* @property {string} rawRequest request without resolving
* @property {LoaderItem[]} loaders list of loaders
* @property {string} resource path + query of the real resource
* @property {Record<string, any>=} resourceResolveData resource resolve data
* @property {TODO=} resourceResolveData resource resolve data
* @property {string} context context directory for resolving
* @property {string=} matchResource path + query of the matched resource (virtual)
* @property {Parser} parser the parser used
@ -260,6 +261,8 @@ makeSerializable(
/** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
const compilationHooksMap = new WeakMap();
/** @typedef {Map<string, EXPECTED_ANY>} CodeGeneratorData */
class NormalModule extends Module {
/**
* @param {Compilation} compilation the compilation
@ -400,7 +403,7 @@ class NormalModule extends Module {
this._isEvaluatingSideEffects = false;
/** @type {WeakSet<ModuleGraph> | undefined} */
this._addedSideEffectsBailout = undefined;
/** @type {Map<string, any>} */
/** @type {CodeGeneratorData} */
this._codeGeneratorData = new Map();
}
@ -694,13 +697,13 @@ class NormalModule extends Module {
if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
[, name, baseDataPath] = match;
}
getValidate()(schema, options, {
getValidate()(schema, /** @type {EXPECTED_OBJECT} */ (options), {
name,
baseDataPath
});
}
return options;
return /** @type {T} */ (options);
},
emitWarning: warning => {
if (!(warning instanceof Error)) {
@ -811,7 +814,11 @@ class NormalModule extends Module {
Object.assign(loaderContext, options.loader);
hooks.loader.call(/** @type {LoaderContext<any>} */ (loaderContext), this);
hooks.loader.call(
/** @type {LoaderContext<EXPECTED_ANY>} */
(loaderContext),
this
);
return loaderContext;
}
@ -915,7 +922,6 @@ class NormalModule extends Module {
});
return callback(error);
}
const result = hooks.processResult.call(
/** @type {Result} */ (_result),
this
@ -971,7 +977,8 @@ class NormalModule extends Module {
hooks.beforeLoaders.call(
this.loaders,
this,
/** @type {LoaderContext<any>} */ (loaderContext)
/** @type {LoaderContext<EXPECTED_ANY>} */
(loaderContext)
);
} catch (err) {
processResult(/** @type {Error} */ (err));
@ -1436,7 +1443,9 @@ class NormalModule extends Module {
runtimeRequirements.add(RuntimeGlobals.thisAsExports);
}
/** @type {() => Map<string, any>} */
/**
* @type {() => CodeGeneratorData}
*/
const getData = () => this._codeGeneratorData;
const sources = new Map();

View File

@ -84,7 +84,7 @@ const {
* @property {string=} context
*/
/** @typedef {ResourceData & { data: Record<string, any> }} ResourceDataWithData */
/** @typedef {ResourceData & { data: Record<string, EXPECTED_ANY> }} ResourceDataWithData */
/**
* @typedef {object} ParsedLoaderRequest

View File

@ -5,6 +5,7 @@
"use strict";
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./NormalModule")} NormalModule */
@ -16,10 +17,10 @@
* @property {NormalModule} current
* @property {NormalModule} module
* @property {Compilation} compilation
* @property {{[k: string]: any}} options
* @property {WebpackOptions} options
*/
/** @typedef {Record<string, any> & ParserStateBase} ParserState */
/** @typedef {Record<string, EXPECTED_ANY> & ParserStateBase} ParserState */
class Parser {
/* istanbul ignore next */

View File

@ -8,23 +8,25 @@
const path = require("path");
const webpackSchema = require("../schemas/WebpackOptions.json");
/** @typedef {TODO & { absolutePath: boolean, instanceof: string, cli: { helper?: boolean, exclude?: boolean } }} Schema */
/** @typedef {Parameters<import("schema-utils").validate>[0] & { absolutePath: boolean, instanceof: string, cli: { helper?: boolean, exclude?: boolean, description?: string, negatedDescription?: string, resetDescription?: string } }} Schema */
// TODO add originPath to PathItem for better errors
/**
* @typedef {object} PathItem
* @property {any} schema the part of the schema
* @property {Schema} schema the part of the schema
* @property {string} path the path in the config
*/
/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */
/** @typedef {string | number | boolean | RegExp} Value */
/**
* @typedef {object} Problem
* @property {ProblemType} type
* @property {string} path
* @property {string} argument
* @property {any=} value
* @property {Value=} value
* @property {number=} index
* @property {string=} expected
*/
@ -36,6 +38,10 @@ const webpackSchema = require("../schemas/WebpackOptions.json");
* @property {string=} expected
*/
/** @typedef {{ [key: string]: EnumValue }} EnumValueObject */
/** @typedef {EnumValue[]} EnumValueArray */
/** @typedef {string | number | boolean | EnumValueObject | EnumValueArray | null} EnumValue */
/**
* @typedef {object} ArgumentConfig
* @property {string | undefined} description
@ -43,7 +49,7 @@ const webpackSchema = require("../schemas/WebpackOptions.json");
* @property {string} path
* @property {boolean} multiple
* @property {"enum"|"string"|"path"|"number"|"boolean"|"RegExp"|"reset"} type
* @property {any[]=} values
* @property {EnumValue[]=} values
*/
/** @typedef {"string" | "number" | "boolean"} SimpleType */
@ -56,8 +62,6 @@ const webpackSchema = require("../schemas/WebpackOptions.json");
* @property {ArgumentConfig[]} configs
*/
/** @typedef {string | number | boolean | RegExp | (string | number | boolean | RegExp)} Value */
/** @typedef {Record<string, Argument>} Flags */
/**
@ -93,7 +97,7 @@ const getArguments = (schema = webpackSchema) => {
let schemaPart = schema;
for (let i = 1; i < newPath.length; i++) {
const inner = schemaPart[newPath[i]];
const inner = schemaPart[/** @type {keyof Schema} */ (newPath[i])];
if (!inner) {
break;
@ -147,7 +151,7 @@ const getArguments = (schema = webpackSchema) => {
/**
* @param {Schema} schemaPart schema
* @returns {Pick<ArgumentConfig, "type"|"values"> | undefined} partial argument config
* @returns {Pick<ArgumentConfig, "type" | "values"> | undefined} partial argument config
*/
const schemaToArgumentConfig = schemaPart => {
if (schemaPart.enum) {
@ -272,7 +276,7 @@ const getArguments = (schema = webpackSchema) => {
/**
* @param {Schema} schemaPart the current schema
* @param {string} schemaPath the current path in the schema
* @param {{ schema: TODO, path: string }[]} path all previous visited schemaParts
* @param {PathItem[]} path all previous visited schemaParts
* @param {string | null} inArray if inside of an array, the path to the array
* @returns {number} added arguments
*/
@ -291,6 +295,7 @@ const getArguments = (schema = webpackSchema) => {
if (schemaPart.cli && schemaPart.cli.exclude) return 0;
/** @type {PathItem[]} */
const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path];
let addedArguments = 0;
@ -423,7 +428,7 @@ const cliAddedItems = new WeakMap();
* @param {Configuration} config configuration
* @param {string} schemaPath path in the config
* @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
* @returns {{ problem?: LocalProblem, object?: any, property?: Property, value?: any }} problem or object with property and value
* @returns {{ problem?: LocalProblem, object?: TODO, property?: Property, value?: EXPECTED_OBJECT | EXPECTED_ANY[] }} problem or object with property and value
*/
const getObjectAndProperty = (config, schemaPath, index = 0) => {
if (!schemaPath) return { value: config };
@ -522,7 +527,7 @@ const getObjectAndProperty = (config, schemaPath, index = 0) => {
/**
* @param {Configuration} config configuration
* @param {string} schemaPath path in the config
* @param {any} value parsed value
* @param {ParsedValue} value parsed value
* @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
* @returns {LocalProblem | null} problem or null for success
*/
@ -587,10 +592,12 @@ const getExpectedValue = argConfig => {
}
};
/** @typedef {null | string | number | boolean | RegExp | EnumValue | []} ParsedValue */
/**
* @param {ArgumentConfig} argConfig processing instructions
* @param {Value} value the value
* @returns {any | undefined} parsed value
* @returns {ParsedValue | undefined} parsed value
*/
const parseValueForArgumentConfig = (argConfig, value) => {
switch (argConfig.type) {
@ -627,9 +634,10 @@ const parseValueForArgumentConfig = (argConfig, value) => {
break;
case "enum": {
const values =
/** @type {NonNullable<ArgumentConfig["values"]>} */
/** @type {EnumValue[]} */
(argConfig.values);
if (values.includes(value)) return value;
if (values.includes(/** @type {Exclude<Value, RegExp>} */ (value)))
return value;
for (const item of values) {
if (`${item}` === value) return item;
}
@ -641,7 +649,7 @@ const parseValueForArgumentConfig = (argConfig, value) => {
}
};
/** @typedef {any} Configuration */
/** @typedef {TODO} Configuration */
/**
* @param {Flags} args object of arguments

View File

@ -1726,7 +1726,7 @@ const getResolveLoaderDefaults = ({ cache }) => {
const applyInfrastructureLoggingDefaults = infrastructureLogging => {
F(infrastructureLogging, "stream", () => process.stderr);
const tty =
/** @type {any} */ (infrastructureLogging.stream).isTTY &&
/** @type {EXPECTED_ANY} */ (infrastructureLogging.stream).isTTY &&
process.env.TERM !== "dumb";
D(infrastructureLogging, "level", "info");
D(infrastructureLogging, "debug", false);

View File

@ -1572,7 +1572,7 @@ class CssParser extends Parser {
/**
* @param {Range} range range of the comment
* @returns {{ options: Record<string, any> | null, errors: (Error & { comment: Comment })[] | null }} result
* @returns {{ options: Record<string, EXPECTED_ANY> | null, errors: (Error & { comment: Comment })[] | null }} result
*/
parseCommentOptions(range) {
const comments = this.getComments(range);

View File

@ -104,7 +104,7 @@ class AMDRequireDependenciesBlockParserPlugin {
} else if (param.isConstArray()) {
/** @type {(string | LocalModuleDependency | AMDRequireItemDependency)[]} */
const deps = [];
for (const request of /** @type {any[]} */ (param.array)) {
for (const request of /** @type {EXPECTED_ANY[]} */ (param.array)) {
let dep;
let localModule;
if (request === "require") {

View File

@ -14,14 +14,14 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../json/JsonData")} JsonData */
/** @typedef {import("../json/JsonData").RawJsonData} RawJsonData */
/** @typedef {import("../json/JsonData").JsonValue} JsonValue */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
/**
* @callback GetExportsFromDataFn
* @param {RawJsonData} data raw json data
* @param {JsonValue} data raw json data
* @param {number} [curDepth] current depth
* @returns {ExportSpec[] | null} export spec or nothing
*/
@ -88,7 +88,7 @@ class JsonExportsDependency extends NullDependency {
getExports(moduleGraph) {
return {
exports: getExportsWithDepth(this.exportsDepth)(
this.data && /** @type {RawJsonData} */ (this.data.get())
this.data && /** @type {JsonValue} */ (this.data.get())
),
dependencies: undefined
};

View File

@ -184,13 +184,15 @@ class WorkerPlugin {
return true;
};
/** @typedef {Record<string, EXPECTED_ANY>} Values */
/**
* @param {JavascriptParser} parser the parser
* @param {ObjectExpression} expr expression
* @returns {{ expressions: Record<string, Expression | Pattern>, otherElements: (Property | SpreadElement)[], values: Record<string, any>, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object
* @returns {{ expressions: Record<string, Expression | Pattern>, otherElements: (Property | SpreadElement)[], values: Values, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object
*/
const parseObjectExpression = (parser, expr) => {
/** @type {Record<string, any>} */
/** @type {Values} */
const values = {};
/** @type {Record<string, Expression | Pattern>} */
const expressions = {};
@ -209,7 +211,8 @@ class WorkerPlugin {
expressions[prop.key.name] = prop.value;
if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) {
const value = parser.evaluateExpression(
/** @type {Expression} */ (prop.value)
/** @type {Expression} */
(prop.value)
);
if (value.isCompileTimeValue())
values[prop.key.name] = value.asCompileTimeValue();
@ -286,7 +289,7 @@ class WorkerPlugin {
/** @type {Record<string, Expression | Pattern>} */
expressions: {},
otherElements: [],
/** @type {Record<string, any>} */
/** @type {Values} */
values: {},
spread: false,
insertType: arg2 ? "spread" : "argument",

View File

@ -4505,7 +4505,7 @@ class JavascriptParser extends Parser {
}
this.hooks.finish.call(ast, comments);
this.scope = oldScope;
this.state = /** @type {ParserState} */ (oldState);
this.state = oldState;
this.comments = oldComments;
this.semicolons = oldSemicolons;
this.statementPath = oldStatementPath;

View File

@ -10,16 +10,16 @@ const { register } = require("../util/serialization");
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
class JsonData {
/**
* @param {Buffer | RawJsonData} data JSON data
* @param {Buffer | JsonValue} data JSON data
*/
constructor(data) {
/** @type {Buffer | undefined} */
this._buffer = undefined;
/** @type {RawJsonData | undefined} */
/** @type {JsonValue | undefined} */
this._data = undefined;
if (Buffer.isBuffer(data)) {
this._buffer = data;
@ -29,7 +29,7 @@ class JsonData {
}
/**
* @returns {RawJsonData|undefined} Raw JSON data
* @returns {JsonValue | undefined} Raw JSON data
*/
get() {
if (this._data === undefined && this._buffer !== undefined) {

View File

@ -21,10 +21,12 @@ const RuntimeGlobals = require("../RuntimeGlobals");
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./JsonData")} JsonData */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
/** @typedef {import("./JsonModulesPlugin").JsonArray} JsonArray */
/** @typedef {import("./JsonModulesPlugin").JsonObject} JsonObject */
/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
/**
* @param {RawJsonData} data Raw JSON data
* @param {JsonValue} data Raw JSON data
* @returns {undefined|string} stringified data
*/
const stringifySafe = data => {
@ -39,30 +41,35 @@ const stringifySafe = data => {
};
/**
* @param {RawJsonData} data Raw JSON data (always an object or array)
* @param {JsonObject | JsonArray} data Raw JSON data (always an object or array)
* @param {ExportsInfo} exportsInfo exports info
* @param {RuntimeSpec} runtime the runtime
* @returns {RawJsonData} reduced data
* @returns {JsonObject | JsonArray} reduced data
*/
const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused)
return data;
const isArray = Array.isArray(data);
/** @type {RawJsonData} */
/** @type {JsonObject | JsonArray} */
const reducedData = isArray ? [] : {};
for (const key of Object.keys(data)) {
const exportInfo = exportsInfo.getReadOnlyExportInfo(key);
const used = exportInfo.getUsed(runtime);
if (used === UsageState.Unused) continue;
/** @type {RawJsonData} */
// The real type is `JsonObject | JsonArray`, but typescript doesn't work `Object.keys(['string', 'other-string', 'etc'])` properly
const newData = /** @type {JsonObject} */ (data)[key];
const value =
used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo
? createObjectForExportsInfo(data[key], exportInfo.exportsInfo, runtime)
: data[key];
used === UsageState.OnlyPropertiesUsed &&
exportInfo.exportsInfo &&
typeof newData === "object" &&
newData
? createObjectForExportsInfo(newData, exportInfo.exportsInfo, runtime)
: newData;
const name = /** @type {string} */ (exportInfo.getUsedName(key, runtime));
/** @type {Record<string, RawJsonData>} */ (reducedData)[name] = value;
/** @type {JsonObject} */
(reducedData)[name] = value;
}
if (isArray) {
const arrayLengthWhenUsed =
@ -72,8 +79,11 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
: undefined;
let sizeObjectMinusArray = 0;
for (let i = 0; i < reducedData.length; i++) {
if (reducedData[i] === undefined) {
const reducedDataLength =
/** @type {JsonArray} */
(reducedData).length;
for (let i = 0; i < reducedDataLength; i++) {
if (/** @type {JsonArray} */ (reducedData)[i] === undefined) {
sizeObjectMinusArray -= 2;
} else {
sizeObjectMinusArray += `${i}`.length + 3;
@ -83,7 +93,7 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
sizeObjectMinusArray +=
`${arrayLengthWhenUsed}`.length +
8 -
(arrayLengthWhenUsed - reducedData.length) * 2;
(arrayLengthWhenUsed - reducedDataLength) * 2;
}
if (sizeObjectMinusArray < 0)
return Object.assign(
@ -95,11 +105,12 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
/** @type {number} */
const generatedLength =
arrayLengthWhenUsed !== undefined
? Math.max(arrayLengthWhenUsed, reducedData.length)
: reducedData.length;
? Math.max(arrayLengthWhenUsed, reducedDataLength)
: reducedDataLength;
for (let i = 0; i < generatedLength; i++) {
if (reducedData[i] === undefined) {
reducedData[i] = 0;
if (/** @type {JsonArray} */ (reducedData)[i] === undefined) {
/** @type {JsonArray} */
(reducedData)[i] = 0;
}
}
}
@ -129,7 +140,7 @@ class JsonGenerator extends Generator {
* @returns {number} estimate size of the module
*/
getSize(module, type) {
/** @type {RawJsonData | undefined} */
/** @type {JsonValue | undefined} */
const data =
module.buildInfo &&
module.buildInfo.jsonData &&
@ -162,7 +173,7 @@ class JsonGenerator extends Generator {
concatenationScope
}
) {
/** @type {RawJsonData | undefined} */
/** @type {JsonValue | undefined} */
const data =
module.buildInfo &&
module.buildInfo.jsonData &&
@ -175,7 +186,7 @@ class JsonGenerator extends Generator {
);
}
const exportsInfo = moduleGraph.getExportsInfo(module);
/** @type {RawJsonData} */
/** @type {JsonValue} */
const finalJson =
typeof data === "object" &&
data &&

View File

@ -11,7 +11,9 @@ const JsonGenerator = require("./JsonGenerator");
const JsonParser = require("./JsonParser");
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {Record<string, any>} RawJsonData */
/** @typedef {import("../util/fs").JsonArray} JsonArray */
/** @typedef {import("../util/fs").JsonObject} JsonObject */
/** @typedef {import("../util/fs").JsonValue} JsonValue */
const validate = createSchemaValidation(
require("../../schemas/plugins/JsonModulesPluginParser.check.js"),

View File

@ -15,7 +15,7 @@ const JsonData = require("./JsonData");
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
const getParseJson = memoize(() => require("json-parse-even-better-errors"));
@ -43,7 +43,7 @@ class JsonParser extends Parser {
typeof this.options.parse === "function"
? this.options.parse
: getParseJson();
/** @type {Buffer | RawJsonData | undefined} */
/** @type {Buffer | JsonValue | undefined} */
let data;
try {
data =
@ -55,7 +55,7 @@ class JsonParser extends Parser {
`Cannot parse JSON: ${/** @type {Error} */ (err).message}`
);
}
const jsonData = new JsonData(/** @type {Buffer | RawJsonData} */ (data));
const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data));
const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo);
buildInfo.jsonData = jsonData;
buildInfo.strict = true;

View File

@ -7,7 +7,7 @@
/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {(arg0?: any) => void} CacheAssoc */
/** @typedef {EXPECTED_FUNCTION} CacheAssoc */
/**
* @template T

View File

@ -4,7 +4,7 @@
"use strict";
/** @typedef {undefined | null | number | string | boolean | Buffer | object | (() => ComplexSerializableType[] | Promise<ComplexSerializableType[]>)} ComplexSerializableType */
/** @typedef {undefined | null | number | string | boolean | Buffer | EXPECTED_OBJECT | (() => ComplexSerializableType[] | Promise<ComplexSerializableType[]>)} ComplexSerializableType */
/** @typedef {undefined | null | number | bigint | string | boolean | Buffer | (() => PrimitiveSerializableType[] | Promise<PrimitiveSerializableType[]>)} PrimitiveSerializableType */

View File

@ -27,6 +27,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Chunk").ChunkId} ChunkId */
/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("../ChunkGroup")} ChunkGroup */
/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */
/** @typedef {import("../Compilation")} Compilation */
@ -34,7 +35,6 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
/** @typedef {import("../Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("../Module")} Module */
@ -42,20 +42,23 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
/** @typedef {import("../ModuleProfile")} ModuleProfile */
/** @typedef {import("../RequestShortener")} RequestShortener */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./StatsFactory")} StatsFactory */
/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */
/**
* @template T
* @typedef {import("../util/comparators").Comparator<T>} Comparator<T>
*/
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @template T, R
* @typedef {import("../util/smartGrouping").GroupConfig<T, R>} GroupConfig
*/
/** @typedef {import("./StatsFactory")} StatsFactory */
/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsCompilation} StatsCompilation */
/** @typedef {KnownStatsCompilation & Record<string, EXPECTED_ANY>} StatsCompilation */
/**
* @typedef {object} KnownStatsCompilation
* @property {any=} env
@ -83,7 +86,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {Record<string, StatsLogging>=} logging
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsLogging} StatsLogging */
/** @typedef {KnownStatsLogging & Record<string, EXPECTED_ANY>} StatsLogging */
/**
* @typedef {object} KnownStatsLogging
* @property {StatsLoggingEntry[]} entries
@ -91,7 +94,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {boolean} debug
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsLoggingEntry} StatsLoggingEntry */
/** @typedef {KnownStatsLoggingEntry & Record<string, EXPECTED_ANY>} StatsLoggingEntry */
/**
* @typedef {object} KnownStatsLoggingEntry
* @property {string} type
@ -102,7 +105,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {number=} time
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsAsset} StatsAsset */
/** @typedef {KnownStatsAsset & Record<string, EXPECTED_ANY>} StatsAsset */
/**
* @typedef {object} KnownStatsAsset
* @property {string} type
@ -123,7 +126,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {boolean=} isOverSizeLimit
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsChunkGroup} StatsChunkGroup */
/** @typedef {KnownStatsChunkGroup & Record<string, EXPECTED_ANY>} StatsChunkGroup */
/**
* @typedef {object} KnownStatsChunkGroup
* @property {(string | null)=} name
@ -139,7 +142,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {boolean=} isOverSizeLimit
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsModule} StatsModule */
/** @typedef {KnownStatsModule & Record<string, EXPECTED_ANY>} StatsModule */
/**
* @typedef {object} KnownStatsModule
* @property {string=} type
@ -183,7 +186,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {ReturnType<Source["source"]>=} source
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsProfile} StatsProfile */
/** @typedef {KnownStatsProfile & Record<string, EXPECTED_ANY>} StatsProfile */
/**
* @typedef {object} KnownStatsProfile
* @property {number} total
@ -198,7 +201,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {number} dependencies
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsModuleIssuer} StatsModuleIssuer */
/** @typedef {KnownStatsModuleIssuer & Record<string, EXPECTED_ANY>} StatsModuleIssuer */
/**
* @typedef {object} KnownStatsModuleIssuer
* @property {string} identifier
@ -207,7 +210,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {StatsProfile} profile
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsModuleReason} StatsModuleReason */
/** @typedef {KnownStatsModuleReason & Record<string, EXPECTED_ANY>} StatsModuleReason */
/**
* @typedef {object} KnownStatsModuleReason
* @property {string | null} moduleIdentifier
@ -224,7 +227,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {(string | number | null)=} resolvedModuleId
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsChunk} StatsChunk */
/** @typedef {KnownStatsChunk & Record<string, EXPECTED_ANY>} StatsChunk */
/**
* @typedef {object} KnownStatsChunk
* @property {boolean} rendered
@ -250,7 +253,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {StatsChunkOrigin[]=} origins
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsChunkOrigin} StatsChunkOrigin */
/** @typedef {KnownStatsChunkOrigin & Record<string, EXPECTED_ANY>} StatsChunkOrigin */
/**
* @typedef {object} KnownStatsChunkOrigin
* @property {string} module
@ -261,7 +264,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {(string | number)=} moduleId
*/
/** @typedef { Record<string, EXPECTED_ANY> & KnownStatsModuleTraceItem} StatsModuleTraceItem */
/** @typedef {KnownStatsModuleTraceItem & Record<string, EXPECTED_ANY>} StatsModuleTraceItem */
/**
* @typedef {object} KnownStatsModuleTraceItem
* @property {string=} originIdentifier
@ -273,13 +276,13 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {(string|number)=} moduleId
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsModuleTraceDependency} StatsModuleTraceDependency */
/** @typedef {KnownStatsModuleTraceDependency & Record<string, EXPECTED_ANY>} StatsModuleTraceDependency */
/**
* @typedef {object} KnownStatsModuleTraceDependency
* @property {string=} loc
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsError} StatsError */
/** @typedef {KnownStatsError & Record<string, EXPECTED_ANY>} StatsError */
/**
* @typedef {object} KnownStatsError
* @property {string} message
@ -295,6 +298,7 @@ const { makePathsRelative, parseResource } = require("../util/identifier");
* @property {StatsModuleTraceItem[]=} moduleTrace
* @property {string=} details
* @property {string=} stack
* @property {string=} compilerPath
*/
/** @typedef {Asset & { type: string, related: PreprocessedAsset[] | undefined }} PreprocessedAsset */
@ -2298,7 +2302,7 @@ const MODULES_GROUPERS = type => ({
}
});
/** @typedef {Record<string, (groupConfigs: import("../util/smartGrouping").GroupConfig<KnownStatsModuleReason, TODO>[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} ModuleReasonsGroupers */
/** @typedef {Record<string, (groupConfigs: GroupConfig<KnownStatsModuleReason, TODO>[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} ModuleReasonsGroupers */
/** @type {ModuleReasonsGroupers} */
const MODULE_REASONS_GROUPERS = {

View File

@ -7,8 +7,14 @@
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsChunkGroup} KnownStatsChunkGroup */
/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsError} KnownStatsError */
/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleIssuer} KnownStatsModuleIssuer */
/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleTraceDependency} KnownStatsModuleTraceDependency */
/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleTraceItem} KnownStatsModuleTraceItem */
/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsProfile} KnownStatsProfile */
/** @typedef {import("./StatsPrinter")} StatsPrinter */
/** @typedef {import("./StatsPrinter").KnownStatsPrinterColorFn} KnownStatsPrinterColorFn */
/** @typedef {import("./StatsPrinter").KnownStatsPrinterContext} KnownStatsPrinterContext */
/** @typedef {import("./StatsPrinter").KnownStatsPrinterFormatters} KnownStatsPrinterFormatters */
/** @typedef {import("./StatsPrinter").StatsPrinterContext} StatsPrinterContext */
@ -111,6 +117,41 @@ const moreCount = (list, count) =>
* @typedef {{ [P in K]-?: T[P] }} WithRequired
*/
/**
* @template {keyof StatsPrinterContext} RequiredStatsPrinterContextKeys
* @typedef {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | RequiredStatsPrinterContextKeys>} DefineStatsPrinterContext
*/
/**
* @template T
* @template {keyof StatsPrinterContext} RequiredStatsPrinterContextKeys
* @typedef {(thing: Exclude<T, undefined>, context: DefineStatsPrinterContext<RequiredStatsPrinterContextKeys>, printer: StatsPrinter) => string | undefined} ModuleSimplePrinter
*/
/**
* @template T
* @typedef {T extends (infer U)[] ? U : T} Unpacked
*/
/**
* @template {object} O
* @template {keyof O} P
* @template {string} B
* @typedef {P extends string ? `${B}.${P}` : never} PropertyName
*/
/**
* @template {string} T
* @typedef {{ [property in `${T}.separator!`]: () => string }} Separator
*/
/**
* @template {object} O
* @template {string} B
* @template {string} [R=B]
* @typedef {{ [P in keyof O as PropertyName<O, P, B>]?: ModuleSimplePrinter<O[P], R> }} Printers
*/
/** @type {Record<string, (thing: any, context: Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation">, printer: StatsPrinter) => string | undefined>} */
const COMPILATION_SIMPLE_PRINTERS = {
"compilation.summary!": (
@ -339,13 +380,7 @@ const ASSET_SIMPLE_PRINTERS = {
"asset.info.javascriptModule": (javascriptModule, { formatFlag }) =>
javascriptModule ? formatFlag("javascript module") : undefined,
"asset.info.sourceFilename": (sourceFilename, { formatFlag }) =>
sourceFilename
? formatFlag(
sourceFilename === true
? "from source file"
: `from: ${sourceFilename}`
)
: undefined,
sourceFilename ? formatFlag(`from: ${sourceFilename}`) : undefined,
"asset.info.development": (development, { green, formatFlag }) =>
development ? green(formatFlag("dev")) : undefined,
"asset.info.hotModuleReplacement": (
@ -493,7 +528,7 @@ const MODULE_SIMPLE_PRINTERS = {
"module.separator!": () => "\n"
};
/** @type {Record<string, (thing: any, context: Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleIssuer">, printer: StatsPrinter) => string | undefined>} */
/** @type {Printers<KnownStatsModuleIssuer, "moduleIssuer"> & Printers<KnownStatsModuleIssuer["profile"], "moduleIssuer.profile", "moduleIssuer">} */
const MODULE_ISSUER_PRINTERS = {
"moduleIssuer.id": (id, { formatModuleId }) => formatModuleId(id),
"moduleIssuer.profile.total": (value, { formatTime }) => formatTime(value)
@ -525,7 +560,7 @@ const MODULE_REASON_PRINTERS = {
: undefined
};
/** @type {Record<string, (thing: any, context: Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "profile">, printer: StatsPrinter) => string | undefined>} */
/** @type {Printers<KnownStatsProfile, "module.profile", "profile">} */
const MODULE_PROFILE_PRINTERS = {
"module.profile.total": (value, { formatTime }) => formatTime(value),
"module.profile.resolving": (value, { formatTime }) =>
@ -650,7 +685,7 @@ const CHUNK_PRINTERS = {
"chunkOrigin.loc": loc => loc
};
/** @type {Record<string, (thing: any, context: Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "error">, printer: StatsPrinter) => string | undefined>} */
/** @type {Printers<KnownStatsError, "error"> & { ["error.filteredDetails"]?: (filteredDetails: number) => string | undefined } & Separator<"error">} */
const ERROR_PRINTERS = {
"error.compilerPath": (compilerPath, { bold }) =>
compilerPath ? bold(`(${compilerPath})`) : undefined,
@ -716,18 +751,18 @@ const LOG_ENTRY_PRINTERS = {
filteredEntries > 0 ? `+ ${filteredEntries} hidden lines` : undefined
};
/** @type {Record<string, (thing: any, context: Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleTraceItem">, printer: StatsPrinter) => string | undefined>} */
/** @type {Printers<KnownStatsModuleTraceItem, "moduleTraceItem">} */
const MODULE_TRACE_ITEM_PRINTERS = {
"moduleTraceItem.originName": originName => originName
};
/** @type {Record<string, (thing: any, context: Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleTraceDependency">, printer: StatsPrinter) => string | undefined>} */
/** @type {Printers<KnownStatsModuleTraceDependency, "moduleTraceDependency">} */
const MODULE_TRACE_DEPENDENCY_PRINTERS = {
"moduleTraceDependency.loc": loc => loc
};
/**
* @type {Record<string, string | ((item: any) => string)>}
* @type {Record<string, string | ((item: EXPECTED_ANY) => string)>}
*/
const ITEM_NAMES = {
"compilation.assets[]": "asset",
@ -1500,7 +1535,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
COMPILATION_SIMPLE_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation">} */
/** @type {DefineStatsPrinterContext<"compilation">} */
(ctx),
stats
)
@ -1513,7 +1548,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
ASSET_SIMPLE_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "asset">} */
/** @type {DefineStatsPrinterContext<"asset">} */
(ctx),
stats
)
@ -1526,7 +1561,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
MODULE_SIMPLE_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "module">} */
/** @type {DefineStatsPrinterContext<"module">} */
(ctx),
stats
)
@ -1537,9 +1572,10 @@ class DefaultStatsPrinterPlugin {
stats.hooks.print
.for(key)
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
MODULE_ISSUER_PRINTERS[key](
/** @type {Record<string, ModuleSimplePrinter<KnownStatsModuleIssuer[keyof KnownStatsModuleIssuer] | KnownStatsModuleIssuer["profile"][keyof KnownStatsModuleIssuer["profile"]], "type" | "compilation" | "moduleIssuer">>} */
(MODULE_ISSUER_PRINTERS)[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleIssuer">} */
/** @type {DefineStatsPrinterContext<"moduleIssuer">} */
(ctx),
stats
)
@ -1552,7 +1588,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
MODULE_REASON_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleReason">} */
/** @type {DefineStatsPrinterContext<"moduleReason">} */
(ctx),
stats
)
@ -1563,9 +1599,10 @@ class DefaultStatsPrinterPlugin {
stats.hooks.print
.for(key)
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
MODULE_PROFILE_PRINTERS[key](
/** @type {Record<string, ModuleSimplePrinter<KnownStatsProfile[keyof KnownStatsProfile], "type" | "compilation" | "profile">>} */
(MODULE_PROFILE_PRINTERS)[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "profile">} */
/** @type {DefineStatsPrinterContext<"profile">} */
(ctx),
stats
)
@ -1578,7 +1615,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
CHUNK_GROUP_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "chunkGroupKind" | "chunkGroup">} */
/** @type {DefineStatsPrinterContext<"chunkGroupKind" | "chunkGroup">} */
(ctx),
stats
)
@ -1591,7 +1628,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
CHUNK_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "chunk">} */
/** @type {DefineStatsPrinterContext<"chunk">} */
(ctx),
stats
)
@ -1602,9 +1639,10 @@ class DefaultStatsPrinterPlugin {
stats.hooks.print
.for(key)
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
ERROR_PRINTERS[key](
/** @type {Record<string, ModuleSimplePrinter<KnownStatsError[keyof KnownStatsError], "type" | "compilation" | "error">>} */
(ERROR_PRINTERS)[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "error">} */
/** @type {DefineStatsPrinterContext<"error">} */
(ctx),
stats
)
@ -1617,7 +1655,7 @@ class DefaultStatsPrinterPlugin {
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
LOG_ENTRY_PRINTERS[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "logging">} */
/** @type {DefineStatsPrinterContext<"logging">} */
(ctx),
stats
)
@ -1628,9 +1666,10 @@ class DefaultStatsPrinterPlugin {
stats.hooks.print
.for(key)
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
MODULE_TRACE_DEPENDENCY_PRINTERS[key](
/** @type {Record<string, ModuleSimplePrinter<KnownStatsModuleTraceDependency[keyof KnownStatsModuleTraceDependency], "type" | "compilation" | "moduleTraceDependency">>} */
(MODULE_TRACE_DEPENDENCY_PRINTERS)[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleTraceDependency">} */
/** @type {DefineStatsPrinterContext<"moduleTraceDependency">} */
(ctx),
stats
)
@ -1641,9 +1680,10 @@ class DefaultStatsPrinterPlugin {
stats.hooks.print
.for(key)
.tap("DefaultStatsPrinterPlugin", (obj, ctx) =>
MODULE_TRACE_ITEM_PRINTERS[key](
/** @type {Record<string, ModuleSimplePrinter<KnownStatsModuleTraceItem[keyof KnownStatsModuleTraceItem], "type" | "compilation" | "moduleTraceItem">>} */
(MODULE_TRACE_ITEM_PRINTERS)[key](
obj,
/** @type {Required<KnownStatsPrinterColorFn> & Required<KnownStatsPrinterFormatters> & WithRequired<StatsPrinterContext, "type" | "compilation" | "moduleTraceItem">} */
/** @type {DefineStatsPrinterContext<"moduleTraceItem">} */
(ctx),
stats
)

View File

@ -14,9 +14,9 @@ const smartGrouping = require("../util/smartGrouping");
/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../util/comparators").Comparator<any>} Comparator */
/** @typedef {import("../util/comparators").Comparator<TODO>} Comparator */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("../util/smartGrouping").GroupConfig<any, object>} GroupConfig */
/** @typedef {import("../util/smartGrouping").GroupConfig<TODO, EXPECTED_OBJECT>} GroupConfig */
/**
* @typedef {object} KnownStatsFactoryContext
@ -31,7 +31,7 @@ const smartGrouping = require("../util/smartGrouping");
* @property {(compilation: Compilation) => WebpackError[]} cachedGetWarnings
*/
/** @typedef {Record<string, any> & KnownStatsFactoryContext} StatsFactoryContext */
/** @typedef {KnownStatsFactoryContext & Record<string, EXPECTED_ANY>} StatsFactoryContext */
/** @typedef {any} CreatedObject */
/** @typedef {any} FactoryData */

View File

@ -57,8 +57,8 @@ const { HookMap, SyncWaterfallHook, SyncBailHook } = require("tapable");
/**
* @typedef {object} KnownStatsPrinterFormatters
* @property {(file: string, oversize?: boolean) => string=} formatFilename
* @property {(id: string) => string=} formatModuleId
* @property {(id: string, direction?: "parent"|"child"|"sibling") => string=} formatChunkId
* @property {(id: string | number) => string=} formatModuleId
* @property {(id: string | number, direction?: "parent" | "child" | "sibling") => string=} formatChunkId
* @property {(size: number) => string=} formatSize
* @property {(size: string) => string=} formatLayer
* @property {(dateTime: number) => string=} formatDateTime
@ -67,7 +67,7 @@ const { HookMap, SyncWaterfallHook, SyncBailHook } = require("tapable");
* @property {(message: string) => string=} formatError
*/
/** @typedef {Record<string, EXPECTED_ANY> & KnownStatsPrinterColorFn & KnownStatsPrinterFormatters & KnownStatsPrinterContext} StatsPrinterContext */
/** @typedef {KnownStatsPrinterColorFn & KnownStatsPrinterFormatters & KnownStatsPrinterContext & Record<string, EXPECTED_ANY>} StatsPrinterContext */
/** @typedef {TODO} PrintObject */
/**

View File

@ -8,12 +8,13 @@
/**
* @template T
* @template V
* @typedef {Map<object, WeakTupleMap<T[], V>>} M
* @typedef {Map<EXPECTED_ANY, WeakTupleMap<T[], V>>} M
*/
/**
* @template T
* @template V
* @typedef {WeakMap<object, WeakTupleMap<T[], V>>} W
* @typedef {WeakMap<EXPECTED_OBJECT, WeakTupleMap<T[], V>>} W
*/
/**

View File

@ -322,7 +322,7 @@ class TwoKeyWeakMap {
}
}
/** @type {TwoKeyWeakMap<Comparator<any>, Comparator<any>, Comparator<any>>}} */
/** @type {TwoKeyWeakMap<Comparator<EXPECTED_ANY>, Comparator<EXPECTED_ANY>, Comparator<EXPECTED_ANY>>}} */
const concatComparatorsCache = new TwoKeyWeakMap();
/**
@ -398,7 +398,7 @@ const compareSelect = (getter, comparator) => {
};
module.exports.compareSelect = compareSelect;
/** @type {WeakMap<Comparator<any>, Comparator<Iterable<any>>>} */
/** @type {WeakMap<Comparator<EXPECTED_ANY>, Comparator<Iterable<EXPECTED_ANY>>>} */
const compareIteratorsCache = new WeakMap();
/**

View File

@ -63,8 +63,8 @@ const path = require("path");
/** @typedef {string | number | boolean | null} JsonPrimitive */
/** @typedef {JsonValue[]} JsonArray */
/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */
/** @typedef {{[Key in string]: JsonValue} & {[Key in string]?: JsonValue | undefined}} JsonObject */
/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */
/** @typedef {(err: NodeJS.ErrnoException | null) => void} NoParamCallback */
/** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */

View File

@ -0,0 +1 @@
null

View File

@ -0,0 +1,5 @@
it("should work", () => {
const data = require('./data.json');
expect(data).toBe(null);
});

View File

@ -0,0 +1,4 @@
/** @type {import("../../../../").Configuration} */
module.exports = {
mode: "production"
};

View File

@ -0,0 +1 @@
"string"

View File

@ -0,0 +1,5 @@
it("should work", () => {
const data = require('./data.json');
expect(data).toBe("string");
});

View File

@ -0,0 +1,4 @@
/** @type {import("../../../../").Configuration} */
module.exports = {
mode: "production"
};

View File

@ -17,7 +17,7 @@ const rawSerializer = new Serializer([new FileMiddleware(fs)]);
const lazySizes = [];
/**
* @param {Array<any>} data data
* @param {(Buffer | (() => Promise<Buffer[]>))[]} data data
* @returns {Promise<SizeInfo>} size info
*/
const captureSize = async data => {
@ -43,7 +43,7 @@ const ESCAPE_END_OBJECT = true;
const ESCAPE_UNDEFINED = false;
/**
* @param {Array<any>} data data
* @param {Array<EXPECTED_ANY>} data data
* @param {string} indent indent
* @returns {Promise<void>} promise
*/

118
types.d.ts vendored
View File

@ -86,10 +86,14 @@ import {
YieldExpression
} from "estree";
import { IncomingMessage, ServerOptions } from "http";
import { JSONSchema4, JSONSchema6, JSONSchema7 } from "json-schema";
import { ListenOptions, Server } from "net";
import { validate as validateFunction } from "schema-utils";
import { default as ValidationError } from "schema-utils/declarations/ValidationError";
import { ValidationErrorConfiguration } from "schema-utils/declarations/validate";
import {
Extend,
ValidationErrorConfiguration
} from "schema-utils/declarations/validate";
import {
AsArray,
AsyncParallelHook,
@ -244,7 +248,7 @@ declare interface ArgumentConfig {
path: string;
multiple: boolean;
type: "string" | "number" | "boolean" | "path" | "enum" | "RegExp" | "reset";
values?: any[];
values?: EnumValue[];
}
type ArrayBufferLike = ArrayBuffer | SharedArrayBuffer;
type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
@ -4180,6 +4184,16 @@ declare abstract class Entrypoint extends ChunkGroup {
*/
getEntrypointChunk(): Chunk;
}
type EnumValue =
| null
| string
| number
| boolean
| EnumValueObject
| EnumValue[];
declare interface EnumValueObject {
[index: string]: EnumValue;
}
/**
* The abilities of the environment where the webpack generated code should run.
@ -7763,6 +7777,7 @@ declare interface KnownStatsError {
moduleTrace?: StatsModuleTraceItem[];
details?: string;
stack?: string;
compilerPath?: string;
}
declare interface KnownStatsFactoryContext {
type: string;
@ -7887,9 +7902,9 @@ declare interface KnownStatsPrinterContext {
}
declare interface KnownStatsPrinterFormatters {
formatFilename?: (file: string, oversize?: boolean) => string;
formatModuleId?: (id: string) => string;
formatModuleId?: (id: string | number) => string;
formatChunkId?: (
id: string,
id: string | number,
direction?: "parent" | "child" | "sibling"
) => string;
formatSize?: (size: number) => string;
@ -8321,7 +8336,7 @@ declare interface LoaderDefinitionFunction<
}
declare interface LoaderItem {
loader: string;
options: any;
options?: null | string | Record<string, any>;
ident: null | string;
type: null | string;
}
@ -9292,7 +9307,7 @@ type ModuleInfo = ConcatenatedModuleInfo | ExternalModuleInfo;
declare interface ModuleMemCachesItem {
buildInfo: BuildInfo;
references?: WeakMap<Dependency, Module>;
memCache: WeakTupleMap<any, any>;
memCache: WeakTupleMap<Module[], string>;
}
/**
@ -9801,7 +9816,7 @@ declare class NormalModule extends Module {
generator?: Generator;
generatorOptions?: GeneratorOptions;
resource: string;
resourceResolveData?: Record<string, any>;
resourceResolveData: any;
matchResource?: string;
loaders: LoaderItem[];
error: null | WebpackError;
@ -9854,10 +9869,7 @@ declare interface NormalModuleCompilationHooks {
>
>;
processResult: SyncWaterfallHook<
[
[string | Buffer, string | SourceMapSource, Record<string, any>],
NormalModule
]
[[string | Buffer, string | SourceMapSource, PreparsedAst], NormalModule]
>;
needBuild: AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>;
}
@ -9900,7 +9912,7 @@ declare interface NormalModuleCreateData {
/**
* resource resolve data
*/
resourceResolveData?: Record<string, any>;
resourceResolveData?: any;
/**
* context directory for resolving
@ -11352,7 +11364,7 @@ declare interface ParserStateBase {
current: NormalModule;
module: NormalModule;
compilation: Compilation;
options: { [index: string]: any };
options: WebpackOptionsNormalized;
}
declare interface PathData {
chunkGraph?: ChunkGraph;
@ -11502,7 +11514,7 @@ declare interface Problem {
type: ProblemType;
path: string;
argument: string;
value?: any;
value?: string | number | boolean | RegExp;
index?: number;
expected?: string;
}
@ -14712,12 +14724,12 @@ declare class Stats {
toJson(options?: string | boolean | StatsOptions): StatsCompilation;
toString(options?: string | boolean | StatsOptions): string;
}
type StatsAsset = Record<string, any> & KnownStatsAsset;
type StatsChunk = Record<string, any> & KnownStatsChunk;
type StatsChunkGroup = Record<string, any> & KnownStatsChunkGroup;
type StatsChunkOrigin = Record<string, any> & KnownStatsChunkOrigin;
type StatsCompilation = Record<string, any> & KnownStatsCompilation;
type StatsError = Record<string, any> & KnownStatsError;
type StatsAsset = KnownStatsAsset & Record<string, any>;
type StatsChunk = KnownStatsChunk & Record<string, any>;
type StatsChunkGroup = KnownStatsChunkGroup & Record<string, any>;
type StatsChunkOrigin = KnownStatsChunkOrigin & Record<string, any>;
type StatsCompilation = KnownStatsCompilation & Record<string, any>;
type StatsError = KnownStatsError & Record<string, any>;
declare abstract class StatsFactory {
hooks: StatsFactoryHooks;
create(
@ -14726,7 +14738,7 @@ declare abstract class StatsFactory {
baseContext: Omit<StatsFactoryContext, "type">
): any;
}
type StatsFactoryContext = Record<string, any> & KnownStatsFactoryContext;
type StatsFactoryContext = KnownStatsFactoryContext & Record<string, any>;
declare interface StatsFactoryHooks {
extract: HookMap<
SyncBailHook<[ObjectForExtract, any, StatsFactoryContext], void>
@ -14762,14 +14774,14 @@ declare interface StatsFactoryHooks {
SyncBailHook<[any, StatsFactoryContext], void | StatsFactory>
>;
}
type StatsLogging = Record<string, any> & KnownStatsLogging;
type StatsLoggingEntry = Record<string, any> & KnownStatsLoggingEntry;
type StatsModule = Record<string, any> & KnownStatsModule;
type StatsModuleIssuer = Record<string, any> & KnownStatsModuleIssuer;
type StatsModuleReason = Record<string, any> & KnownStatsModuleReason;
type StatsModuleTraceDependency = Record<string, any> &
KnownStatsModuleTraceDependency;
type StatsModuleTraceItem = Record<string, any> & KnownStatsModuleTraceItem;
type StatsLogging = KnownStatsLogging & Record<string, any>;
type StatsLoggingEntry = KnownStatsLoggingEntry & Record<string, any>;
type StatsModule = KnownStatsModule & Record<string, any>;
type StatsModuleIssuer = KnownStatsModuleIssuer & Record<string, any>;
type StatsModuleReason = KnownStatsModuleReason & Record<string, any>;
type StatsModuleTraceDependency = KnownStatsModuleTraceDependency &
Record<string, any>;
type StatsModuleTraceItem = KnownStatsModuleTraceItem & Record<string, any>;
/**
* Stats options object.
@ -15237,11 +15249,11 @@ declare abstract class StatsPrinter {
hooks: StatsPrintHooks;
print(type: string, object?: any, baseContext?: StatsPrinterContext): string;
}
type StatsPrinterContext = Record<string, any> &
KnownStatsPrinterColorFn &
type StatsPrinterContext = KnownStatsPrinterColorFn &
KnownStatsPrinterFormatters &
KnownStatsPrinterContext;
type StatsProfile = Record<string, any> & KnownStatsProfile;
KnownStatsPrinterContext &
Record<string, any>;
type StatsProfile = KnownStatsProfile & Record<string, any>;
type StatsValue =
| boolean
| StatsOptions
@ -16064,7 +16076,45 @@ declare namespace exports {
) => void;
export const version: string;
export namespace cli {
export let getArguments: (schema?: any) => Flags;
export let getArguments: (
schema?:
| (JSONSchema4 &
Extend & {
absolutePath: boolean;
instanceof: string;
cli: {
helper?: boolean;
exclude?: boolean;
description?: string;
negatedDescription?: string;
resetDescription?: string;
};
})
| (JSONSchema6 &
Extend & {
absolutePath: boolean;
instanceof: string;
cli: {
helper?: boolean;
exclude?: boolean;
description?: string;
negatedDescription?: string;
resetDescription?: string;
};
})
| (JSONSchema7 &
Extend & {
absolutePath: boolean;
instanceof: string;
cli: {
helper?: boolean;
exclude?: boolean;
description?: string;
negatedDescription?: string;
resetDescription?: string;
};
})
) => Flags;
export let processArguments: (
args: Flags,
config: any,