refactor: code

This commit is contained in:
alexander.akait 2024-08-01 21:36:27 +03:00
parent b84d7956b5
commit 93743d233a
140 changed files with 1192 additions and 1279 deletions

View File

@ -214,24 +214,20 @@ module.exports = [
"unicorn/prefer-includes": "error",
"unicorn/no-zero-fractions": "error",
"unicorn/prefer-string-starts-ends-with": "error",
"unicorn/prefer-default-parameters": "error",
"unicorn/prefer-negative-index": "error",
"unicorn/prefer-ternary": ["error", "only-single-line"],
"unicorn/prefer-array-find": "error",
"unicorn/prefer-string-slice": "error",
"unicorn/no-lonely-if": "error",
"unicorn/no-hex-escape": "error",
"unicorn/escape-case": "error",
"unicorn/no-array-for-each": "error",
"unicorn/prefer-number-properties": "error",
"unicorn/prefer-regexp-test": "error",
"unicorn/prefer-native-coercion-functions": "error",
// TODO Enable
"unicorn/prefer-spread": "off",
"unicorn/prefer-string-slice": "off",
"unicorn/explicit-length-check": "off",
"unicorn/no-lonely-if": "off",
"unicorn/prefer-ternary": "off",
"unicorn/no-useless-undefined": "off",
"unicorn/no-hex-escape": "off",
"unicorn/escape-case": "off",
"unicorn/prefer-negative-index": "off",
"unicorn/no-array-for-each": "off",
"unicorn/prefer-number-properties": "off",
"unicorn/prefer-default-parameters": "off",
"unicorn/prefer-regexp-test": "off",
"unicorn/prefer-math-trunc": "off",
"unicorn/prefer-array-find": "off",
"unicorn/prefer-native-coercion-functions": "off",
"unicorn/no-useless-switch-case": "off"
"unicorn/prefer-spread": "off"
}
},
{
@ -362,7 +358,9 @@ module.exports = [
"prefer-template": "off",
"no-implicit-coercion": "off",
"func-style": "off",
"unicorn/prefer-includes": "off"
"unicorn/prefer-includes": "off",
"unicorn/no-useless-undefined": "off",
"unicorn/no-array-for-each": "off"
}
},
{

View File

@ -214,7 +214,7 @@ class APIPlugin {
* @param {JavascriptParser} parser the parser
*/
const handler = parser => {
Object.keys(REPLACEMENTS).forEach(key => {
for (const key of Object.keys(REPLACEMENTS)) {
const info = REPLACEMENTS[key];
parser.hooks.expression.for(key).tap(PLUGIN_NAME, expression => {
const dep = toConstantDependency(parser, info.expr, info.req);
@ -238,7 +238,7 @@ class APIPlugin {
.for(key)
.tap(PLUGIN_NAME, evaluateToString(info.type));
}
});
}
parser.hooks.expression
.for("__webpack_layer__")

View File

@ -45,6 +45,7 @@ class AutomaticPrefetchPlugin {
"AutomaticPrefetchPlugin",
(compilation, callback) => {
if (!lastModules) return callback();
// eslint-disable-next-line unicorn/no-array-for-each
asyncLib.forEach(
lastModules,
(m, callback) => {

View File

@ -37,7 +37,7 @@ const createModulesListMessage = (modules, moduleGraph) =>
let message = `* ${m.identifier()}`;
const validReasons = Array.from(
moduleGraph.getIncomingConnectionsByOriginModule(m).keys()
).filter(x => x);
).filter(Boolean);
if (validReasons.length > 0) {
message += `\n Used by ${validReasons.length} module(s), i. e.`;

View File

@ -766,7 +766,7 @@ class Chunk {
});
}
}
if (list.length === 0) return undefined;
if (list.length === 0) return;
list.sort((a, b) => {
const cmp =
/** @type {number} */ (b.order) - /** @type {number} */ (a.order);

View File

@ -700,7 +700,7 @@ class ChunkGraph {
const modulesWithSourceType = cgc.modules
.getFromUnorderedCache(cgc._modulesBySourceType)
.get(sourceType);
if (modulesWithSourceType === undefined) return undefined;
if (modulesWithSourceType === undefined) return;
modulesWithSourceType.sortWith(comparator);
return modulesWithSourceType;
}

View File

@ -570,7 +570,7 @@ class Compilation {
* @returns {FakeHook<Pick<AsyncSeriesHook<T>, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects
*/
const createProcessAssetsHook = (name, stage, getArgs, code) => {
if (!this._backCompat && code) return undefined;
if (!this._backCompat && code) return;
const errorMessage =
reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`;
@ -1208,10 +1208,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
trace
};
if (this.hooks.log.call(name, logEntry) === undefined) {
if (logEntry.type === LogType.profileEnd) {
if (typeof console.profileEnd === "function") {
console.profileEnd(`[${name}] ${logEntry.args[0]}`);
}
if (
logEntry.type === LogType.profileEnd &&
typeof console.profileEnd === "function"
) {
console.profileEnd(`[${name}] ${logEntry.args[0]}`);
}
if (logEntries === undefined) {
logEntries = this.logging.get(name);
@ -1221,10 +1222,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}
}
logEntries.push(logEntry);
if (logEntry.type === LogType.profile) {
if (typeof console.profile === "function") {
console.profile(`[${name}] ${logEntry.args[0]}`);
}
if (
logEntry.type === LogType.profile &&
typeof console.profile === "function"
) {
console.profile(`[${name}] ${logEntry.args[0]}`);
}
}
},
@ -1921,14 +1923,12 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
module,
originModule !== undefined ? originModule : null
);
if (module !== newModule) {
if (currentProfile !== undefined) {
const otherProfile = moduleGraph.getProfile(module);
if (otherProfile !== undefined) {
currentProfile.mergeInto(otherProfile);
} else {
moduleGraph.setProfile(module, currentProfile);
}
if (module !== newModule && currentProfile !== undefined) {
const otherProfile = moduleGraph.getProfile(module);
if (otherProfile !== undefined) {
currentProfile.mergeInto(otherProfile);
} else {
moduleGraph.setProfile(module, currentProfile);
}
}
@ -3340,9 +3340,9 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
(job, callback) => {
const { module } = job;
const { codeGenerationDependencies } = module;
if (codeGenerationDependencies !== undefined) {
if (
notCodeGeneratedModules === undefined ||
if (
codeGenerationDependencies !== undefined &&
(notCodeGeneratedModules === undefined ||
codeGenerationDependencies.some(dep => {
const referencedModule = /** @type {Module} */ (
moduleGraph.getModule(dep)
@ -3350,12 +3350,11 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
return /** @type {NotCodeGeneratedModules} */ (
notCodeGeneratedModules
).has(referencedModule);
})
) {
delayedJobs.push(job);
delayedModules.add(module);
return callback();
}
}))
) {
delayedJobs.push(job);
delayedModules.add(module);
return callback();
}
const { hash, runtime, runtimes } = job;
this._codeGenerationModule(
@ -3923,11 +3922,12 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
if (!module.hasReasons(this.moduleGraph, chunk.runtime)) {
this.removeReasonsOfDependencyBlock(module, module);
}
if (!module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph)) {
if (this.chunkGraph.isModuleInChunk(module, chunk)) {
this.chunkGraph.disconnectChunkAndModule(chunk, module);
this.removeChunkFromDependencies(module, chunk);
}
if (
!module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph) &&
this.chunkGraph.isModuleInChunk(module, chunk)
) {
this.chunkGraph.disconnectChunkAndModule(chunk, module);
this.removeChunkFromDependencies(module, chunk);
}
}
@ -4335,7 +4335,7 @@ This prevents using hashes of each other and should be avoided.`);
}
this.logger.timeAggregate("hashing: hash chunks");
};
otherChunks.forEach(processChunk);
for (const chunk of otherChunks) processChunk(chunk);
for (const chunk of runtimeChunks) processChunk(chunk);
if (errors.length > 0) {
errors.sort(compareSelect(err => err.module, compareModulesByIdentifier));
@ -4445,7 +4445,9 @@ This prevents using hashes of each other and should be avoided.`);
};
const entry = oldRelated[key];
if (Array.isArray(entry)) {
entry.forEach(remove);
for (const name of entry) {
remove(name);
}
} else if (entry) {
remove(entry);
}
@ -4469,7 +4471,9 @@ This prevents using hashes of each other and should be avoided.`);
};
const entry = newRelated[key];
if (Array.isArray(entry)) {
entry.forEach(add);
for (const name of entry) {
add(name);
}
} else if (entry) {
add(entry);
}
@ -4492,11 +4496,10 @@ This prevents using hashes of each other and should be avoided.`);
`Called Compilation.updateAsset for not existing filename ${file}`
);
}
if (typeof newSourceOrFunction === "function") {
this.assets[file] = newSourceOrFunction(this.assets[file]);
} else {
this.assets[file] = newSourceOrFunction;
}
this.assets[file] =
typeof newSourceOrFunction === "function"
? newSourceOrFunction(this.assets[file])
: newSourceOrFunction;
if (assetInfoUpdateOrFunction !== undefined) {
const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO;
if (typeof assetInfoUpdateOrFunction === "function") {
@ -4522,14 +4525,12 @@ This prevents using hashes of each other and should be avoided.`);
`Called Compilation.renameAsset for not existing filename ${file}`
);
}
if (this.assets[newFile]) {
if (!isSourceEqual(this.assets[file], source)) {
this.errors.push(
new WebpackError(
`Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content`
)
);
}
if (this.assets[newFile] && !isSourceEqual(this.assets[file], source)) {
this.errors.push(
new WebpackError(
`Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content`
)
);
}
const assetInfo = this.assetsInfo.get(file);
// Update related in all other assets
@ -4593,6 +4594,9 @@ This prevents using hashes of each other and should be avoided.`);
const related = assetInfo && assetInfo.related;
if (related) {
for (const key of Object.keys(related)) {
/**
* @param {string} file file
*/
const checkUsedAndDelete = file => {
if (!this._assetsRelatedIn.has(file)) {
this.deleteAsset(file);
@ -4600,7 +4604,9 @@ This prevents using hashes of each other and should be avoided.`);
};
const items = related[key];
if (Array.isArray(items)) {
items.forEach(checkUsedAndDelete);
for (const file of items) {
checkUsedAndDelete(file);
}
} else if (items) {
checkUsedAndDelete(items);
}
@ -4634,8 +4640,7 @@ This prevents using hashes of each other and should be avoided.`);
* @returns {Readonly<Asset> | undefined} the asset or undefined when not found
*/
getAsset(name) {
if (!Object.prototype.hasOwnProperty.call(this.assets, name))
return undefined;
if (!Object.prototype.hasOwnProperty.call(this.assets, name)) return;
return {
name,
source: this.assets[name],
@ -4718,6 +4723,7 @@ This prevents using hashes of each other and should be avoided.`);
);
return callback();
}
// eslint-disable-next-line unicorn/no-array-for-each
asyncLib.forEach(
manifest,
(fileManifest, callback) => {
@ -5220,9 +5226,9 @@ This prevents using hashes of each other and should be avoided.`);
},
require: __webpack_require__
};
interceptModuleExecution.forEach(handler =>
handler(execOptions)
);
for (const handler of interceptModuleExecution) {
handler(execOptions);
}
const module = moduleArgument.module;
this.buildTimeExecutedModules.add(module);
const moduleObject = execOptions.module;

View File

@ -353,10 +353,11 @@ class Compiler {
);
}
}
if (this.hooks.infrastructureLog.call(name, type, args) === undefined) {
if (this.infrastructureLogger !== undefined) {
this.infrastructureLogger(name, type, args);
}
if (
this.hooks.infrastructureLog.call(name, type, args) === undefined &&
this.infrastructureLogger !== undefined
) {
this.infrastructureLogger(name, type, args);
}
},
childName => {
@ -977,7 +978,7 @@ ${other}`);
}
};
if (targetFile.match(/\/|\\/)) {
if (/\/|\\/.test(targetFile)) {
const fs = /** @type {OutputFileSystem} */ (this.outputFileSystem);
const dir = dirname(fs, join(fs, outputPath, targetFile));
mkdirp(fs, dir, writeOut);
@ -1220,11 +1221,10 @@ ${other}`);
"invalid",
"done",
"thisCompilation"
].includes(name)
].includes(name) &&
childCompiler.hooks[name]
) {
if (childCompiler.hooks[name]) {
childCompiler.hooks[name].taps = this.hooks[name].taps.slice();
}
childCompiler.hooks[name].taps = this.hooks[name].taps.slice();
}
}

View File

@ -207,21 +207,13 @@ class ConstPlugin {
// NOTE: When code runs in strict mode, `var` declarations
// are hoisted but `function` declarations don't.
//
let declarations;
if (parser.scope.isStrict) {
// If the code runs in strict mode, variable declarations
// using `var` must be hoisted.
declarations = getHoistedDeclarations(branchToRemove, false);
} else {
// Otherwise, collect all hoisted declaration.
declarations = getHoistedDeclarations(branchToRemove, true);
}
let replacement;
if (declarations.length > 0) {
replacement = `{ var ${declarations.join(", ")}; }`;
} else {
replacement = "{}";
}
const declarations = parser.scope.isStrict
? getHoistedDeclarations(branchToRemove, false)
: getHoistedDeclarations(branchToRemove, true);
const replacement =
declarations.length > 0
? `{ var ${declarations.join(", ")}; }`
: "{}";
const dep = new ConstDependency(
replacement,
/** @type {Range} */ (branchToRemove.range)

View File

@ -1124,10 +1124,12 @@ module.exports = webpackEmptyAsyncContext;`;
}
return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
}
if (asyncMode === "weak") {
if (this.dependencies && this.dependencies.length > 0) {
return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
}
if (
asyncMode === "weak" &&
this.dependencies &&
this.dependencies.length > 0
) {
return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
}
if (this.dependencies && this.dependencies.length > 0) {
return this.getSyncSource(this.dependencies, id, chunkGraph);

View File

@ -142,11 +142,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
.slice(i)
.replace(/!+$/, "")
.replace(/!!+/g, "!");
if (loadersRequest === "") {
loaders = [];
} else {
loaders = loadersRequest.split("!");
}
loaders = loadersRequest === "" ? [] : loadersRequest.split("!");
resource = request.slice(idx + 1);
} else {
loaders = [];

View File

@ -120,7 +120,7 @@ class RuntimeValue {
* @returns {Set<string> | undefined} used keys
*/
function getObjKeys(properties) {
if (!properties) return undefined;
if (!properties) return;
return new Set([...properties].map(p => p.id));
}
@ -166,8 +166,7 @@ const stringifyObj = (
} else {
let keys = Object.keys(obj);
if (objKeys) {
if (objKeys.size === 0) keys = [];
else keys = keys.filter(k => objKeys.has(k));
keys = objKeys.size === 0 ? [] : keys.filter(k => objKeys.has(k));
}
code = `{${keys
.map(key => {
@ -301,7 +300,7 @@ const toCacheVersion = code => {
key,
value: toCacheVersion(/** @type {Record<string, any>} */ (code)[key])
}));
if (items.some(({ value }) => value === undefined)) return undefined;
if (items.some(({ value }) => value === undefined)) return;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
}
if (typeof code === "bigint") {
@ -404,7 +403,7 @@ class DefinePlugin {
* @returns {void}
*/
const walkDefinitions = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
if (
code &&
@ -417,11 +416,11 @@ class DefinePlugin {
`${prefix + key}.`
);
applyObjectDefine(prefix + key, code);
return;
continue;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
});
}
};
/**
@ -432,13 +431,13 @@ class DefinePlugin {
*/
const applyDefineKey = (prefix, key) => {
const splittedKey = key.split(".");
splittedKey.slice(1).forEach((_, i) => {
for (const [i, _] of splittedKey.slice(1).entries()) {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
addValueDependency(key);
return true;
});
});
}
};
/**
@ -647,7 +646,7 @@ class DefinePlugin {
* @returns {void}
*/
const walkDefinitionsForValues = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
const version = toCacheVersion(code);
const name = VALUE_DEP_PREFIX + prefix + key;
@ -674,7 +673,7 @@ class DefinePlugin {
`${prefix + key}.`
);
}
});
}
};
walkDefinitionsForValues(definitions, "");

View File

@ -76,17 +76,15 @@ class DelegatedModuleFactoryPlugin {
"DelegatedModuleFactoryPlugin",
module => {
const request = module.libIdent(this.options);
if (request) {
if (request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(
this.options.source,
resolved,
this.options.type,
request,
module
);
}
if (request && request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(
this.options.source,
resolved,
this.options.type,
request,
module
);
}
return module;
}

View File

@ -163,16 +163,8 @@ class Dependency {
this._locEL = 0;
this._locEC = 0;
}
if ("index" in loc) {
this._locI = loc.index;
} else {
this._locI = undefined;
}
if ("name" in loc) {
this._locN = loc.name;
} else {
this._locN = undefined;
}
this._locI = "index" in loc ? loc.index : undefined;
this._locN = "name" in loc ? loc.name : undefined;
this._loc = loc;
}

View File

@ -48,9 +48,9 @@ const cutOffMultilineMessage = (stack, message) => {
/** @type {string[]} */
const result = [];
stackSplitByLines.forEach((line, idx) => {
for (const [idx, line] of stackSplitByLines.entries()) {
if (!line.includes(messageSplitByLines[idx])) result.push(line);
});
}
return result.join("\n");
};

View File

@ -261,7 +261,7 @@ class ExportsInfo {
getReadOnlyExportInfoRecursive(name) {
const exportInfo = this.getReadOnlyExportInfo(name[0]);
if (name.length === 1) return exportInfo;
if (!exportInfo.exportsInfo) return undefined;
if (!exportInfo.exportsInfo) return;
return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1));
}
@ -272,7 +272,7 @@ class ExportsInfo {
getNestedExportsInfo(name) {
if (Array.isArray(name) && name.length > 0) {
const info = this.getReadOnlyExportInfo(name[0]);
if (!info.exportsInfo) return undefined;
if (!info.exportsInfo) return;
return info.exportsInfo.getNestedExportsInfo(name.slice(1));
}
return this;
@ -1170,14 +1170,13 @@ class ExportInfo {
if (!this._usedInRuntime.has(runtime)) {
return false;
}
} else if (runtime !== undefined) {
if (
Array.from(runtime).every(
runtime => !this._usedInRuntime.has(runtime)
)
) {
return false;
}
} else if (
runtime !== undefined &&
Array.from(runtime).every(
runtime => !this._usedInRuntime.has(runtime)
)
) {
return false;
}
}
}
@ -1209,7 +1208,7 @@ class ExportInfo {
getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) {
if (this.terminalBinding) return this;
const target = this.getTarget(moduleGraph, resolveTargetFilter);
if (!target) return undefined;
if (!target) return;
const exportsInfo = moduleGraph.getExportsInfo(target.module);
if (!target.export) return exportsInfo;
return exportsInfo.getReadOnlyExportInfoRecursive(target.export);
@ -1258,9 +1257,9 @@ class ExportInfo {
* @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid
*/
_findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) {
if (!this._target || this._target.size === 0) return undefined;
if (!this._target || this._target.size === 0) return;
const rawTarget = this._getMaxTarget().values().next().value;
if (!rawTarget) return undefined;
if (!rawTarget) return;
/** @type {{ module: Module, export: string[] | undefined }} */
let target = {
module: rawTarget.connection.module,
@ -1297,7 +1296,7 @@ class ExportInfo {
*/
getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) {
const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined);
if (result === CIRCULAR) return undefined;
if (result === CIRCULAR) return;
return result;
}
@ -1363,26 +1362,26 @@ class ExportInfo {
}
};
if (!this._target || this._target.size === 0) return undefined;
if (!this._target || this._target.size === 0) return;
if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR;
const newAlreadyVisited = new Set(alreadyVisited);
newAlreadyVisited.add(this);
const values = this._getMaxTarget().values();
const target = resolveTarget(values.next().value, newAlreadyVisited);
if (target === CIRCULAR) return CIRCULAR;
if (target === null) return undefined;
if (target === null) return;
let result = values.next();
while (!result.done) {
const t = resolveTarget(result.value, newAlreadyVisited);
if (t === CIRCULAR) return CIRCULAR;
if (t === null) return undefined;
if (t.module !== target.module) return undefined;
if (!t.export !== !target.export) return undefined;
if (t === null) return;
if (t.module !== target.module) return;
if (!t.export !== !target.export) return;
if (
target.export &&
!equals(/** @type {ArrayLike<string>} */ (t.export), target.export)
)
return undefined;
return;
result = values.next();
}
return target;
@ -1397,14 +1396,14 @@ class ExportInfo {
*/
moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) {
const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined);
if (target === CIRCULAR) return undefined;
if (!target) return undefined;
if (target === CIRCULAR) return;
if (!target) return;
const originalTarget = this._getMaxTarget().values().next().value;
if (
originalTarget.connection === target.connection &&
originalTarget.export === target.export
) {
return undefined;
return;
}
this._target.clear();
this._target.set(undefined, {

View File

@ -210,7 +210,7 @@ const getSourceForImportExternal = (
*/
const importAssertionReplacer = (key, value) => {
if (key === "_isLegacyAssert") {
return undefined;
return;
}
return value;

View File

@ -84,12 +84,7 @@ class ExternalModuleFactoryPlugin {
return callback();
}
/** @type {string | string[] | Record<string, string|string[]>} */
let externalConfig;
if (value === true) {
externalConfig = dependency.request;
} else {
externalConfig = value;
}
let externalConfig = value === true ? dependency.request : value;
// When no explicit type is specified, extract it from the externalConfig
if (type === undefined) {
if (

View File

@ -523,7 +523,7 @@ class SnapshotOptimization {
getStatisticMessage() {
const total = this._statItemsShared + this._statItemsUnshared;
if (total === 0) return undefined;
if (total === 0) return;
return `${
this._statItemsShared && Math.round((this._statItemsShared * 100) / total)
}% (${this._statItemsShared}/${total}) entries shared via ${
@ -553,7 +553,9 @@ class SnapshotOptimization {
*/
const increaseSharedAndStoreOptimizationEntry = entry => {
if (entry.children !== undefined) {
entry.children.forEach(increaseSharedAndStoreOptimizationEntry);
for (const child of entry.children) {
increaseSharedAndStoreOptimizationEntry(child);
}
}
entry.shared++;
storeOptimizationEntry(entry);
@ -1573,7 +1575,7 @@ class FileSystemInfo {
case RBDT_RESOLVE_CJS: {
const isDirectory = /[\\/]$/.test(path);
if (isDirectory) {
resolveDirectory(path.slice(0, path.length - 1));
resolveDirectory(path.slice(0, -1));
} else {
resolveFile(path, "f", resolveCjs);
}
@ -1582,7 +1584,7 @@ class FileSystemInfo {
case RBDT_RESOLVE_ESM: {
const isDirectory = /[\\/]$/.test(path);
if (isDirectory) {
resolveDirectory(path.slice(0, path.length - 1));
resolveDirectory(path.slice(0, -1));
} else {
resolveFile(path);
}

View File

@ -54,14 +54,15 @@ class FlagDependencyExportsPlugin {
const exportsInfo = moduleGraph.getExportsInfo(module);
// If the module doesn't have an exportsType, it's a module
// without declared exports.
if (!module.buildMeta || !module.buildMeta.exportsType) {
if (exportsInfo.otherExportsInfo.provided !== null) {
// It's a module without declared exports
statNoExports++;
exportsInfo.setHasProvideInfo();
exportsInfo.setUnknownExportsProvided();
return callback();
}
if (
(!module.buildMeta || !module.buildMeta.exportsType) &&
exportsInfo.otherExportsInfo.provided !== null
) {
// It's a module without declared exports
statNoExports++;
exportsInfo.setHasProvideInfo();
exportsInfo.setUnknownExportsProvided();
return callback();
}
// If the module has no hash, it's uncacheable
if (

View File

@ -130,8 +130,8 @@ class ByTypeGenerator extends Generator {
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
const t = type || "javascript";
getSize(module, type = "javascript") {
const t = type;
const generator = this.map[t];
return generator ? generator.getSize(module, t) : 0;
}

View File

@ -144,7 +144,7 @@ class HotModuleReplacementPlugin {
/** @type {string[]} */
const requests = [];
if (params.length > 0) {
params.forEach((param, idx) => {
for (const [idx, param] of params.entries()) {
const request = /** @type {string} */ (param.string);
const dep = new ParamDependency(
request,
@ -157,7 +157,7 @@ class HotModuleReplacementPlugin {
dep.loc.index = idx;
module.addDependency(dep);
requests.push(request);
});
}
if (expr.arguments.length > 1) {
hotAcceptCallback.call(expr.arguments[1], requests);
for (let i = 1; i < expr.arguments.length; i++) {
@ -201,7 +201,7 @@ class HotModuleReplacementPlugin {
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter(param => param.isString());
}
params.forEach((param, idx) => {
for (const [idx, param] of params.entries()) {
const dep = new ParamDependency(
/** @type {string} */ (param.string),
/** @type {Range} */ (param.range)
@ -210,7 +210,7 @@ class HotModuleReplacementPlugin {
dep.loc = Object.create(/** @type {DependencyLocation} */ (expr.loc));
dep.loc.index = idx;
module.addDependency(dep);
});
}
}
return true;
};
@ -649,12 +649,11 @@ class HotModuleReplacementPlugin {
for (const moduleRuntime of runtimes) {
if (typeof moduleRuntime === "string") {
if (moduleRuntime === runtime) return;
} else if (moduleRuntime !== undefined) {
if (
moduleRuntime.has(/** @type {string} */ (runtime))
)
return;
}
} else if (
moduleRuntime !== undefined &&
moduleRuntime.has(/** @type {string} */ (runtime))
)
return;
}
const item = hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)

View File

@ -55,6 +55,7 @@ class LibManifestPlugin {
const moduleGraph = compilation.moduleGraph;
// store used paths to detect issue and output an error. #18200
const usedPaths = new Set();
// eslint-disable-next-line unicorn/no-array-for-each
asyncLib.forEach(
Array.from(compilation.chunks),
(chunk, callback) => {

View File

@ -21,11 +21,7 @@ class ModuleBuildError extends WebpackError {
let message = "Module build failed";
let details;
if (from) {
message += ` (from ${from}):\n`;
} else {
message += ": ";
}
message += from ? ` (from ${from}):\n` : ": ";
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
@ -36,11 +32,8 @@ class ModuleBuildError extends WebpackError {
} else {
details = stack;
if (typeof err.message === "string" && err.message) {
message += err.message;
} else {
message += err;
}
message +=
typeof err.message === "string" && err.message ? err.message : err;
}
} else if (typeof err.message === "string" && err.message) {
message += err.message;

View File

@ -20,11 +20,7 @@ class ModuleError extends WebpackError {
constructor(err, { from = null } = {}) {
let message = "Module Error";
if (from) {
message += ` (from ${from}):\n`;
} else {
message += ": ";
}
message += from ? ` (from ${from}):\n` : ": ";
if (err && typeof err === "object" && err.message) {
message += err.message;

View File

@ -297,15 +297,15 @@ ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
const countMap = Object.create(null);
const posMap = Object.create(null);
array.forEach((item, idx) => {
for (const [idx, item] of array.entries()) {
countMap[item] = countMap[item] || [];
countMap[item].push(idx);
posMap[item] = 0;
});
}
if (comparator) {
Object.keys(countMap).forEach(item => {
for (const item of Object.keys(countMap)) {
countMap[item].sort(comparator);
});
}
}
return array.map((item, i) => {
if (countMap[item].length > 1) {
@ -370,20 +370,14 @@ ModuleFilenameHelpers.matchPart = (str, test) => {
* ```
*/
ModuleFilenameHelpers.matchObject = (obj, str) => {
if (obj.test) {
if (!ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
if (obj.include) {
if (!ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
if (obj.exclude) {
if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
return true;
};

View File

@ -445,7 +445,7 @@ class ModuleGraph {
}
}
this._dependencyMap.set(dependency, null);
return undefined;
return;
}
return connection === null ? undefined : connection;
}

View File

@ -234,12 +234,8 @@ class ModuleInfoHeaderPlugin {
moduleGraph.getOptimizationBailout(module);
if (optimizationBailout) {
for (const text of optimizationBailout) {
let code;
if (typeof text === "function") {
code = text(requestShortener);
} else {
code = text;
}
const code =
typeof text === "function" ? text(requestShortener) : text;
source.add(`${Template.toComment(`${code}`)}\n`);
}
}

View File

@ -20,11 +20,7 @@ class ModuleWarning extends WebpackError {
constructor(warning, { from = null } = {}) {
let message = "Module Warning";
if (from) {
message += ` (from ${from}):\n`;
} else {
message += ": ";
}
message += from ? ` (from ${from}):\n` : ": ";
if (warning && typeof warning === "object" && warning.message) {
message += warning.message;

View File

@ -511,7 +511,7 @@ module.exports = class MultiCompiler {
/** @type {SetupResult[]} */
const setupResults = [];
nodes.forEach((node, i) => {
for (const [i, node] of nodes.entries()) {
setupResults.push(
(node.setupResult = setup(
node.compiler,
@ -522,7 +522,7 @@ module.exports = class MultiCompiler {
() => nodeInvalid(node)
))
);
});
}
let processing = true;
const processQueue = () => {
if (processing) return;

View File

@ -62,6 +62,7 @@ class MultiWatching {
* @returns {void}
*/
close(callback) {
// eslint-disable-next-line unicorn/no-array-for-each
asyncLib.forEach(
this.watchings,
(watching, finishedCallback) => {

View File

@ -150,7 +150,7 @@ const needCalls = (times, callback) => err => {
return callback(err);
}
if (err && times > 0) {
times = NaN;
times = Number.NaN;
return callback(err);
}
};
@ -171,11 +171,8 @@ const mergeGlobalOptions = (globalOptions, type, localOptions) => {
current = current ? `${current}/${part}` : part;
const options = globalOptions[current];
if (typeof options === "object") {
if (result === undefined) {
result = options;
} else {
result = cachedCleverMerge(result, options);
}
result =
result === undefined ? options : cachedCleverMerge(result, options);
}
}
if (result === undefined) {
@ -1063,11 +1060,9 @@ Add the extension to the request.`
/(\.[^.]+)(\?|$)/,
"$2"
);
if (resolver.options.extensions.has(match[1])) {
hint = `Did you mean '${fixedRequest}'?`;
} else {
hint = `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`;
}
hint = resolver.options.extensions.has(match[1])
? `Did you mean '${fixedRequest}'?`
: `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`;
} else {
hint =
"Did you mean to omit the extension or to remove 'resolve.enforceExtension'?";

View File

@ -507,7 +507,7 @@ class ProgressPlugin {
afterSeal: "after seal"
};
const numberOfHooks = Object.keys(hooks).length;
Object.keys(hooks).forEach((name, idx) => {
for (const [idx, name] of Object.keys(hooks).entries()) {
const title = hooks[/** @type {keyof typeof hooks} */ (name)];
const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
@ -534,7 +534,7 @@ class ProgressPlugin {
handler(percentage, "sealing", title, tap.name);
}
});
});
}
});
compiler.hooks.make.intercept({
name: "ProgressPlugin",

View File

@ -58,16 +58,16 @@ class ProvidePlugin {
* @returns {void}
*/
const handler = (parser, parserOptions) => {
Object.keys(definitions).forEach(name => {
for (const name of Object.keys(definitions)) {
const request =
/** @type {string[]} */
([]).concat(definitions[name]);
const splittedName = name.split(".");
if (splittedName.length > 0) {
splittedName.slice(1).forEach((_, i) => {
for (const [i, _] of splittedName.slice(1).entries()) {
const name = splittedName.slice(0, i + 1).join(".");
parser.hooks.canRename.for(name).tap(PLUGIN_NAME, approve);
});
}
}
parser.hooks.expression.for(name).tap(PLUGIN_NAME, expr => {
@ -100,7 +100,7 @@ class ProvidePlugin {
parser.walkExpressions(expr.arguments);
return true;
});
});
}
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)

View File

@ -67,11 +67,11 @@ function getGlobalObject(definition) {
if (
// identifier, we do not need real identifier regarding ECMAScript/Unicode
trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) ||
/^[_\p{L}][_0-9\p{L}]*$/iu.test(trimmed) ||
// iife
// call expression
// expression in parentheses
trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu)
/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu.test(trimmed)
)
return trimmed;

View File

@ -442,12 +442,9 @@ class SourceMapDevToolPlugin {
// If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file`
if (usesContentHash && task.assetInfo.contenthash) {
const contenthash = task.assetInfo.contenthash;
let pattern;
if (Array.isArray(contenthash)) {
pattern = contenthash.map(quoteMeta).join("|");
} else {
pattern = quoteMeta(contenthash);
}
const pattern = Array.isArray(contenthash)
? contenthash.map(quoteMeta).join("|")
: quoteMeta(contenthash);
sourceMap.file = sourceMap.file.replace(
new RegExp(pattern, "g"),
m => "x".repeat(m.length)

View File

@ -55,7 +55,7 @@ const hashLength = (replacer, handler, assetInfo, hashName) => {
/** @type {ReplacerFunction} */
const fn = (match, arg, input) => {
let result;
const length = arg && parseInt(arg, 10);
const length = arg && Number.parseInt(arg, 10);
if (length && handler) {
result = handler(length);

View File

@ -155,28 +155,23 @@ class WebpackOptionsApply extends OptionsApply {
}
callback();
}).apply(compiler);
} else if (options.externalsPresets.node) {
if (options.experiments.css) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin(
"module",
({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `asset ${request}`);
} else if (dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `css-import ${request}`);
} else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
if (/^\.css(\?|$)/.test(request))
return callback(null, `css-import ${request}`);
return callback(null, `module ${request}`);
}
callback();
}
).apply(compiler);
}
} else if (options.externalsPresets.node && options.experiments.css) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin("module", ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `asset ${request}`);
} else if (dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `css-import ${request}`);
} else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
if (/^\.css(\?|$)/.test(request))
return callback(null, `css-import ${request}`);
return callback(null, `module ${request}`);
}
callback();
}).apply(compiler);
}
new ChunkPrefetchPreloadPlugin().apply(compiler);
@ -606,7 +601,7 @@ class WebpackOptionsApply extends OptionsApply {
const cacheOptions = options.cache;
switch (cacheOptions.type) {
case "memory": {
if (isFinite(cacheOptions.maxGenerations)) {
if (Number.isFinite(cacheOptions.maxGenerations)) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
new MemoryWithGcCachePlugin({
@ -634,7 +629,7 @@ class WebpackOptionsApply extends OptionsApply {
const list = cacheOptions.buildDependencies[key];
new AddBuildDependenciesPlugin(list).apply(compiler);
}
if (!isFinite(cacheOptions.maxMemoryGenerations)) {
if (!Number.isFinite(cacheOptions.maxMemoryGenerations)) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
new MemoryCachePlugin().apply(compiler);

View File

@ -255,13 +255,12 @@ class AssetGenerator extends Generator {
} else {
/** @type {string | false | undefined} */
let encoding = this.dataUrlOptions.encoding;
if (encoding === undefined) {
if (
module.resourceResolveData &&
module.resourceResolveData.encoding !== undefined
) {
encoding = module.resourceResolveData.encoding;
}
if (
encoding === undefined &&
module.resourceResolveData &&
module.resourceResolveData.encoding !== undefined
) {
encoding = module.resourceResolveData.encoding;
}
if (encoding === undefined) {
encoding = DEFAULT_ENCODING;

View File

@ -34,13 +34,8 @@ class AssetSourceGenerator extends Generator {
}
const content = originalSource.source();
let encodedSource;
if (typeof content === "string") {
encodedSource = content;
} else {
encodedSource = content.toString("utf-8");
}
const encodedSource =
typeof content === "string" ? content : content.toString("utf-8");
let sourceContent;
if (concatenationScope) {

View File

@ -160,7 +160,7 @@ class Pack {
const info = this.itemInfo.get(identifier);
this._addRequest(identifier);
if (info === undefined) {
return undefined;
return;
}
if (info.etag !== etag) return null;
info.lastAccess = Date.now();
@ -169,7 +169,7 @@ class Pack {
return info.freshValue;
}
if (!this.content[loc]) {
return undefined;
return;
}
return /** @type {PackContent} */ (this.content[loc]).get(identifier);
}
@ -1146,19 +1146,19 @@ class PackFileCacheStrategy {
})
.then(packContainer => {
logger.timeEnd("restore cache container");
if (!packContainer) return undefined;
if (!packContainer) return;
if (!(packContainer instanceof PackContainer)) {
logger.warn(
`Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`,
packContainer
);
return undefined;
return;
}
if (packContainer.version !== version) {
logger.log(
`Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.`
);
return undefined;
return;
}
logger.time("check build dependencies");
return Promise.all([

View File

@ -59,11 +59,10 @@ const objectToString = (object, excludeContext) => {
for (const key in object) {
if (excludeContext && key === "context") continue;
const value = object[key];
if (typeof value === "object" && value !== null) {
str += `|${key}=[${objectToString(value, false)}|]`;
} else {
str += `|${key}=|${value}`;
}
str +=
typeof value === "object" && value !== null
? `|${key}=[${objectToString(value, false)}|]`
: `|${key}=|${value}`;
}
return str;
};

View File

@ -565,7 +565,7 @@ const parseValueForArgumentConfig = (argConfig, value) => {
if (typeof value === "number") return value;
if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) {
const n = Number(value);
if (!isNaN(n)) return n;
if (!Number.isNaN(n)) return n;
}
break;
case "boolean":

View File

@ -534,7 +534,7 @@ const getNormalizedEntryStatic = entry => {
* @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
*/
const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
if (runtimeChunk === undefined) return undefined;
if (runtimeChunk === undefined) return;
if (runtimeChunk === false) return false;
if (runtimeChunk === "single") {
return {

View File

@ -128,7 +128,10 @@ class CssExportsGenerator extends Generator {
template.apply(dependency, source, templateContext);
};
module.dependencies.forEach(handleDependency);
for (const dependency of module.dependencies) {
handleDependency(dependency);
}
if (generateContext.concatenationScope) {
const source = new ConcatSource();

View File

@ -101,9 +101,14 @@ class CssGenerator extends Generator {
template.apply(dependency, source, templateContext);
};
module.dependencies.forEach(handleDependency);
if (module.presentationalDependencies !== undefined)
module.presentationalDependencies.forEach(handleDependency);
for (const dependency of module.dependencies) {
handleDependency(dependency);
}
if (module.presentationalDependencies !== undefined) {
for (const dependency of module.presentationalDependencies) {
handleDependency(dependency);
}
}
const data = generateContext.getData();
data.set("css-exports", cssExportsData);

View File

@ -224,7 +224,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
withCompression
? Template.asString([
// LZW decode
`var map = {}, char = data[0], oldPhrase = char, decoded = char, code = 256, maxCode = ${"\uffff".charCodeAt(
`var map = {}, char = data[0], oldPhrase = char, decoded = char, code = 256, maxCode = ${"\uFFFF".charCodeAt(
0
)}, phrase;`,
"for (i = 1; i < data.length; i++) {",

View File

@ -128,7 +128,7 @@ const validateParserOptions = {
const escapeCss = (str, omitOptionalUnderscore) => {
const escaped = `${str}`.replace(
// cspell:word uffff
/[^a-zA-Z0-9_\u0081-\uffff-]/g,
/[^a-zA-Z0-9_\u0081-\uFFFF-]/g,
s => `\\${s}`
);
return !omitOptionalUnderscore && /^(?!--)[0-9_-]/.test(escaped)
@ -146,7 +146,7 @@ const lzwEncode = str => {
let encoded = "";
let phrase = str[0];
let code = 256;
const maxCode = "\uffff".charCodeAt(0);
const maxCode = "\uFFFF".charCodeAt(0);
for (let i = 1; i < str.length; i++) {
const c = str[i];
if (map.has(phrase + c)) {

View File

@ -60,7 +60,7 @@ const normalizeUrl = (str, isString) => {
// Unescape
.replace(UNESCAPE, match => {
if (match.length > 2) {
return String.fromCharCode(parseInt(match.slice(1).trim(), 16));
return String.fromCharCode(Number.parseInt(match.slice(1).trim(), 16));
}
return match[1];
});
@ -171,7 +171,7 @@ class CssParser extends Parser {
} else if (typeof source === "object") {
throw new Error("webpackAst is unexpected for the CssParser");
}
if (source[0] === "\ufeff") {
if (source[0] === "\uFEFF") {
source = source.slice(1);
}
@ -250,7 +250,9 @@ class CssParser extends Parser {
{ length: charCodes.reduce((a, b) => Math.max(a, b), 0) + 1 },
() => false
);
charCodes.forEach(cc => (arr[cc] = true));
for (const cc of charCodes) {
arr[cc] = true;
}
return (input, pos) => {
for (;;) {
const cc = input.charCodeAt(pos);

View File

@ -233,19 +233,19 @@ class ProfilingPlugin {
tracer.profiler.startProfiling();
// Compiler Hooks
Object.keys(compiler.hooks).forEach(hookName => {
for (const hookName of Object.keys(compiler.hooks)) {
const hook = compiler.hooks[hookName];
if (hook) {
hook.intercept(makeInterceptorFor("Compiler", tracer)(hookName));
}
});
}
Object.keys(compiler.resolverFactory.hooks).forEach(hookName => {
for (const hookName of Object.keys(compiler.resolverFactory.hooks)) {
const hook = compiler.resolverFactory.hooks[hookName];
if (hook) {
hook.intercept(makeInterceptorFor("Resolver", tracer)(hookName));
}
});
}
compiler.hooks.compilation.tap(
PLUGIN_NAME,
@ -340,12 +340,12 @@ class ProfilingPlugin {
*/
const interceptAllHooksFor = (instance, tracer, logLabel) => {
if (Reflect.has(instance, "hooks")) {
Object.keys(instance.hooks).forEach(hookName => {
for (const hookName of Object.keys(instance.hooks)) {
const hook = instance.hooks[hookName];
if (hook && !hook._fakeHook) {
hook.intercept(makeInterceptorFor(logLabel, tracer)(hookName));
}
});
}
}
};
@ -363,13 +363,13 @@ const interceptAllParserHooks = (moduleFactory, tracer) => {
WEBASSEMBLY_MODULE_TYPE_SYNC
];
moduleTypes.forEach(moduleType => {
for (const moduleType of moduleTypes) {
moduleFactory.hooks.parser
.for(moduleType)
.tap(PLUGIN_NAME, (parser, parserOpts) => {
interceptAllHooksFor(parser, tracer, "Parser");
});
});
}
};
/**

View File

@ -114,7 +114,7 @@ class AMDDefineDependencyParserPlugin {
/** @type {(string | LocalModuleDependency | AMDRequireItemDependency)[]} */
const deps = [];
/** @type {string[]} */
(param.array).forEach((request, idx) => {
for (const [idx, request] of param.array.entries()) {
let dep;
let localModule;
if (request === "require") {
@ -135,7 +135,7 @@ class AMDDefineDependencyParserPlugin {
parser.state.current.addDependency(dep);
}
deps.push(dep);
});
}
const dep = this.newRequireArrayDependency(
deps,
/** @type {Range} */ (param.range)
@ -156,13 +156,14 @@ class AMDDefineDependencyParserPlugin {
*/
processItem(parser, expr, param, namedModule) {
if (param.isConditional()) {
/** @type {BasicEvaluatedExpression[]} */
(param.options).forEach(param => {
const result = this.processItem(parser, expr, param);
const options = /** @type {BasicEvaluatedExpression[]} */ (param.options);
for (const item of options) {
const result = this.processItem(parser, expr, item);
if (result === undefined) {
this.processContext(parser, expr, param);
this.processContext(parser, expr, item);
}
});
}
return true;
} else if (param.isString()) {
let dep;

View File

@ -302,7 +302,7 @@ class CommonJsExportsParserPlugin {
* @param {CallExpression=} call call expression
* @returns {boolean | void} true, when the expression was handled
*/
const handleAccessExport = (expr, base, members, call = undefined) => {
const handleAccessExport = (expr, base, members, call) => {
if (HarmonyExports.isEnabled(parser.state)) return;
if (members.length === 0) {
bailout(

View File

@ -288,19 +288,17 @@ class CommonJsImportsParserPlugin {
);
}
}
if (requireOptions) {
if (requireOptions.webpackIgnore !== undefined) {
if (typeof requireOptions.webpackIgnore !== "boolean") {
parser.state.module.addWarning(
new UnsupportedFeatureWarning(
`\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`,
/** @type {DependencyLocation} */ (expr.loc)
)
);
} else if (requireOptions.webpackIgnore) {
// Do not instrument `require()` if `webpackIgnore` is `true`
return true;
}
if (requireOptions && requireOptions.webpackIgnore !== undefined) {
if (typeof requireOptions.webpackIgnore !== "boolean") {
parser.state.module.addWarning(
new UnsupportedFeatureWarning(
`\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`,
/** @type {DependencyLocation} */ (expr.loc)
)
);
} else if (requireOptions.webpackIgnore) {
// Do not instrument `require()` if `webpackIgnore` is `true`
return true;
}
}
}

View File

@ -108,12 +108,10 @@ CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependency
{ module, moduleGraph, runtime, runtimeRequirements }
) {
const dep = /** @type {CommonJsSelfReferenceDependency} */ (dependency);
let used;
if (dep.names.length === 0) {
used = dep.names;
} else {
used = moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime);
}
const used =
dep.names.length === 0
? dep.names
: moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime);
if (!used) {
throw new Error(
"Self-reference dependency has unused export name: This should not happen"

View File

@ -82,7 +82,7 @@ module.exports.create = (
// When there are more than two quasis, the generated RegExp can be more precise
// We join the quasis with the expression regexp
const innerQuasis = quasis.slice(1, quasis.length - 1);
const innerQuasis = quasis.slice(1, -1);
const innerRegExp =
/** @type {RegExp} */ (options.wrappedContextRegExp).source +
innerQuasis
@ -123,14 +123,14 @@ module.exports.create = (
const replaces = [];
const parts = /** @type {BasicEvaluatedExpression[]} */ (param.parts);
parts.forEach((part, i) => {
for (const [i, part] of parts.entries()) {
if (i % 2 === 0) {
// Quasis or merged quasi
let range = /** @type {Range} */ (part.range);
let value = /** @type {string} */ (part.string);
if (param.templateStringKind === "cooked") {
value = JSON.stringify(value);
value = value.slice(1, value.length - 1);
value = value.slice(1, -1);
}
if (i === 0) {
// prefix
@ -156,7 +156,7 @@ module.exports.create = (
part.expression.value.raw === value
) {
// Shortcut when it's a single quasi and doesn't need to be replaced
return;
continue;
}
replaces.push({
range,
@ -166,7 +166,7 @@ module.exports.create = (
// Expression
parser.walkExpression(part.expression);
}
});
}
dep.replaces = replaces;
dep.critical =

View File

@ -178,7 +178,7 @@ class CssLocalIdentifierDependency extends NullDependency {
const escapeCssIdentifier = (str, omitUnderscore) => {
const escaped = `${str}`.replace(
// cspell:word uffff
/[^a-zA-Z0-9_\u0081-\uffff-]/g,
/[^a-zA-Z0-9_\u0081-\uFFFF-]/g,
s => `\\${s}`
);
return !omitUnderscore && /^(?!--)[0-9-]/.test(escaped)

View File

@ -72,7 +72,7 @@ const getProperty = (moduleGraph, module, _exportName, property, runtime) => {
case UsageState.Unused:
return false;
case UsageState.NoInfo:
return undefined;
return;
case UsageState.Unknown:
return null;
default:
@ -82,7 +82,6 @@ const getProperty = (moduleGraph, module, _exportName, property, runtime) => {
case "provideInfo":
return moduleGraph.getExportsInfo(module).isExportProvided(exportName);
}
return undefined;
};
class ExportsInfoDependency extends NullDependency {

View File

@ -18,7 +18,7 @@ class HarmonyAcceptImportDependency extends HarmonyImportDependency {
* @param {string} request the request string
*/
constructor(request) {
super(request, NaN);
super(request, Number.NaN);
this.weak = true;
}

View File

@ -112,11 +112,10 @@ HarmonyEvaluatedImportSpecifierDependency.Template = class HarmonyEvaluatedImpor
break;
}
case "namespace": {
if (ids[0] === "__esModule") {
value = ids.length === 1 || undefined;
} else {
value = exportsInfo.isExportProvided(ids);
}
value =
ids[0] === "__esModule"
? ids.length === 1 || undefined
: exportsInfo.isExportProvided(ids);
break;
}
case "dynamic": {

View File

@ -145,26 +145,23 @@ module.exports = class HarmonyExportDependencyParserPlugin {
"HarmonyExportDependencyParserPlugin",
(statement, id, name, idx) => {
const settings = parser.getTagData(id, harmonySpecifierTag);
let dep;
const harmonyNamedExports = (parser.state.harmonyNamedExports =
parser.state.harmonyNamedExports || new Set());
harmonyNamedExports.add(name);
InnerGraph.addVariableUsage(parser, id, name);
if (settings) {
dep = new HarmonyExportImportedSpecifierDependency(
settings.source,
settings.sourceOrder,
settings.ids,
name,
harmonyNamedExports,
null,
exportPresenceMode,
null,
settings.assertions
);
} else {
dep = new HarmonyExportSpecifierDependency(id, name);
}
const dep = settings
? new HarmonyExportImportedSpecifierDependency(
settings.source,
settings.sourceOrder,
settings.ids,
name,
harmonyNamedExports,
null,
exportPresenceMode,
null,
settings.assertions
)
: new HarmonyExportSpecifierDependency(id, name);
dep.loc = Object.create(
/** @type {DependencyLocation} */ (statement.loc)
);

View File

@ -597,13 +597,13 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
* @returns {{ names: string[], namesSlice: number, dependencyIndices: number[], dependencyIndex: number } | undefined} exported names and their origin dependency
*/
_discoverActiveExportsFromOtherStarExports(moduleGraph) {
if (!this.otherStarExports) return undefined;
if (!this.otherStarExports) return;
const i =
"length" in this.otherStarExports
? this.otherStarExports.length
: countIterable(this.otherStarExports);
if (i === 0) return undefined;
if (i === 0) return;
if (this.allStarExports) {
const { names, dependencyIndices } = moduleGraph.cached(
@ -643,7 +643,7 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
switch (mode.type) {
case "missing":
return undefined;
return;
case "dynamic-reexport": {
const from =
/** @type {ModuleGraphConnection} */
@ -1153,11 +1153,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
}
content += "__WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = ";
if (modern) {
content += `() => ${importVar}[__WEBPACK_IMPORT_KEY__]`;
} else {
content += `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`;
}
content += modern
? `() => ${importVar}[__WEBPACK_IMPORT_KEY__]`
: `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`;
runtimeRequirements.add(RuntimeGlobals.exports);
runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);

View File

@ -96,7 +96,7 @@ function getAttributes(node) {
? /** @type {{ assertions?: ImportAttributeNode[] }} */ (node).assertions
: /** @type {{ attributes?: ImportAttributeNode[] }} */ (node).attributes;
if (attributes === undefined) {
return undefined;
return;
}
const result = /** @type {ImportAttributes} */ ({});
for (const attribute of attributes) {

View File

@ -75,7 +75,7 @@ class ImportMetaPlugin {
}
// import.meta direct
const webpackVersion = parseInt(
const webpackVersion = Number.parseInt(
require("../../package.json").version,
10
);

View File

@ -391,15 +391,13 @@ class WorkerPlugin {
dep2.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep1);
parser.state.module.addPresentationalDependency(dep2);
} else if (insertType === "argument") {
if (this._module) {
const dep = new ConstDependency(
', { type: "module" }',
insertLocation
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
}
} else if (insertType === "argument" && this._module) {
const dep = new ConstDependency(
', { type: "module" }',
insertLocation
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
}
parser.walkExpression(expr.callee);
@ -479,7 +477,9 @@ class WorkerPlugin {
};
for (const item of options) {
if (item === "...") {
DEFAULT_SYNTAX.forEach(processItem);
for (const itemFromDefault of DEFAULT_SYNTAX) {
processItem(itemFromDefault);
}
} else processItem(item);
}
};

View File

@ -117,15 +117,12 @@ module.exports = function () {
if ($hasOwnProperty$(currentUpdate, moduleId)) {
var newModuleFactory = currentUpdate[moduleId];
/** @type {TODO} */
var result;
if (newModuleFactory) {
result = getAffectedModuleEffects(moduleId);
} else {
result = {
type: "disposed",
moduleId: moduleId
};
}
var result = newModuleFactory
? getAffectedModuleEffects(moduleId)
: {
type: "disposed",
moduleId: moduleId
};
/** @type {Error|false} */
var abortError = false;
var doApply = false;

View File

@ -184,7 +184,7 @@ class BasicEvaluatedExpression {
asCompileTimeValue() {
switch (this.type) {
case TypeUndefined:
return undefined;
return;
case TypeNull:
return null;
case TypeString:
@ -252,7 +252,6 @@ class BasicEvaluatedExpression {
const str = this.asString();
if (typeof str === "string") return str !== "";
}
return undefined;
}
/**
@ -275,8 +274,6 @@ class BasicEvaluatedExpression {
if (this.isConstArray()) return false;
if (this.isTemplateString()) return false;
if (this.isRegExp()) return false;
return undefined;
}
/**
@ -297,7 +294,7 @@ class BasicEvaluatedExpression {
this.items
)) {
const itemStr = item.asString();
if (itemStr === undefined) return undefined;
if (itemStr === undefined) return;
array.push(itemStr);
}
return `${array}`;
@ -309,12 +306,11 @@ class BasicEvaluatedExpression {
this.parts
)) {
const partStr = part.asString();
if (partStr === undefined) return undefined;
if (partStr === undefined) return;
str += partStr;
}
return str;
}
return undefined;
}
/**

View File

@ -1386,7 +1386,7 @@ class JavascriptParser extends Parser {
.setSideEffects(param.couldHaveSideEffects())
.setRange(/** @type {Range} */ (expr.range));
});
["substr", "substring", "slice"].forEach(fn => {
for (const fn of ["substr", "substring", "slice"]) {
this.hooks.evaluateCallExpressionMember
.for(fn)
.tap("JavascriptParser", (expr, param) => {
@ -1426,7 +1426,7 @@ class JavascriptParser extends Parser {
.setSideEffects(param.couldHaveSideEffects())
.setRange(/** @type {Range} */ (expr.range));
});
});
}
/**
* @param {"cooked" | "raw"} kind kind of values to get
@ -1706,7 +1706,7 @@ class JavascriptParser extends Parser {
* @returns {Set<DestructuringAssignmentProperty> | undefined} destructured identifiers
*/
destructuringAssignmentPropertiesFor(node) {
if (!this.destructuringAssignmentProperties) return undefined;
if (!this.destructuringAssignmentProperties) return;
return this.destructuringAssignmentProperties.get(node);
}
@ -1726,10 +1726,11 @@ class JavascriptParser extends Parser {
* @returns {void}
*/
walkClass(classy) {
if (classy.superClass) {
if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) {
this.walkExpression(classy.superClass);
}
if (
classy.superClass &&
!this.hooks.classExtendsExpression.call(classy.superClass, classy)
) {
this.walkExpression(classy.superClass);
}
if (classy.body && classy.body.type === "ClassBody") {
const scopeParams = [];
@ -2155,10 +2156,8 @@ class JavascriptParser extends Parser {
* @param {ForStatement} statement for statement
*/
preWalkForStatement(statement) {
if (statement.init) {
if (statement.init.type === "VariableDeclaration") {
this.preWalkStatement(statement.init);
}
if (statement.init && statement.init.type === "VariableDeclaration") {
this.preWalkStatement(statement.init);
}
this.preWalkStatement(statement.body);
}
@ -2425,19 +2424,18 @@ class JavascriptParser extends Parser {
} else {
this.hooks.export.call(statement);
}
if (statement.declaration) {
if (
!this.hooks.exportDeclaration.call(statement, statement.declaration)
) {
const prev = this.prevStatement;
this.preWalkStatement(statement.declaration);
this.prevStatement = prev;
this.blockPreWalkStatement(statement.declaration);
let index = 0;
this.enterDeclaration(statement.declaration, def => {
this.hooks.exportSpecifier.call(statement, def, def, index++);
});
}
if (
statement.declaration &&
!this.hooks.exportDeclaration.call(statement, statement.declaration)
) {
const prev = this.prevStatement;
this.preWalkStatement(statement.declaration);
this.prevStatement = prev;
this.blockPreWalkStatement(statement.declaration);
let index = 0;
this.enterDeclaration(statement.declaration, def => {
this.hooks.exportSpecifier.call(statement, def, def, index++);
});
}
if (statement.specifiers) {
for (
@ -3174,31 +3172,30 @@ class JavascriptParser extends Parser {
walkAssignmentExpression(expression) {
if (expression.left.type === "Identifier") {
const renameIdentifier = this.getRenameIdentifier(expression.right);
if (renameIdentifier) {
if (
renameIdentifier &&
this.callHooksForInfo(
this.hooks.canRename,
renameIdentifier,
expression.right
)
) {
// renaming "a = b;"
if (
this.callHooksForInfo(
this.hooks.canRename,
!this.callHooksForInfo(
this.hooks.rename,
renameIdentifier,
expression.right
)
) {
// renaming "a = b;"
if (
!this.callHooksForInfo(
this.hooks.rename,
renameIdentifier,
expression.right
)
) {
this.setVariable(
expression.left.name,
typeof renameIdentifier === "string"
? this.getVariableInfo(renameIdentifier)
: renameIdentifier
);
}
return;
this.setVariable(
expression.left.name,
typeof renameIdentifier === "string"
? this.getVariableInfo(renameIdentifier)
: renameIdentifier
);
}
return;
}
this.walkExpression(expression.right);
this.enterPattern(expression.left, (name, decl) => {
@ -3221,17 +3218,16 @@ class JavascriptParser extends Parser {
expression.left,
ALLOWED_MEMBER_TYPES_EXPRESSION
);
if (exprName) {
if (
this.callHooksForInfo(
this.hooks.assignMemberChain,
exprName.rootInfo,
expression,
exprName.getMembers()
)
) {
return;
}
if (
exprName &&
this.callHooksForInfo(
this.hooks.assignMemberChain,
exprName.rootInfo,
expression,
exprName.getMembers()
)
) {
return;
}
this.walkExpression(expression.right);
this.walkExpression(expression.left);
@ -3344,26 +3340,18 @@ class JavascriptParser extends Parser {
const renameIdentifier = this.getRenameIdentifier(
/** @type {Expression} */ (argOrThis)
);
if (renameIdentifier) {
if (
this.callHooksForInfo(
this.hooks.canRename,
renameIdentifier,
argOrThis
)
) {
if (
!this.callHooksForInfo(
this.hooks.rename,
renameIdentifier,
argOrThis
)
) {
return typeof renameIdentifier === "string"
? /** @type {string} */ (this.getVariableInfo(renameIdentifier))
: renameIdentifier;
}
}
if (
renameIdentifier &&
this.callHooksForInfo(
this.hooks.canRename,
renameIdentifier,
argOrThis
) &&
!this.callHooksForInfo(this.hooks.rename, renameIdentifier, argOrThis)
) {
return typeof renameIdentifier === "string"
? /** @type {string} */ (this.getVariableInfo(renameIdentifier))
: renameIdentifier;
}
this.walkExpression(argOrThis);
};
@ -4589,8 +4577,10 @@ class JavascriptParser extends Parser {
)
)) {
if (typeof val === "object" && val !== null) {
if (val.constructor.name === "RegExp") val = new RegExp(val);
else val = JSON.parse(JSON.stringify(val));
val =
val.constructor.name === "RegExp"
? new RegExp(val)
: JSON.parse(JSON.stringify(val));
}
options[key] = val;
}
@ -4646,9 +4636,9 @@ class JavascriptParser extends Parser {
let name;
if (info instanceof VariableInfo) {
name = info.freeName;
if (typeof name !== "string") return undefined;
if (typeof name !== "string") return;
} else if (typeof info !== "string") {
return undefined;
return;
} else {
name = info;
}
@ -4668,8 +4658,7 @@ class JavascriptParser extends Parser {
this.extractMemberExpressionChain(expression);
switch (object.type) {
case "CallExpression": {
if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0)
return undefined;
if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) return;
let callee = object.callee;
let rootMembers = EMPTY_ARRAY;
if (callee.type === "MemberExpression") {
@ -4677,9 +4666,9 @@ class JavascriptParser extends Parser {
this.extractMemberExpressionChain(callee));
}
const rootName = getRootName(callee);
if (!rootName) return undefined;
if (!rootName) return;
const result = this.getFreeInfoFromVariable(rootName);
if (!result) return undefined;
if (!result) return;
const { info: rootInfo, name: resolvedRoot } = result;
const calleeName = objectAndMembersToName(resolvedRoot, rootMembers);
return {
@ -4697,13 +4686,12 @@ class JavascriptParser extends Parser {
case "Identifier":
case "MetaProperty":
case "ThisExpression": {
if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0)
return undefined;
if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) return;
const rootName = getRootName(object);
if (!rootName) return undefined;
if (!rootName) return;
const result = this.getFreeInfoFromVariable(rootName);
if (!result) return undefined;
if (!result) return;
const { info: rootInfo, name: resolvedRoot } = result;
return {
type: "expression",

View File

@ -27,7 +27,7 @@ const RuntimeGlobals = require("../RuntimeGlobals");
const stringifySafe = data => {
const stringified = JSON.stringify(data);
if (!stringified) {
return undefined; // Invalid JSON
return; // Invalid JSON
}
return stringified.replace(/\u2028|\u2029/g, str =>
@ -53,16 +53,10 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
if (used === UsageState.Unused) continue;
/** @type {RawJsonData} */
let value;
if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) {
value = createObjectForExportsInfo(
data[key],
exportInfo.exportsInfo,
runtime
);
} else {
value = data[key];
}
const value =
used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo
? createObjectForExportsInfo(data[key], exportInfo.exportsInfo, runtime)
: data[key];
const name = /** @type {string} */ (exportInfo.getUsedName(key, runtime));
/** @type {Record<string, RawJsonData>} */ (reducedData)[name] = value;

View File

@ -49,7 +49,7 @@ class JsonParser extends Parser {
data =
typeof source === "object"
? source
: parseFn(source[0] === "\ufeff" ? source.slice(1) : source);
: parseFn(source[0] === "\uFEFF" ? source.slice(1) : source);
} catch (err) {
throw new Error(
`Cannot parse JSON: ${/** @type {Error} */ (err).message}`

View File

@ -217,13 +217,11 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin {
`Missing external configuration for type:${type}`
);
}
if (Array.isArray(request)) {
expr = `require(${JSON.stringify(
request[0]
)})${accessorToObjectAccess(request.slice(1))}`;
} else {
expr = `require(${JSON.stringify(request)})`;
}
expr = Array.isArray(request)
? `require(${JSON.stringify(
request[0]
)})${accessorToObjectAccess(request.slice(1))}`
: `require(${JSON.stringify(request)})`;
if (m.isOptional(moduleGraph)) {
expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`;
}

View File

@ -36,8 +36,7 @@ const truncateArgs = (args, maxLength) => {
// Check if there is space for at least 4 chars per arg
if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) {
// remove args
if (args.length > 1)
return truncateArgs(args.slice(0, args.length - 1), maxLength);
if (args.length > 1) return truncateArgs(args.slice(0, -1), maxLength);
return [];
}

View File

@ -48,7 +48,7 @@ module.exports = ({ colors, appendOnly, stream }) => {
const clearStatusMessage = () => {
if (hasStatusMessage) {
stream.write("\x1b[2K\r");
stream.write("\u001B[2K\r");
hasStatusMessage = false;
}
};
@ -58,8 +58,8 @@ module.exports = ({ colors, appendOnly, stream }) => {
const l = /** @type {TODO} */ (stream).columns || 40;
const args = truncateArgs(currentStatusMessage, l - 1);
const str = args.join(" ");
const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`;
stream.write(`\x1b[2K\r${coloredStr}`);
const coloredStr = `\u001B[1m${str}\u001B[39m\u001B[22m`;
stream.write(`\u001B[2K\r${coloredStr}`);
hasStatusMessage = true;
};
@ -86,27 +86,27 @@ module.exports = ({ colors, appendOnly, stream }) => {
const writeGroupMessage = writeColored(
"<-> ",
"\u001b[1m\u001b[36m",
"\u001b[39m\u001b[22m"
"\u001B[1m\u001B[36m",
"\u001B[39m\u001B[22m"
);
const writeGroupCollapsedMessage = writeColored(
"<+> ",
"\u001b[1m\u001b[36m",
"\u001b[39m\u001b[22m"
"\u001B[1m\u001B[36m",
"\u001B[39m\u001B[22m"
);
return {
log: writeColored(" ", "\u001b[1m", "\u001b[22m"),
log: writeColored(" ", "\u001B[1m", "\u001B[22m"),
debug: writeColored(" ", "", ""),
trace: writeColored(" ", "", ""),
info: writeColored("<i> ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"),
warn: writeColored("<w> ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"),
error: writeColored("<e> ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"),
info: writeColored("<i> ", "\u001B[1m\u001B[32m", "\u001B[39m\u001B[22m"),
warn: writeColored("<w> ", "\u001B[1m\u001B[33m", "\u001B[39m\u001B[22m"),
error: writeColored("<e> ", "\u001B[1m\u001B[31m", "\u001B[39m\u001B[22m"),
logTime: writeColored(
"<t> ",
"\u001b[1m\u001b[35m",
"\u001b[39m\u001b[22m"
"\u001B[1m\u001B[35m",
"\u001B[39m\u001B[22m"
),
group: (...args) => {
writeGroupMessage(...args);
@ -123,7 +123,7 @@ module.exports = ({ colors, appendOnly, stream }) => {
groupEnd: () => {
if (currentCollapsed > 0) currentCollapsed--;
else if (currentIndent.length >= 2)
currentIndent = currentIndent.slice(0, currentIndent.length - 2);
currentIndent = currentIndent.slice(0, -2);
},
profile: console.profile && (name => console.profile(name)),
profileEnd: console.profileEnd && (name => console.profileEnd(name)),

View File

@ -272,12 +272,14 @@ class AggressiveSplittingPlugin {
// We remove invalid splittings and try again
for (const chunk of compilation.chunks) {
const splitData = chunkSplitDataMap.get(chunk);
if (splitData !== undefined) {
if (splitData.hash && chunk.hash !== splitData.hash) {
// Split was successful, but hash doesn't equal
// We can throw away the split since it's useless now
invalidSplits.add(splitData);
}
if (
splitData !== undefined &&
splitData.hash &&
chunk.hash !== splitData.hash
) {
// Split was successful, but hash doesn't equal
// We can throw away the split since it's useless now
invalidSplits.add(splitData);
}
}

View File

@ -218,12 +218,12 @@ const createComparator = (property, comparator) => (a, b) =>
* @returns {0 | 1 | -1} result
*/
const compareNumbers = (a, b) => {
if (isNaN(a)) {
if (!isNaN(b)) {
if (Number.isNaN(a)) {
if (!Number.isNaN(b)) {
return 1;
}
} else {
if (isNaN(b)) {
if (Number.isNaN(b)) {
return -1;
}
if (a !== b) {

View File

@ -109,13 +109,14 @@ class InnerGraphPlugin {
parser.hooks.preStatement.tap(PLUGIN_NAME, statement => {
if (!InnerGraph.isEnabled(parser.state)) return;
if (parser.scope.topLevelScope === true) {
if (statement.type === "FunctionDeclaration") {
const name = statement.id ? statement.id.name : "*default*";
const fn = InnerGraph.tagTopLevelSymbol(parser, name);
statementWithTopLevelSymbol.set(statement, fn);
return true;
}
if (
parser.scope.topLevelScope === true &&
statement.type === "FunctionDeclaration"
) {
const name = statement.id ? statement.id.name : "*default*";
const fn = InnerGraph.tagTopLevelSymbol(parser, name);
statementWithTopLevelSymbol.set(statement, fn);
return true;
}
});

View File

@ -119,7 +119,7 @@ class LimitChunkCountPlugin {
/** @type {Map<Chunk, Set<ChunkCombination>>} */
const combinationsByChunk = new Map();
orderedChunks.forEach((b, bIdx) => {
for (const [bIdx, b] of orderedChunks.entries()) {
// create combination pairs with size and integrated size
for (let aIdx = 0; aIdx < bIdx; aIdx++) {
const a = orderedChunks[aIdx];
@ -149,8 +149,7 @@ class LimitChunkCountPlugin {
addToSetMap(combinationsByChunk, a, c);
addToSetMap(combinationsByChunk, b, c);
}
return combinations;
});
}
// list of modified chunks during this run
// combinations affected by this change are skipped to allow

View File

@ -773,14 +773,10 @@ class ModuleConcatenationPlugin {
);
if (runtimeCondition === false) continue;
if (runtimeCondition === true) continue outer;
if (currentRuntimeCondition !== false) {
currentRuntimeCondition = mergeRuntime(
currentRuntimeCondition,
runtimeCondition
);
} else {
currentRuntimeCondition = runtimeCondition;
}
currentRuntimeCondition =
currentRuntimeCondition !== false
? mergeRuntime(currentRuntimeCondition, runtimeCondition)
: runtimeCondition;
}
if (currentRuntimeCondition !== false) {
otherRuntimeConnections.push({

View File

@ -254,7 +254,7 @@ ${referencingAssets
})
.join("\n")}`);
compilation.errors.push(err);
return undefined;
return;
}
const hashes = new Set();
for (const { referencedHashes, ownHashes } of assets) {

View File

@ -323,11 +323,7 @@ const combineSizes = (a, b, combine) => {
/** @type {SplitChunksSizes} */
const result = {};
for (const key of aKeys) {
if (bKeys.has(key)) {
result[key] = combine(a[key], b[key]);
} else {
result[key] = a[key];
}
result[key] = bKeys.has(key) ? combine(a[key], b[key]) : a[key];
}
for (const key of bKeys) {
if (!aKeys.has(key)) {
@ -1434,7 +1430,7 @@ module.exports = class SplitChunksPlugin {
: item.cacheGroup.maxAsyncRequests
);
if (
isFinite(maxRequests) &&
Number.isFinite(maxRequests) &&
getRequests(chunk) >= maxRequests
) {
usedChunks.delete(chunk);

View File

@ -74,11 +74,10 @@ class GetChunkFilenameRuntimeModule extends RuntimeModule {
if (
chunkFilename.length ===
/** @type {string} */ (dynamicFilename).length
/** @type {string} */ (dynamicFilename).length &&
chunkFilename < /** @type {string} */ (dynamicFilename)
) {
if (chunkFilename < /** @type {string} */ (dynamicFilename)) {
return;
}
return;
}
}
maxChunks = set.size;
@ -137,7 +136,7 @@ class GetChunkFilenameRuntimeModule extends RuntimeModule {
return '" + chunkId + "';
}
const s = JSON.stringify(str);
return s.slice(1, s.length - 1);
return s.slice(1, -1);
};
/**
* @param {string} value string

View File

@ -138,7 +138,7 @@ const parseCacheControl = (cacheControl, requestTime) => {
if (cacheControl) {
const parsed = parseKeyValuePairs(cacheControl);
if (parsed["no-cache"]) storeCache = storeLock = false;
if (parsed["max-age"] && !isNaN(Number(parsed["max-age"]))) {
if (parsed["max-age"] && !Number.isNaN(Number(parsed["max-age"]))) {
validUntil = requestTime + Number(parsed["max-age"]) * 1000;
}
if (parsed["must-revalidate"]) validUntil = 0;

View File

@ -635,7 +635,7 @@ class ObjectMiddleware extends SerializerMiddleware {
if (nextItem === ESCAPE_ESCAPE_VALUE) {
return ESCAPE;
} else if (nextItem === ESCAPE_UNDEFINED) {
return undefined;
// Nothing
} else if (nextItem === ESCAPE_END_OBJECT) {
throw new Error(
`Unexpected end of object at position ${currentDataPos - 1}`
@ -668,11 +668,9 @@ class ObjectMiddleware extends SerializerMiddleware {
if (request && !loadedRequests.has(request)) {
let loaded = false;
for (const [regExp, loader] of loaders) {
if (regExp.test(request)) {
if (loader(request)) {
loaded = true;
break;
}
if (regExp.test(request) && loader(request)) {
loaded = true;
break;
}
}
if (!loaded) {

View File

@ -52,11 +52,10 @@ class Serializer {
/** @type {any} */
let current = value;
for (const middleware of this.deserializeMiddlewares) {
if (current && typeof current.then === "function") {
current = current.then(data => middleware.deserialize(data, ctx));
} else {
current = middleware.deserialize(current, ctx);
}
current =
current && typeof current.then === "function"
? current.then(data => middleware.deserialize(data, ctx))
: middleware.deserialize(current, ctx);
}
return current;
}

View File

@ -70,7 +70,7 @@ class SerializerMiddleware {
* @returns {object} options
*/
static getLazyOptions(fn) {
if (typeof fn !== "function") return undefined;
if (typeof fn !== "function") return;
return /** @type {any} */ (fn).options;
}
@ -79,7 +79,7 @@ class SerializerMiddleware {
* @returns {any} serialized value
*/
static getLazySerializedValue(fn) {
if (typeof fn !== "function") return undefined;
if (typeof fn !== "function") return;
return fn[LAZY_SERIALIZED_VALUE];
}

View File

@ -65,11 +65,7 @@ const extractCommithashByDomain = {
return;
}
if (!type) {
commithash = hash;
} else {
commithash = `#${commithash}`;
}
commithash = !type ? hash : `#${commithash}`;
if (project && project.endsWith(".git")) {
project = project.slice(0, -4);
@ -252,11 +248,9 @@ function canBeDecoded(str) {
function getGitUrlVersion(gitUrl) {
const oriGitUrl = gitUrl;
// github extreme shorthand
if (RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl)) {
gitUrl = `github:${gitUrl}`;
} else {
gitUrl = correctProtocol(gitUrl);
}
gitUrl = RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl)
? `github:${gitUrl}`
: correctProtocol(gitUrl);
gitUrl = correctUrl(gitUrl);

View File

@ -576,11 +576,10 @@ const SIMPLE_EXTRACTORS = {
if (type === LogType.groupEnd) {
groupStack.pop();
if (groupStack.length > 0) {
currentList = groupStack[groupStack.length - 1].children;
} else {
currentList = rootList;
}
currentList =
groupStack.length > 0
? groupStack[groupStack.length - 1].children
: rootList;
if (depthInCollapsedGroup > 0) depthInCollapsedGroup--;
continue;
}

View File

@ -625,7 +625,7 @@ const SIMPLE_PRINTERS = {
: `${bold(moduleName)}`,
"error.loc": (loc, { green }) => green(loc),
"error.message": (message, { bold, formatError }) =>
message.includes("\u001b[") ? message : bold(formatError(message)),
message.includes("\u001B[") ? message : bold(formatError(message)),
"error.details": (details, { formatError }) => formatError(details),
"error.filteredDetails": filteredDetails =>
filteredDetails ? `+ ${filteredDetails} hidden lines` : undefined,
@ -1198,12 +1198,12 @@ const SIMPLE_ELEMENT_JOINERS = {
};
const AVAILABLE_COLORS = {
bold: "\u001b[1m",
yellow: "\u001b[1m\u001b[33m",
red: "\u001b[1m\u001b[31m",
green: "\u001b[1m\u001b[32m",
cyan: "\u001b[1m\u001b[36m",
magenta: "\u001b[1m\u001b[35m"
bold: "\u001B[1m",
yellow: "\u001B[1m\u001B[33m",
red: "\u001B[1m\u001B[31m",
green: "\u001B[1m\u001B[32m",
cyan: "\u001B[1m\u001B[36m",
magenta: "\u001B[1m\u001B[35m"
};
const AVAILABLE_FORMATS = {
@ -1254,7 +1254,7 @@ const AVAILABLE_FORMATS = {
return `${boldQuantity ? bold(time) : time}${unit}`;
},
formatError: (message, { green, yellow, red }) => {
if (message.includes("\u001b[")) return message;
if (message.includes("\u001B[")) return message;
const highlights = [
{ regExp: /(Did you mean .+)/g, format: green },
{
@ -1345,11 +1345,11 @@ class DefaultStatsPrinterPlugin {
`${start}${
typeof str === "string"
? str.replace(
/((\u001b\[39m|\u001b\[22m|\u001b\[0m)+)/g,
/((\u001B\[39m|\u001B\[22m|\u001B\[0m)+)/g,
`$1${start}`
)
: str
}\u001b[39m\u001b[22m`;
}\u001B[39m\u001B[22m`;
} else {
context[color] = str => str;
}

View File

@ -56,7 +56,7 @@ class ArrayQueue {
*/
dequeue() {
if (this._listReversed.length === 0) {
if (this._list.length === 0) return undefined;
if (this._list.length === 0) return;
if (this._list.length === 1) return this._list.pop();
if (this._list.length < 16) return this._list.shift();
const temp = this._listReversed;

View File

@ -94,7 +94,7 @@ class LazyBucketSortedSet {
* @returns {T | undefined} an item
*/
popFirst() {
if (this.size === 0) return undefined;
if (this.size === 0) return;
this.size--;
if (this._unsortedItems.size > 0) {
for (const item of this._unsortedItems) {

View File

@ -48,7 +48,7 @@ class Queue {
*/
dequeue() {
const result = this._iterator.next();
if (result.done) return undefined;
if (result.done) return;
this._set.delete(result.value);
return result.value;
}

View File

@ -40,12 +40,10 @@ class Semaphore {
}
_continue() {
if (this.available > 0) {
if (this.waiters.length > 0) {
this.available--;
const callback = /** @type {(function(): void)} */ (this.waiters.pop());
callback();
}
if (this.available > 0 && this.waiters.length > 0) {
this.available--;
const callback = /** @type {(function(): void)} */ (this.waiters.pop());
callback();
}
}
}

View File

@ -115,7 +115,6 @@ class StackedMap {
}
this.map.set(item, TOMBSTONE);
}
return undefined;
}
_compress() {

View File

@ -57,7 +57,7 @@ class TupleQueue {
this._set.delete(...value);
return value;
}
return undefined;
return;
}
this._set.delete(...result.value);
return result.value;

View File

@ -36,7 +36,7 @@ function getScheme(specifier) {
(start < aLowerCaseCharCode || start > zLowerCaseCharCode) &&
(start < aUpperCaseCharCode || start > zUpperCaseCharCode)
) {
return undefined;
return;
}
let i = 1;
@ -49,12 +49,12 @@ function getScheme(specifier) {
ch === plusCharCode ||
ch === hyphenCharCode
) {
if (++i === specifier.length) return undefined;
if (++i === specifier.length) return;
ch = specifier.charCodeAt(i);
}
// Scheme must end with colon
if (ch !== colonCharCode) return undefined;
if (ch !== colonCharCode) return;
// Check for Windows absolute path
// https://url.spec.whatwg.org/#url-miscellaneous
@ -67,7 +67,7 @@ function getScheme(specifier) {
nextChar === hashCharCode ||
nextChar === queryCharCode
) {
return undefined;
return;
}
}

View File

@ -83,7 +83,7 @@ class WeakTupleMap {
let node = this;
for (let i = 0; i < args.length; i++) {
node = node._peek(args[i]);
if (node === undefined) return undefined;
if (node === undefined) return;
}
return node._getValue();
}
@ -158,10 +158,10 @@ class WeakTupleMap {
*/
_peek(thing) {
if (isWeakKey(thing)) {
if ((this.f & 4) !== 4) return undefined;
if ((this.f & 4) !== 4) return;
return /** @type {W<T, V>} */ (this.w).get(thing);
}
if ((this.f & 2) !== 2) return undefined;
if ((this.f & 2) !== 2) return;
return /** @type {M<T, V>} */ (this.m).get(thing);
}

View File

@ -282,7 +282,7 @@ class TwoKeyWeakMap {
get(key1, key2) {
const childMap = this._map.get(key1);
if (childMap === undefined) {
return undefined;
return;
}
return childMap.get(key2);
}

View File

@ -137,7 +137,6 @@ module.exports.arrayToSetDeprecation = (set, name) => {
for (const item of this) {
if (i++ === index) return item;
}
return undefined;
};
return fn;
};

View File

@ -115,9 +115,7 @@ const isTooBig = (size, maxSize) => {
const s = size[key];
if (s === 0) continue;
const maxSizeValue = maxSize[key];
if (typeof maxSizeValue === "number") {
if (s > maxSizeValue) return true;
}
if (typeof maxSizeValue === "number" && s > maxSizeValue) return true;
}
return false;
};
@ -132,9 +130,7 @@ const isTooSmall = (size, minSize) => {
const s = size[key];
if (s === 0) continue;
const minSizeValue = minSize[key];
if (typeof minSizeValue === "number") {
if (s < minSizeValue) return true;
}
if (typeof minSizeValue === "number" && s < minSizeValue) return true;
}
return false;
};
@ -150,9 +146,7 @@ const getTooSmallTypes = (size, minSize) => {
const s = size[key];
if (s === 0) continue;
const minSizeValue = minSize[key];
if (typeof minSizeValue === "number") {
if (s < minSizeValue) types.add(key);
}
if (typeof minSizeValue === "number" && s < minSizeValue) types.add(key);
}
return types;
};
@ -242,7 +236,7 @@ class Group {
lastNode = node;
}
}
if (resultNodes.length === this.nodes.length) return undefined;
if (resultNodes.length === this.nodes.length) return;
this.nodes = newNodes;
this.similarities = newSimilarities;
this.size = sumSize(newNodes);

View File

@ -42,18 +42,15 @@ const getPathInAst = (ast, node) => {
const nr = node.range;
const enterNode = n => {
if (!n) return undefined;
if (!n) return;
const r = n.range;
if (r) {
if (r[0] <= nr[0] && r[1] >= nr[1]) {
const path = getPathInAst(n, node);
if (path) {
path.push(n);
return path;
}
if (r && r[0] <= nr[0] && r[1] >= nr[1]) {
const path = getPathInAst(n, node);
if (path) {
path.push(n);
return path;
}
}
return undefined;
};
if (Array.isArray(ast)) {

View File

@ -15,8 +15,8 @@ const A_CODE = "a".charCodeAt(0);
module.exports = (hash, hashLength) => {
if (hashLength < 1) return "";
const slice = hash.slice(0, hashLength);
if (slice.match(/[^\d]/)) return slice;
if (/[^\d]/.test(slice)) return slice;
return `${String.fromCharCode(
A_CODE + (parseInt(hash[0], 10) % 6)
A_CODE + (Number.parseInt(hash[0], 10) % 6)
)}${slice.slice(1)}`;
};

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