Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: types for assets and json modules plus plugins #17262

Merged
merged 2 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/CacheFacade.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ class MultiItemCache {
* @returns {Promise<T>} promise with the data
*/
getPromise() {
/**
* @param {number} i index
* @returns {Promise<T>} promise with the data
*/
const next = i => {
return this._items[i].getPromise().then(result => {
if (result !== undefined) return result;
Expand Down
6 changes: 5 additions & 1 deletion lib/ChunkGroup.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ class ChunkGroup {
}

/**
* @returns {Array} an array containing the blocks
* @returns {Array<AsyncDependenciesBlock>} an array containing the blocks
*/
getBlocks() {
return this._blocks.getFromCache(getArray);
Expand All @@ -363,6 +363,10 @@ class ChunkGroup {
return this._blocks.size;
}

/**
* @param {AsyncDependenciesBlock} block block
* @returns {boolean} true, if block exists
*/
hasBlock(block) {
return this._blocks.has(block);
}
Expand Down
37 changes: 30 additions & 7 deletions lib/CleanPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
directories,
10,
(directory, callback) => {
fs.readdir(join(fs, outputPath, directory), (err, entries) => {
/** @type {NonNullable<OutputFileSystem["readdir"]>} */
(fs.readdir)(join(fs, outputPath, directory), (err, entries) => {
if (err) {
if (err.code === "ENOENT") return callback();
if (err.code === "ENOTDIR") {
Expand Down Expand Up @@ -128,7 +129,8 @@ const getDiffToOldAssets = (currentAssets, oldAssets) => {
*/
const doStat = (fs, filename, callback) => {
if ("lstat" in fs) {
fs.lstat(filename, callback);
/** @type {NonNullable<OutputFileSystem["lstat"]>} */
(fs.lstat)(filename, callback);
} else {
fs.stat(filename, callback);
}
Expand All @@ -145,6 +147,9 @@ const doStat = (fs, filename, callback) => {
* @returns {void}
*/
const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
/**
* @param {string} msg message
*/
const log = msg => {
if (dry) {
logger.info(msg);
Expand All @@ -165,6 +170,10 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
jobs,
10,
({ type, filename, parent }, push, callback) => {
/**
* @param {Error & { code?: string }} err error
* @returns {void}
*/
const handleError = err => {
if (err.code === "ENOENT") {
log(`${filename} was removed during cleaning by something else`);
Expand Down Expand Up @@ -195,7 +204,9 @@ const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
});
return callback();
}
fs.readdir(path, (err, entries) => {

/** @type {NonNullable<OutputFileSystem["readdir"]>} */
(fs.readdir)(path, (err, entries) => {
if (err) return handleError(err);
/** @type {Job} */
const deleteJob = {
Expand Down Expand Up @@ -317,9 +328,17 @@ class CleanPlugin {
typeof keep === "function"
? keep
: typeof keep === "string"
? path => path.startsWith(keep)
? /**
* @param {string} path path
* @returns {boolean} true, if the path should be kept
*/
path => path.startsWith(keep)
: typeof keep === "object" && keep.test
? path => keep.test(path)
? /**
* @param {string} path path
* @returns {boolean} true, if the path should be kept
*/
path => keep.test(path)
: () => false;

// We assume that no external modification happens while the compiler is active
Expand Down Expand Up @@ -371,14 +390,18 @@ class CleanPlugin {

const outputPath = compilation.getPath(compiler.outputPath, {});

/**
* @param {string} path path
* @returns {boolean} true, if needs to be kept
*/
const isKept = path => {
const result = hooks.keep.call(path);
if (result !== undefined) return result;
return keepFn(path);
};

/**
* @param {Error=} err err
* @param {(Error | null)=} err err
* @param {Set<string>=} diff diff
*/
const diffCallback = (err, diff) => {
Expand All @@ -392,7 +415,7 @@ class CleanPlugin {
outputPath,
dry,
logger,
diff,
/** @type {Set<string>} */ (diff),
isKept,
(err, keptAssets) => {
if (err) {
Expand Down
2 changes: 1 addition & 1 deletion lib/Compilation.js
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]),
/** @type {SyncHook<[Iterable<Chunk>, Iterable<Module>]>} */
afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]),
/** @type {SyncBailHook<[], boolean>} */
/** @type {SyncBailHook<[], boolean | undefined>} */
shouldRecord: new SyncBailHook([]),

/** @type {SyncHook<[Chunk, Set<string>, RuntimeRequirementsContext]>} */
Expand Down
2 changes: 1 addition & 1 deletion lib/Compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class Compiler {
/** @type {SyncHook<[]>} */
initialize: new SyncHook([]),

/** @type {SyncBailHook<[Compilation], boolean>} */
/** @type {SyncBailHook<[Compilation], boolean | undefined>} */
shouldEmit: new SyncBailHook(["compilation"]),
/** @type {AsyncSeriesHook<[Stats]>} */
done: new AsyncSeriesHook(["stats"]),
Expand Down
6 changes: 4 additions & 2 deletions lib/NormalModuleReplacementPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ class NormalModuleReplacementPlugin {
});
nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
const createData = result.createData;
if (resourceRegExp.test(createData.resource)) {
if (
resourceRegExp.test(/** @type {string} */ (createData.resource))
) {
if (typeof newResource === "function") {
newResource(result);
} else {
Expand All @@ -56,7 +58,7 @@ class NormalModuleReplacementPlugin {
} else {
createData.resource = join(
fs,
dirname(fs, createData.resource),
dirname(fs, /** @type {string} */ (createData.resource)),
newResource
);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/SelfModuleFactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class SelfModuleFactory {

/**
* @param {ModuleFactoryCreateData} data data object
* @param {function(Error=, ModuleFactoryResult=): void} callback callback
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
Expand Down
2 changes: 1 addition & 1 deletion lib/Template.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ class Template {
* @param {Module[]} modules modules to render (should be ordered by identifier)
* @param {function(Module): Source} renderModule function to render a module
* @param {string=} prefix applying prefix strings
* @returns {Source} rendered chunk modules in a Source object
* @returns {Source | null} rendered chunk modules in a Source object or null if no modules
*/
static renderChunkModules(renderContext, modules, renderModule, prefix = "") {
const { chunkGraph } = renderContext;
Expand Down
4 changes: 4 additions & 0 deletions lib/UseStrictPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {
const ConstDependency = require("./dependencies/ConstDependency");

/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */

const PLUGIN_NAME = "UseStrictPlugin";

Expand All @@ -26,6 +27,9 @@ class UseStrictPlugin {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
/**
* @param {JavascriptParser} parser the parser
*/
const handler = parser => {
parser.hooks.program.tap(PLUGIN_NAME, ast => {
const firstNode = ast.body[0];
Expand Down
7 changes: 7 additions & 0 deletions lib/WarnDeprecatedOptionPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ class WarnDeprecatedOptionPlugin {
}

class DeprecatedOptionWarning extends WebpackError {
/**
* Create an instance deprecated option warning
*
* @param {string} option the target option
* @param {string | number} value the deprecated option value
* @param {string} suggestion the suggestion replacement
*/
constructor(option, value, suggestion) {
super();

Expand Down
4 changes: 4 additions & 0 deletions lib/WatchIgnorePlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ class IgnoringWatchFileSystem {
watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) {
files = Array.from(files);
dirs = Array.from(dirs);
/**
* @param {string} path path to check
* @returns {boolean} true, if path is ignored
*/
const ignored = path =>
this.paths.some(p =>
p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0
Expand Down
9 changes: 7 additions & 2 deletions lib/asset/AssetGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ const encodeDataUri = (encoding, source) => {
return encodedContent;
};

/**
* @param {string} encoding encoding
* @param {string} content content
* @returns {Buffer} decoded content
*/
const decodeDataUriContent = (encoding, content) => {
const isBase64 = encoding === "base64";

Expand Down Expand Up @@ -230,10 +235,10 @@ class AssetGenerator extends Generator {
) {
switch (type) {
case ASSET_MODULE_TYPE:
return module.originalSource();
return /** @type {Source} */ (module.originalSource());
default: {
let content;
const originalSource = module.originalSource();
const originalSource = /** @type {Source} */ (module.originalSource());
if (module.buildInfo.dataUrl) {
let encodedSource;
if (typeof this.dataUrlOptions === "function") {
Expand Down
8 changes: 7 additions & 1 deletion lib/asset/AssetModulesPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ const memoize = require("../util/memoize");
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */

/**
* @param {string} name name of definitions
* @returns {TODO} definition
*/
const getSchema = name => {
const { definitions } = require("../../schemas/WebpackOptions.json");
return {
Expand Down Expand Up @@ -204,7 +208,9 @@ class AssetModulesPlugin {
codeGenResult.data.get("fullContentHash")
});
} catch (e) {
e.message += `\nduring rendering of asset ${module.identifier()}`;
/** @type {Error} */ (
e
).message += `\nduring rendering of asset ${module.identifier()}`;
throw e;
}
}
Expand Down
5 changes: 4 additions & 1 deletion lib/asset/AssetParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

const Parser = require("../Parser");

/** @typedef {import("../../declarations/WebpackOptions").AssetParserDataUrlOptions} AssetParserDataUrlOptions */
/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
Expand Down Expand Up @@ -45,7 +46,9 @@ class AssetParser extends Parser {
typeof this.dataUrlCondition === "object"
) {
state.module.buildInfo.dataUrl =
Buffer.byteLength(source) <= this.dataUrlCondition.maxSize;
Buffer.byteLength(source) <=
/** @type {NonNullable<AssetParserDataUrlOptions["maxSize"]>} */
(this.dataUrlCondition.maxSize);
} else {
throw new Error("Unexpected dataUrlCondition type");
}
Expand Down
8 changes: 5 additions & 3 deletions lib/asset/RawDataUrlModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ class RawDataUrlModule extends Module {
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
if (this.url === undefined) this.url = this.urlBuffer.toString();
if (this.url === undefined)
this.url = /** @type {Buffer} */ (this.urlBuffer).toString();
return Math.max(1, this.url.length);
}

Expand Down Expand Up @@ -102,7 +103,8 @@ class RawDataUrlModule extends Module {
* @returns {CodeGenerationResult} result
*/
codeGeneration(context) {
if (this.url === undefined) this.url = this.urlBuffer.toString();
if (this.url === undefined)
this.url = /** @type {Buffer} */ (this.urlBuffer).toString();
const sources = new Map();
sources.set(
"javascript",
Expand All @@ -121,7 +123,7 @@ class RawDataUrlModule extends Module {
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.urlBuffer);
hash.update(/** @type {Buffer} */ (this.urlBuffer));
super.updateHash(hash, context);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/async-modules/InferAsyncModulesPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class InferAsyncModulesPlugin {
c.isTargetActive(undefined)
)
) {
queue.add(originModule);
queue.add(/** @type {Module} */ (originModule));
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion lib/javascript/JavascriptModulesPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ class JavascriptModulesPlugin {
);

const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0;
/** @type {Set<Module> | undefined} */
let inlinedModules;
if (bootstrap.allowInlineStartup && hasEntryModules) {
inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk));
Expand Down Expand Up @@ -732,7 +733,9 @@ class JavascriptModulesPlugin {
const chunkModules = Template.renderChunkModules(
chunkRenderContext,
inlinedModules
? allModules.filter(m => !inlinedModules.has(m))
? allModules.filter(
m => !(/** @type {Set<Module>} */ (inlinedModules).has(m))
)
: allModules,
module => this.renderModule(module, chunkRenderContext, hooks, true),
prefix
Expand Down
12 changes: 7 additions & 5 deletions lib/json/JsonGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,14 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused)
return data;
const isArray = Array.isArray(data);
/** @type {RawJsonData} */
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 {any} */
/** @type {RawJsonData} */
let value;
if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) {
value = createObjectForExportsInfo(
Expand All @@ -62,8 +63,9 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
} else {
value = data[key];
}
const name = exportInfo.getUsedName(key, runtime);
reducedData[name] = value;

const name = /** @type {string} */ (exportInfo.getUsedName(key, runtime));
/** @type {Record<string, RawJsonData>} */ (reducedData)[name] = value;
}
if (isArray) {
let arrayLengthWhenUsed =
Expand Down Expand Up @@ -130,7 +132,7 @@ class JsonGenerator extends Generator {
module.buildInfo.jsonData &&
module.buildInfo.jsonData.get();
if (!data) return 0;
return stringifySafe(data).length + 10;
return /** @type {string} */ (stringifySafe(data)).length + 10;
}

/**
Expand Down Expand Up @@ -178,7 +180,7 @@ class JsonGenerator extends Generator {
? createObjectForExportsInfo(data, exportsInfo, runtime)
: data;
// Use JSON because JSON.parse() is much faster than JavaScript evaluation
const jsonStr = stringifySafe(finalJson);
const jsonStr = /** @type {string} */ (stringifySafe(finalJson));
const jsonExpr =
jsonStr.length > 20 && typeof finalJson === "object"
? `JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')`
Expand Down