pretty files

This commit is contained in:
Tobias Koppers 2021-05-11 09:31:46 +02:00
parent 504bda5821
commit b0fa9ccada
98 changed files with 752 additions and 805 deletions

4
declarations.d.ts vendored
View File

@ -251,9 +251,7 @@ declare module "webpack-sources" {
map(options?: MapOptions): Object;
sourceAndMap(
options?: MapOptions
): {
sourceAndMap(options?: MapOptions): {
source: string | Buffer;
map: Object;
};

View File

@ -90,9 +90,9 @@ class MultiItemCache {
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(data) {
return Promise.all(
this._items.map(item => item.storePromise(data))
).then(() => {});
return Promise.all(this._items.map(item => item.storePromise(data))).then(
() => {}
);
}
}

View File

@ -547,9 +547,8 @@ class Chunk {
xor.add(chunkGraph.getModuleHash(m, this.runtime));
}
xor.updateHash(hash);
const entryModules = chunkGraph.getChunkEntryModulesWithChunkGroupIterable(
this
);
const entryModules =
chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this);
for (const [m, chunkGroup] of entryModules) {
hash.update("entry");
hash.update(`${chunkGraph.getModuleId(m)}`);

View File

@ -510,7 +510,8 @@ class Compilation {
* @returns {FakeHook<Pick<AsyncSeriesHook<T>, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects
*/
const createProcessAssetsHook = (name, stage, getArgs, code) => {
const errorMessage = reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
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.`;
const getOptions = options => {
if (typeof options === "string") options = { name: options };
@ -1615,9 +1616,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
let creatingModuleDuringBuildSet = undefined;
if (!recursive && this.buildQueue.isProcessing(originModule)) {
// Track build dependency
creatingModuleDuringBuildSet = this.creatingModuleDuringBuild.get(
originModule
);
creatingModuleDuringBuildSet =
this.creatingModuleDuringBuild.get(originModule);
if (creatingModuleDuringBuildSet === undefined) {
creatingModuleDuringBuildSet = new Set();
this.creatingModuleDuringBuild.set(
@ -1746,11 +1746,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
module: result
};
}
const {
fileDependencies,
contextDependencies,
missingDependencies
} = result;
const { fileDependencies, contextDependencies, missingDependencies } =
result;
if (fileDependencies) {
this.fileDependencies.addAll(fileDependencies);
}
@ -2316,7 +2313,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}
] of this.entries) {
if (dependOn && runtime) {
const err = new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid.
const err =
new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid.
Entrypoints that depend on other entrypoints do not have their own runtime.
They will use the runtime(s) from referenced entrypoints instead.
Remove the 'runtime' option from the entrypoint.`);
@ -2357,11 +2355,12 @@ Remove the 'runtime' option from the entrypoint.`);
let chunk = this.namedChunks.get(runtime);
if (chunk) {
if (!runtimeChunks.has(chunk)) {
const err = new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'.
const err =
new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'.
It's not valid to use other entrypoints as runtime chunk.
Did you mean to use 'dependOn: ${JSON.stringify(
runtime
)}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used.
runtime
)}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used.
Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`);
const entryChunk = entry.getEntrypointChunk();
err.chunk = entryChunk;
@ -2621,12 +2620,8 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
_runCodeGenerationJobs(jobs, callback) {
let statModulesFromCache = 0;
let statModulesGenerated = 0;
const {
chunkGraph,
moduleGraph,
dependencyTemplates,
runtimeTemplate
} = this;
const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } =
this;
const results = this.codeGenerationResults;
const errors = [];
asyncLib.eachLimit(
@ -2773,17 +2768,15 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
chunkGraphEntries = this._getChunkGraphEntries()
} = {}) {
const context = { chunkGraph, codeGenerationResults };
const additionalModuleRuntimeRequirements = this.hooks
.additionalModuleRuntimeRequirements;
const additionalModuleRuntimeRequirements =
this.hooks.additionalModuleRuntimeRequirements;
const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule;
for (const module of modules) {
if (chunkGraph.getNumberOfModuleChunks(module) > 0) {
for (const runtime of chunkGraph.getModuleRuntimes(module)) {
let set;
const runtimeRequirements = codeGenerationResults.getRuntimeRequirements(
module,
runtime
);
const runtimeRequirements =
codeGenerationResults.getRuntimeRequirements(module, runtime);
if (runtimeRequirements && runtimeRequirements.size > 0) {
set = new Set(runtimeRequirements);
} else if (additionalModuleRuntimeRequirements.isUsed()) {
@ -2823,9 +2816,8 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
for (const treeEntry of chunkGraphEntries) {
const set = new Set();
for (const chunk of treeEntry.getAllReferencedChunks()) {
const runtimeRequirements = chunkGraph.getChunkRuntimeRequirements(
chunk
);
const runtimeRequirements =
chunkGraph.getChunkRuntimeRequirements(chunk);
for (const r of runtimeRequirements) set.add(r);
}
@ -3223,9 +3215,9 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
runtime,
runtimeTemplate
});
const moduleHashDigest = /** @type {string} */ (moduleHash.digest(
hashDigest
));
const moduleHashDigest = /** @type {string} */ (
moduleHash.digest(hashDigest)
);
chunkGraph.setModuleHashes(
module,
runtime,
@ -3354,10 +3346,11 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
}
}
circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId));
const err = new WebpackError(`Circular dependency between chunks with runtime (${Array.from(
circularRuntimeChunkInfo,
c => c.chunk.name || c.chunk.id
).join(", ")})
const err =
new WebpackError(`Circular dependency between chunks with runtime (${Array.from(
circularRuntimeChunkInfo,
c => c.chunk.name || c.chunk.id
).join(", ")})
This prevents using hashes of each other and should be avoided.`);
err.chunk = circularRuntimeChunkInfo[0].chunk;
this.warnings.push(err);
@ -3420,15 +3413,14 @@ This prevents using hashes of each other and should be avoided.`);
moduleGraph: this.moduleGraph,
runtimeTemplate: this.runtimeTemplate
});
const chunkHashDigest = /** @type {string} */ (chunkHash.digest(
hashDigest
));
const chunkHashDigest = /** @type {string} */ (
chunkHash.digest(hashDigest)
);
hash.update(chunkHashDigest);
chunk.hash = chunkHashDigest;
chunk.renderedHash = chunk.hash.substr(0, hashDigestLength);
const fullHashModules = chunkGraph.getChunkFullHashModulesIterable(
chunk
);
const fullHashModules =
chunkGraph.getChunkFullHashModulesIterable(chunk);
if (fullHashModules) {
fullHashChunks.add(chunk);
} else {
@ -3459,9 +3451,9 @@ This prevents using hashes of each other and should be avoided.`);
runtime: chunk.runtime,
runtimeTemplate
});
const moduleHashDigest = /** @type {string} */ (moduleHash.digest(
hashDigest
));
const moduleHashDigest = /** @type {string} */ (
moduleHash.digest(hashDigest)
);
const oldHash = chunkGraph.getModuleHash(module, chunk.runtime);
chunkGraph.setModuleHashes(
module,
@ -3474,9 +3466,9 @@ This prevents using hashes of each other and should be avoided.`);
const chunkHash = createHash(hashFunction);
chunkHash.update(chunk.hash);
chunkHash.update(this.hash);
const chunkHashDigest = /** @type {string} */ (chunkHash.digest(
hashDigest
));
const chunkHashDigest = /** @type {string} */ (
chunkHash.digest(hashDigest)
);
chunk.hash = chunkHashDigest;
chunk.renderedHash = chunk.hash.substr(0, hashDigestLength);
this.hooks.contentHash.call(chunk);
@ -4051,11 +4043,8 @@ This prevents using hashes of each other and should be avoided.`);
// Create new chunk graph, chunk and entrypoint for the build time execution
const chunkGraph = new ChunkGraph(this.moduleGraph);
const runtime = "build time";
const {
hashFunction,
hashDigest,
hashDigestLength
} = this.outputOptions;
const { hashFunction, hashDigest, hashDigestLength } =
this.outputOptions;
const runtimeTemplate = this.runtimeTemplate;
const chunk = new Chunk("build time chunk");
@ -4151,9 +4140,8 @@ This prevents using hashes of each other and should be avoided.`);
});
this.chunkGraph = old;
const runtimeModules = chunkGraph.getChunkRuntimeModulesIterable(
chunk
);
const runtimeModules =
chunkGraph.getChunkRuntimeModulesIterable(chunk);
// Hash runtime modules
for (const module of runtimeModules) {

View File

@ -590,9 +590,8 @@ class Compiler {
allTargetPaths.add(targetPath);
// check if the target file has already been written by this Compiler
const targetFileGeneration = this._assetEmittingWrittenFiles.get(
targetPath
);
const targetFileGeneration =
this._assetEmittingWrittenFiles.get(targetPath);
// create an cache entry for this Source if not already existing
let cacheEntry = this._assetEmittingSourceCache.get(source);
@ -622,7 +621,8 @@ class Compiler {
}
alreadyWritten();
} else {
const err = new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file.
const err =
new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file.
This will lead to a race-condition and corrupted files on case-insensitive file systems.
${targetPath}
${other}`);

View File

@ -7,7 +7,8 @@
/** @typedef {import("./Module")} Module */
const MODULE_REFERENCE_REGEXP = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(?:_asiSafe(\d))?__$/;
const MODULE_REFERENCE_REGEXP =
/^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(?:_asiSafe(\d))?__$/;
const DEFAULT_EXPORT = "__WEBPACK_DEFAULT_EXPORT__";
const NAMESPACE_OBJECT_EXPORT = "__WEBPACK_NAMESPACE_OBJECT__";

View File

@ -1016,9 +1016,9 @@ module.exports = webpackEmptyAsyncContext;`;
this.getSource(this.getSourceString(this.options.mode, context))
);
const set = new Set();
const allDeps = /** @type {ContextElementDependency[]} */ (this.dependencies.concat(
this.blocks.map(b => b.dependencies[0])
));
const allDeps = /** @type {ContextElementDependency[]} */ (
this.dependencies.concat(this.blocks.map(b => b.dependencies[0]))
);
set.add(RuntimeGlobals.module);
set.add(RuntimeGlobals.hasOwnProperty);
if (allDeps.length > 0) {

View File

@ -104,9 +104,10 @@ class ContextReplacementPlugin {
result.regExp = newContentRegExp;
}
if (typeof newContentCreateContextMap === "function") {
result.resolveDependencies = createResolveDependenciesFromContextMap(
newContentCreateContextMap
);
result.resolveDependencies =
createResolveDependenciesFromContextMap(
newContentCreateContextMap
);
}
if (typeof newContentCallback === "function") {
const origResource = result.resource;

View File

@ -89,9 +89,9 @@ class RuntimeValue {
module: parser.state.module,
key,
get version() {
return /** @type {string} */ (valueCacheVersions.get(
VALUE_DEP_PREFIX + key
));
return /** @type {string} */ (
valueCacheVersions.get(VALUE_DEP_PREFIX + key)
);
}
});
}
@ -286,11 +286,13 @@ class DefinePlugin {
);
const { runtimeTemplate } = compilation;
const mainValue = /** @type {Set<string>} */ (provide(
compilation.valueCacheVersions,
VALUE_DEP_MAIN,
() => new Set()
));
const mainValue = /** @type {Set<string>} */ (
provide(
compilation.valueCacheVersions,
VALUE_DEP_MAIN,
() => new Set()
)
);
/**
* Handler
@ -313,10 +315,12 @@ class DefinePlugin {
);
};
const withValueDependency = (key, fn) => (...args) => {
addValueDependency(key);
return fn(...args);
};
const withValueDependency =
(key, fn) =>
(...args) => {
addValueDependency(key);
return fn(...args);
};
/**
* Walk definitions

View File

@ -91,7 +91,9 @@ class EvalSourceMapDevToolPlugin {
} else if (m instanceof ConcatenatedModule) {
const concatModule = /** @type {ConcatenatedModule} */ (m);
if (concatModule.rootModule instanceof NormalModule) {
const module = /** @type {NormalModule} */ (concatModule.rootModule);
const module = /** @type {NormalModule} */ (
concatModule.rootModule
);
if (!matchModule(module.resource)) {
return result(source);
}

View File

@ -1160,12 +1160,8 @@ class FileSystemInfo {
* @returns {void}
*/
resolveBuildDependencies(context, deps, callback) {
const {
resolveContext,
resolveEsm,
resolveCjs,
resolveCjsAsChild
} = this._createBuildDependenciesResolvers();
const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } =
this._createBuildDependenciesResolvers();
/** @type {Set<string>} */
const files = new Set();
@ -1547,9 +1543,8 @@ class FileSystemInfo {
break;
}
case RBDT_DIRECTORY_DEPENDENCIES: {
const match = /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(
path
);
const match =
/(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path);
const packagePath = match ? match[1] : path;
const packageJson = join(this.fs, packagePath, "package.json");
this.fs.readFile(packageJson, (err, content) => {
@ -1637,12 +1632,8 @@ class FileSystemInfo {
* @returns {void}
*/
checkResolveResultsValid(resolveResults, callback) {
const {
resolveCjs,
resolveCjsAsChild,
resolveEsm,
resolveContext
} = this._createBuildDependenciesResolvers();
const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } =
this._createBuildDependenciesResolvers();
asyncLib.eachLimit(
resolveResults,
20,
@ -1844,11 +1835,12 @@ class FileSystemInfo {
unsharedManagedFiles
);
}
const unsharedManagedContexts = this._managedContextsOptimization.optimize(
managedContexts,
undefined,
children
);
const unsharedManagedContexts =
this._managedContextsOptimization.optimize(
managedContexts,
undefined,
children
);
if (managedContexts.size !== 0) {
snapshot.setManagedContexts(managedContexts);
this._managedContextsOptimization.storeUnsharedSnapshot(
@ -1856,11 +1848,12 @@ class FileSystemInfo {
unsharedManagedContexts
);
}
const unsharedManagedMissing = this._managedMissingOptimization.optimize(
managedMissing,
undefined,
children
);
const unsharedManagedMissing =
this._managedMissingOptimization.optimize(
managedMissing,
undefined,
children
);
if (managedMissing.size !== 0) {
snapshot.setManagedMissing(managedMissing);
this._managedMissingOptimization.storeUnsharedSnapshot(
@ -2064,11 +2057,12 @@ class FileSystemInfo {
}
break;
case 1:
unsharedContextTimestamps = this._contextTimestampsOptimization.optimize(
capturedDirectories,
startTime,
children
);
unsharedContextTimestamps =
this._contextTimestampsOptimization.optimize(
capturedDirectories,
startTime,
children
);
for (const path of capturedDirectories) {
const cache = this._contextTimestamps.get(path);
if (cache !== undefined) {

View File

@ -225,7 +225,8 @@ class FlagDependencyExportsPlugin {
}
if (exports) {
const nestedExportsInfo = exportInfo.createNestedExportsInfo();
const nestedExportsInfo =
exportInfo.createNestedExportsInfo();
mergeExports(nestedExportsInfo, exports);
}
@ -247,12 +248,12 @@ class FlagDependencyExportsPlugin {
const target = exportInfo.getTarget(moduleGraph);
let targetExportsInfo = undefined;
if (target) {
const targetModuleExportsInfo = moduleGraph.getExportsInfo(
target.module
);
targetExportsInfo = targetModuleExportsInfo.getNestedExportsInfo(
target.export
);
const targetModuleExportsInfo =
moduleGraph.getExportsInfo(target.module);
targetExportsInfo =
targetModuleExportsInfo.getNestedExportsInfo(
target.export
);
// add dependency for this module
const set = dependencies.get(target.module);
if (set === undefined) {

View File

@ -201,10 +201,8 @@ class FlagDependencyUsagePlugin {
if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) {
continue;
}
const referencedExports = compilation.getDependencyReferencedExports(
dep,
runtime
);
const referencedExports =
compilation.getDependencyReferencedExports(dep, runtime);
if (
oldReferencedExports === undefined ||
oldReferencedExports === NO_EXPORTS_REFERENCED ||

View File

@ -87,10 +87,8 @@ class HotModuleReplacementPlugin {
const runtimeRequirements = [RuntimeGlobals.module];
const createAcceptHandler = (parser, ParamDependency) => {
const {
hotAcceptCallback,
hotAcceptWithoutCallback
} = HotModuleReplacementPlugin.getParserHooks(parser);
const { hotAcceptCallback, hotAcceptWithoutCallback } =
HotModuleReplacementPlugin.getParserHooks(parser);
return expr => {
const module = parser.state.module;
@ -306,9 +304,7 @@ class HotModuleReplacementPlugin {
}
records.chunkModuleIds = {};
for (const chunk of compilation.chunks) {
records.chunkModuleIds[
chunk.id
] = Array.from(
records.chunkModuleIds[chunk.id] = Array.from(
chunkGraph.getOrderedChunkModulesIterable(
chunk,
compareModulesById(chunkGraph)
@ -341,9 +337,8 @@ class HotModuleReplacementPlugin {
return chunkGraph.getModuleHash(module, chunk.runtime);
}
};
const fullHashModulesInThisChunk = chunkGraph.getChunkFullHashModulesSet(
chunk
);
const fullHashModulesInThisChunk =
chunkGraph.getChunkFullHashModulesSet(chunk);
if (fullHashModulesInThisChunk !== undefined) {
for (const module of fullHashModulesInThisChunk) {
fullHashModules.add(module, chunk);
@ -451,16 +446,14 @@ class HotModuleReplacementPlugin {
allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime);
}
forEachRuntime(allOldRuntime, runtime => {
const {
path: filename,
info: assetInfo
} = compilation.getPathWithInfo(
compilation.outputOptions.hotUpdateMainFilename,
{
hash: records.hash,
runtime
}
);
const { path: filename, info: assetInfo } =
compilation.getPathWithInfo(
compilation.outputOptions.hotUpdateMainFilename,
{
hash: records.hash,
runtime
}
);
hotUpdateMainContentByRuntime.set(runtime, {
updatedChunkIds: new Set(),
removedChunkIds: new Set(),
@ -516,9 +509,8 @@ class HotModuleReplacementPlugin {
newRuntimeModules = Array.from(
chunkGraph.getChunkRuntimeModulesIterable(currentChunk)
).filter(module => updatedModules.has(module, currentChunk));
const fullHashModules = chunkGraph.getChunkFullHashModulesIterable(
currentChunk
);
const fullHashModules =
chunkGraph.getChunkFullHashModulesIterable(currentChunk);
newFullHashModules =
fullHashModules &&
Array.from(fullHashModules).filter(module =>
@ -631,13 +623,11 @@ class HotModuleReplacementPlugin {
filename = entry.filename;
assetInfo = entry.info;
} else {
({
path: filename,
info: assetInfo
} = compilation.getPathWithInfo(
entry.filenameTemplate,
entry.pathOptions
));
({ path: filename, info: assetInfo } =
compilation.getPathWithInfo(
entry.filenameTemplate,
entry.pathOptions
));
}
const source = entry.render();
compilation.additionalChunkAssets.push(filename);

View File

@ -34,7 +34,8 @@ class JavascriptMetaInfoPlugin {
let topLevelDeclarations =
parser.state.module.buildInfo.topLevelDeclarations;
if (topLevelDeclarations === undefined) {
topLevelDeclarations = parser.state.module.buildInfo.topLevelDeclarations = new Set();
topLevelDeclarations =
parser.state.module.buildInfo.topLevelDeclarations = new Set();
}
for (const name of parser.scope.definitions.asSet()) {
const freeInfo = parser.getFreeInfoFromVariable(name);

View File

@ -239,9 +239,8 @@ class MainTemplate {
"chunkIdExpression"
]),
get jsonpScript() {
const hooks = getLoadScriptRuntimeModule().getCompilationHooks(
compilation
);
const hooks =
getLoadScriptRuntimeModule().getCompilationHooks(compilation);
return hooks.createScript;
},
get linkPrefetch() {

View File

@ -12,14 +12,16 @@ const ModuleFilenameHelpers = exports;
// TODO webpack 6: consider removing these
ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi;
ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE =
/\[all-?loaders\]\[resource\]/gi;
ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
ModuleFilenameHelpers.RESOURCE = "[resource]";
ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
// cSpell:words olute
ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi;
ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH =
/\[abs(olute)?-?resource-?path\]/gi;
ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";

View File

@ -183,5 +183,9 @@ class ModuleGraphConnection {
module.exports = ModuleGraphConnection;
module.exports.addConnectionStates = addConnectionStates;
module.exports.TRANSITIVE_ONLY = /** @type {typeof TRANSITIVE_ONLY} */ (TRANSITIVE_ONLY);
module.exports.CIRCULAR_CONNECTION = /** @type {typeof CIRCULAR_CONNECTION} */ (CIRCULAR_CONNECTION);
module.exports.TRANSITIVE_ONLY = /** @type {typeof TRANSITIVE_ONLY} */ (
TRANSITIVE_ONLY
);
module.exports.CIRCULAR_CONNECTION = /** @type {typeof CIRCULAR_CONNECTION} */ (
CIRCULAR_CONNECTION
);

View File

@ -222,9 +222,8 @@ class ModuleInfoHeaderPlugin {
)}`
) + "\n"
);
const optimizationBailout = moduleGraph.getOptimizationBailout(
module
);
const optimizationBailout =
moduleGraph.getOptimizationBailout(module);
if (optimizationBailout) {
for (const text of optimizationBailout) {
let code;

View File

@ -765,7 +765,11 @@ class NormalModule extends Module {
},
(err, result) => {
// Cleanup loaderContext to avoid leaking memory in ICs
loaderContext._compilation = loaderContext._compiler = loaderContext._module = loaderContext.fs = undefined;
loaderContext._compilation =
loaderContext._compiler =
loaderContext._module =
loaderContext.fs =
undefined;
if (!result) {
return processResult(
@ -958,7 +962,8 @@ class NormalModule extends Module {
checkDependencies(this.buildInfo.missingDependencies);
checkDependencies(this.buildInfo.contextDependencies);
if (nonAbsoluteDependencies !== undefined) {
const InvalidDependenciesModuleWarning = getInvalidDependenciesModuleWarning();
const InvalidDependenciesModuleWarning =
getInvalidDependenciesModuleWarning();
this.addWarning(
new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies)
);

View File

@ -48,10 +48,11 @@ class RecordIdsPlugin {
apply(compiler) {
const portableIds = this.options.portableIds;
const makePathsRelative = identifierUtils.makePathsRelative.bindContextCache(
compiler.context,
compiler.root
);
const makePathsRelative =
identifierUtils.makePathsRelative.bindContextCache(
compiler.context,
compiler.root
);
/**
* @param {Module} module the module

View File

@ -42,9 +42,9 @@ const convertToResolveOptions = resolveOptionsWithDepType => {
...remaining,
plugins:
plugins &&
/** @type {ResolvePluginInstance[]} */ (plugins.filter(
item => item !== "..."
))
/** @type {ResolvePluginInstance[]} */ (
plugins.filter(item => item !== "...")
)
};
if (!partialOptions.fileSystem) {
@ -53,7 +53,10 @@ const convertToResolveOptions = resolveOptionsWithDepType => {
);
}
// These weird types validate that we checked all non-optional properties
const options = /** @type {Partial<ResolveOptions> & Pick<ResolveOptions, "fileSystem">} */ (partialOptions);
const options =
/** @type {Partial<ResolveOptions> & Pick<ResolveOptions, "fileSystem">} */ (
partialOptions
);
return removeOperations(
resolveByProperty(options, "byDependency", dependencyType)
@ -124,9 +127,9 @@ module.exports = class ResolverFactory {
const resolveOptions = convertToResolveOptions(
this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType)
);
const resolver = /** @type {ResolverWithOptions} */ (Factory.createResolver(
resolveOptions
));
const resolver = /** @type {ResolverWithOptions} */ (
Factory.createResolver(resolveOptions)
);
if (!resolver) {
throw new Error("No resolver created");
}

View File

@ -430,19 +430,20 @@ class SourceMapDevToolPlugin {
currentSourceMappingURLComment !== false &&
/\.css($|\?)/i.test(file)
) {
currentSourceMappingURLComment = currentSourceMappingURLComment.replace(
/^\n\/\/(.*)$/,
"\n/*$1*/"
);
currentSourceMappingURLComment =
currentSourceMappingURLComment.replace(
/^\n\/\/(.*)$/,
"\n/*$1*/"
);
}
const sourceMapString = JSON.stringify(sourceMap);
if (sourceMapFilename) {
let filename = file;
const sourceMapContentHash =
usesContentHash &&
/** @type {string} */ (createHash("md4")
.update(sourceMapString)
.digest("hex"));
/** @type {string} */ (
createHash("md4").update(sourceMapString).digest("hex")
);
const pathParams = {
chunk,
filename: options.fileContext
@ -454,13 +455,11 @@ class SourceMapDevToolPlugin {
: filename,
contentHash: sourceMapContentHash
};
const {
path: sourceMapFile,
info: sourceMapInfo
} = compilation.getPathWithInfo(
sourceMapFilename,
pathParams
);
const { path: sourceMapFile, info: sourceMapInfo } =
compilation.getPathWithInfo(
sourceMapFilename,
pathParams
);
const sourceMapUrl = options.publicPath
? options.publicPath + sourceMapFile
: relative(

View File

@ -413,5 +413,7 @@ class Template {
}
module.exports = Template;
module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = NUMBER_OF_IDENTIFIER_START_CHARS;
module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS;
module.exports.NUMBER_OF_IDENTIFIER_START_CHARS =
NUMBER_OF_IDENTIFIER_START_CHARS;
module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS;

View File

@ -310,7 +310,8 @@ class Watching {
this.watcher.getAggregatedRemovals &&
this.watcher.getAggregatedRemovals();
this.compiler.fileTimestamps = this.watcher.getFileTimeInfoEntries();
this.compiler.contextTimestamps = this.watcher.getContextTimeInfoEntries();
this.compiler.contextTimestamps =
this.watcher.getContextTimeInfoEntries();
this.pausedWatcher = this.watcher;
this.watcher.pause();
this.watcher = null;

View File

@ -170,9 +170,9 @@ class AssetGenerator extends Generator {
hash.update(runtimeTemplate.outputOptions.hashSalt);
}
hash.update(originalSource.buffer());
const fullHash = /** @type {string} */ (hash.digest(
runtimeTemplate.outputOptions.hashDigest
));
const fullHash = /** @type {string} */ (
hash.digest(runtimeTemplate.outputOptions.hashDigest)
);
const contentHash = fullHash.slice(
0,
runtimeTemplate.outputOptions.hashDigestLength
@ -183,26 +183,9 @@ class AssetGenerator extends Generator {
module.matchResource || module.resource,
runtimeTemplate.compilation.compiler.root
).replace(/^\.\//, "");
let {
path: filename,
info: assetInfo
} = runtimeTemplate.compilation.getAssetPathWithInfo(
assetModuleFilename,
{
module,
runtime,
filename: sourceFilename,
chunkGraph,
contentHash
}
);
let publicPath;
if (this.publicPath) {
const {
path,
info
} = runtimeTemplate.compilation.getAssetPathWithInfo(
this.publicPath,
let { path: filename, info: assetInfo } =
runtimeTemplate.compilation.getAssetPathWithInfo(
assetModuleFilename,
{
module,
runtime,
@ -211,6 +194,19 @@ class AssetGenerator extends Generator {
contentHash
}
);
let publicPath;
if (this.publicPath) {
const { path, info } =
runtimeTemplate.compilation.getAssetPathWithInfo(
this.publicPath,
{
module,
runtime,
filename: sourceFilename,
chunkGraph,
contentHash
}
);
publicPath = JSON.stringify(path);
assetInfo = mergeAssetInfo(assetInfo, info);
} else {

View File

@ -519,7 +519,8 @@ const visitModules = (
if (skipConnectionBuffer.length > 0) {
let { skippedModuleConnections } = chunkGroupInfo;
if (skippedModuleConnections === undefined) {
chunkGroupInfo.skippedModuleConnections = skippedModuleConnections = new Set();
chunkGroupInfo.skippedModuleConnections = skippedModuleConnections =
new Set();
}
for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) {
skippedModuleConnections.add(skipConnectionBuffer[i]);
@ -695,7 +696,8 @@ const visitModules = (
let resultingAvailableModules;
if (minAvailableModules.size > minAvailableModules.plus.size) {
// resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus)
resultingAvailableModules = /** @type {Set<Module> & {plus: Set<Module>}} */ (new Set());
resultingAvailableModules =
/** @type {Set<Module> & {plus: Set<Module>}} */ (new Set());
for (const module of minAvailableModules.plus)
minAvailableModules.add(module);
minAvailableModules.plus = EMPTY_SET;
@ -703,9 +705,10 @@ const visitModules = (
chunkGroupInfo.minAvailableModulesOwned = false;
} else {
// resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus)
resultingAvailableModules = /** @type {Set<Module> & {plus: Set<Module>}} */ (new Set(
minAvailableModules
));
resultingAvailableModules =
/** @type {Set<Module> & {plus: Set<Module>}} */ (
new Set(minAvailableModules)
);
resultingAvailableModules.plus = minAvailableModules.plus;
}
@ -715,7 +718,8 @@ const visitModules = (
resultingAvailableModules.add(m);
}
}
return (chunkGroupInfo.resultingAvailableModules = resultingAvailableModules);
return (chunkGroupInfo.resultingAvailableModules =
resultingAvailableModules);
};
const processConnectQueue = () => {
@ -732,9 +736,8 @@ const visitModules = (
}
// 2. Calculate resulting available modules
const resultingAvailableModules = calculateResultingAvailableModules(
chunkGroupInfo
);
const resultingAvailableModules =
calculateResultingAvailableModules(chunkGroupInfo);
const runtime = chunkGroupInfo.runtime;
@ -800,9 +803,8 @@ const visitModules = (
if (!availableModules.has(m) && !availableModules.plus.has(m)) {
// We can't remove modules from the plus part
// so we need to merge plus into the normal part to allow modifying it
const iterator = cachedMinAvailableModules.plus[
Symbol.iterator
]();
const iterator =
cachedMinAvailableModules.plus[Symbol.iterator]();
// fast forward add all modules until m
/** @type {IteratorResult<Module>} */
let it;
@ -951,13 +953,12 @@ const visitModules = (
statForkedMergedModulesCountPlus += availableModules.plus.size;
// construct a new Set as intersection of cachedMinAvailableModules and availableModules
// we already know that all modules directly from cachedMinAvailableModules are in availableModules too
const newSet = /** @type {ModuleSetPlus} */ (new Set(
cachedMinAvailableModules
));
const newSet = /** @type {ModuleSetPlus} */ (
new Set(cachedMinAvailableModules)
);
newSet.plus = EMPTY_SET;
const iterator = cachedMinAvailableModules.plus[
Symbol.iterator
]();
const iterator =
cachedMinAvailableModules.plus[Symbol.iterator]();
// fast forward add all modules until m
/** @type {IteratorResult<Module>} */
let it;
@ -1018,9 +1019,8 @@ const visitModules = (
};
// combine minAvailableModules from all resultingAvailableModules
for (const source of info.availableSources) {
const resultingAvailableModules = calculateResultingAvailableModules(
source
);
const resultingAvailableModules =
calculateResultingAvailableModules(source);
mergeSet(resultingAvailableModules);
mergeSet(resultingAvailableModules.plus);
}

View File

@ -1041,7 +1041,8 @@ class PackFileCacheStrategy {
if (newBuildDependencies)
this.newBuildDependencies.addAll(newBuildDependencies);
this.resolveResults = resolveResults;
this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot;
this.resolveBuildDependenciesSnapshot =
resolveBuildDependenciesSnapshot;
return pack;
}
return new Pack(logger, this.maxAge);
@ -1163,10 +1164,11 @@ class PackFileCacheStrategy {
);
}
if (this.resolveBuildDependenciesSnapshot) {
this.resolveBuildDependenciesSnapshot = this.fileSystemInfo.mergeSnapshots(
this.resolveBuildDependenciesSnapshot,
snapshot
);
this.resolveBuildDependenciesSnapshot =
this.fileSystemInfo.mergeSnapshots(
this.resolveBuildDependenciesSnapshot,
snapshot
);
} else {
this.resolveBuildDependenciesSnapshot = snapshot;
}
@ -1194,10 +1196,11 @@ class PackFileCacheStrategy {
this.logger.debug("Captured build dependencies");
if (this.buildSnapshot) {
this.buildSnapshot = this.fileSystemInfo.mergeSnapshots(
this.buildSnapshot,
snapshot
);
this.buildSnapshot =
this.fileSystemInfo.mergeSnapshots(
this.buildSnapshot,
snapshot
);
} else {
this.buildSnapshot = snapshot;
}

View File

@ -318,9 +318,10 @@ const applyCacheDefaults = (cache, { name, mode, development }) => {
const applySnapshotDefaults = (snapshot, { production }) => {
A(snapshot, "managedPaths", () => {
if (process.versions.pnp === "3") {
const match = /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve("watchpack")
);
const match =
/^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve("watchpack")
);
if (match) {
return [path.resolve(match[1], "unplugged")];
}
@ -337,16 +338,18 @@ const applySnapshotDefaults = (snapshot, { production }) => {
});
A(snapshot, "immutablePaths", () => {
if (process.versions.pnp === "1") {
const match = /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
require.resolve("watchpack")
);
const match =
/^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
require.resolve("watchpack")
);
if (match) {
return [match[1]];
}
} else if (process.versions.pnp === "3") {
const match = /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve("watchpack")
);
const match =
/^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve("watchpack")
);
if (match) {
return [match[1]];
}

View File

@ -92,9 +92,9 @@ const keyedNestedConfig = (value, fn, customKeys) => {
? {}
: Object.keys(value).reduce(
(obj, key) => (
(obj[key] = (customKeys && key in customKeys
? customKeys[key]
: fn)(value[key])),
(obj[key] = (
customKeys && key in customKeys ? customKeys[key] : fn
)(value[key])),
obj
),
/** @type {Record<string, R>} */ ({})
@ -163,10 +163,10 @@ const getNormalizedWebpackOptions = config => {
config.entry === undefined
? { main: {} }
: typeof config.entry === "function"
? (fn => () =>
Promise.resolve().then(fn).then(getNormalizedEntryStatic))(
config.entry
)
? (
fn => () =>
Promise.resolve().then(fn).then(getNormalizedEntryStatic)
)(config.entry)
: getNormalizedEntryStatic(config.entry),
experiments: cloneObject(config.experiments),
externals: config.externals,

View File

@ -332,9 +332,10 @@ const interceptAllParserHooks = (moduleFactory, tracer) => {
const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => {
interceptAllHooksFor(
{
hooks: require("../javascript/JavascriptModulesPlugin").getCompilationHooks(
compilation
)
hooks:
require("../javascript/JavascriptModulesPlugin").getCompilationHooks(
compilation
)
},
tracer,
"JavascriptModulesPlugin"

View File

@ -77,9 +77,9 @@ AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends (
{ runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements }
) {
const dep = /** @type {AMDRequireDependency} */ (dependency);
const depBlock = /** @type {AsyncDependenciesBlock} */ (moduleGraph.getParentBlock(
dep
));
const depBlock = /** @type {AsyncDependenciesBlock} */ (
moduleGraph.getParentBlock(dep)
);
const promise = runtimeTemplate.blockPromise({
chunkGraph,
block: depBlock,

View File

@ -230,9 +230,8 @@ class CommonJsExportRequireDependency extends ModuleDependency {
if (name === "__esModule" && isNamespaceImport) {
exports.add(name);
} else if (importedExportsInfo) {
const importedExportInfo = importedExportsInfo.getReadOnlyExportInfo(
name
);
const importedExportInfo =
importedExportsInfo.getReadOnlyExportInfo(name);
if (importedExportInfo.provided === false) continue;
exports.add(name);
if (importedExportInfo.provided === true) continue;

View File

@ -192,7 +192,9 @@ class CommonJsExportsParserPlugin {
parser.hooks.call
.for("Object.defineProperty")
.tap("CommonJsExportsParserPlugin", expression => {
const expr = /** @type {import("estree").CallExpression} */ (expression);
const expr = /** @type {import("estree").CallExpression} */ (
expression
);
if (!parser.isStatementLevelExpression(expr)) return;
if (expr.arguments.length !== 3) return;
if (expr.arguments[0].type === "SpreadElement") return;

View File

@ -182,10 +182,8 @@ class CommonJsImportsParserPlugin {
};
const createRequireHandler = callNew => expr => {
if (options.commonjsMagicComments) {
const {
options: requireOptions,
errors: commentErrors
} = parser.parseCommentOptions(expr.range);
const { options: requireOptions, errors: commentErrors } =
parser.parseCommentOptions(expr.range);
if (commentErrors) {
for (const e of commentErrors) {

View File

@ -265,13 +265,14 @@ class NodeModuleDecoratorRuntimeModule extends RuntimeModule {
generate() {
const { runtimeTemplate } = this.compilation;
return Template.asString([
`${
RuntimeGlobals.nodeModuleDecorator
} = ${runtimeTemplate.basicFunction("module", [
"module.paths = [];",
"if (!module.children) module.children = [];",
"return module;"
])};`
`${RuntimeGlobals.nodeModuleDecorator} = ${runtimeTemplate.basicFunction(
"module",
[
"module.paths = [];",
"if (!module.children) module.children = [];",
"return module;"
]
)};`
]);
}
}

View File

@ -45,6 +45,7 @@ makeSerializable(
"webpack/lib/dependencies/CommonJsRequireContextDependency"
);
CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall;
CommonJsRequireContextDependency.Template =
ContextDependencyTemplateAsRequireCall;
module.exports = CommonJsRequireContextDependency;

View File

@ -61,10 +61,11 @@ exports.create = (Dep, range, param, expr, options, contextOptions, parser) => {
const valueRange = param.range;
const { context, prefix } = splitContextFromPrefix(prefixRaw);
const { path: postfix, query, fragment } = parseResource(
postfixRaw,
parser
);
const {
path: postfix,
query,
fragment
} = parseResource(postfixRaw, parser);
// When there are more than two quasis, the generated RegExp can be more precise
// We join the quasis with the expression regexp
@ -160,10 +161,11 @@ exports.create = (Dep, range, param, expr, options, contextOptions, parser) => {
param.postfix && param.postfix.isString() ? param.postfix.range : null;
const valueRange = param.range;
const { context, prefix } = splitContextFromPrefix(prefixRaw);
const { path: postfix, query, fragment } = parseResource(
postfixRaw,
parser
);
const {
path: postfix,
query,
fragment
} = parseResource(postfixRaw, parser);
const regExp = new RegExp(
`^${quoteMeta(prefix)}${options.wrappedContextRegExp.source}${quoteMeta(
postfix

View File

@ -411,9 +411,8 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
const ignoredExports = new Set(["default", ...this.activeExports]);
let hiddenExports = undefined;
const otherStarExports = this._discoverActiveExportsFromOtherStarExports(
moduleGraph
);
const otherStarExports =
this._discoverActiveExportsFromOtherStarExports(moduleGraph);
if (otherStarExports !== undefined) {
hiddenExports = new Set();
for (let i = 0; i < otherStarExports.namesSlice; i++) {
@ -441,9 +440,8 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
const name = exportInfo.name;
if (ignoredExports.has(name)) continue;
if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
const importedExportInfo = importedExportsInfo.getReadOnlyExportInfo(
name
);
const importedExportInfo =
importedExportsInfo.getReadOnlyExportInfo(name);
if (importedExportInfo.provided === false) continue;
if (hiddenExports !== undefined && hiddenExports.has(name)) {
hidden.add(name);
@ -763,9 +761,8 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
`(reexported as '${this.name}')`
);
if (ids.length === 0 && this.name === null) {
const potentialConflicts = this._discoverActiveExportsFromOtherStarExports(
moduleGraph
);
const potentialConflicts =
this._discoverActiveExportsFromOtherStarExports(moduleGraph);
if (potentialConflicts && potentialConflicts.namesSlice > 0) {
const ownNames = new Set(
potentialConflicts.names.slice(
@ -802,9 +799,8 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
conflictingModule,
exportInfo.name
);
const conflictingTarget = conflictingExportInfo.getTerminalBinding(
moduleGraph
);
const conflictingTarget =
conflictingExportInfo.getTerminalBinding(moduleGraph);
if (!conflictingTarget) continue;
if (target === conflictingTarget) continue;
const list = conflicts.get(conflictingDependency.request);
@ -882,7 +878,9 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
apply(dependency, source, templateContext) {
const { moduleGraph, runtime, concatenationScope } = templateContext;
const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ (dependency);
const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ (
dependency
);
const mode = dep.getMode(moduleGraph, runtime);

View File

@ -152,10 +152,8 @@ module.exports = class HarmonyImportDependencyParserPlugin {
InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
return true;
});
const {
hotAcceptCallback,
hotAcceptWithoutCallback
} = HotModuleReplacementPlugin.getParserHooks(parser);
const { hotAcceptCallback, hotAcceptWithoutCallback } =
HotModuleReplacementPlugin.getParserHooks(parser);
hotAcceptCallback.tap(
"HarmonyImportDependencyParserPlugin",
(expr, requests) => {

View File

@ -243,12 +243,8 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
*/
apply(dependency, source, templateContext) {
const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency);
const {
moduleGraph,
module,
runtime,
concatenationScope
} = templateContext;
const { moduleGraph, module, runtime, concatenationScope } =
templateContext;
const connection = moduleGraph.getConnection(dep);
// Skip rendering depending when dependency is conditional
if (connection && !connection.isTargetActive(runtime)) return;
@ -287,11 +283,8 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
} else {
super.apply(dependency, source, templateContext);
const {
runtimeTemplate,
initFragments,
runtimeRequirements
} = templateContext;
const { runtimeTemplate, initFragments, runtimeRequirements } =
templateContext;
exportExpr = runtimeTemplate.exportFromImport({
moduleGraph,

View File

@ -81,9 +81,9 @@ ImportDependency.Template = class ImportDependencyTemplate extends (
{ runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements }
) {
const dep = /** @type {ImportDependency} */ (dependency);
const block = /** @type {AsyncDependenciesBlock} */ (moduleGraph.getParentBlock(
dep
));
const block = /** @type {AsyncDependenciesBlock} */ (
moduleGraph.getParentBlock(dep)
);
const content = runtimeTemplate.moduleNamespacePromise({
chunkGraph,
block: block,

View File

@ -36,10 +36,8 @@ class ImportParserPlugin {
/** @type {RawChunkGroupOptions} */
const groupOptions = {};
const {
options: importOptions,
errors: commentErrors
} = parser.parseCommentOptions(expr.range);
const { options: importOptions, errors: commentErrors } =
parser.parseCommentOptions(expr.range);
if (commentErrors) {
for (const e of commentErrors) {

View File

@ -46,9 +46,8 @@ module.exports = class RequireEnsureDependenciesBlockParserPlugin {
? dependenciesExpr.items
: [dependenciesExpr];
const successExpressionArg = expr.arguments[1];
const successExpression = getFunctionExpression(
successExpressionArg
);
const successExpression =
getFunctionExpression(successExpressionArg);
if (successExpression) {
parser.walkExpressions(successExpression.expressions);

View File

@ -68,9 +68,9 @@ RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends
{ runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements }
) {
const dep = /** @type {RequireEnsureDependency} */ (dependency);
const depBlock = /** @type {AsyncDependenciesBlock} */ (moduleGraph.getParentBlock(
dep
));
const depBlock = /** @type {AsyncDependenciesBlock} */ (
moduleGraph.getParentBlock(dep)
);
const promise = runtimeTemplate.blockPromise({
chunkGraph,
block: depBlock,

View File

@ -62,12 +62,12 @@ WorkerDependency.Template = class WorkerDependencyTemplate extends (
apply(dependency, source, templateContext) {
const { chunkGraph, moduleGraph, runtimeRequirements } = templateContext;
const dep = /** @type {WorkerDependency} */ (dependency);
const block = /** @type {AsyncDependenciesBlock} */ (moduleGraph.getParentBlock(
dependency
));
const entrypoint = /** @type {Entrypoint} */ (chunkGraph.getBlockChunkGroup(
block
));
const block = /** @type {AsyncDependenciesBlock} */ (
moduleGraph.getParentBlock(dependency)
);
const entrypoint = /** @type {Entrypoint} */ (
chunkGraph.getBlockChunkGroup(block)
);
const chunk = entrypoint.getEntrypointChunk();
runtimeRequirements.add(RuntimeGlobals.publicPath);

View File

@ -186,21 +186,18 @@ class WorkerPlugin {
spread: hasSpreadInOptions,
insertType,
insertLocation
} =
arg2 && arg2.type === "ObjectExpression"
? parseObjectExpression(parser, arg2)
: {
expressions: {},
otherElements: [],
values: {},
spread: false,
insertType: arg2 ? "spread" : "argument",
insertLocation: arg2 ? arg2.range : arg1.range[1]
};
const {
options: importOptions,
errors: commentErrors
} = parser.parseCommentOptions(expr.range);
} = arg2 && arg2.type === "ObjectExpression"
? parseObjectExpression(parser, arg2)
: {
expressions: {},
otherElements: [],
values: {},
spread: false,
insertType: arg2 ? "spread" : "argument",
insertLocation: arg2 ? arg2.range : arg1.range[1]
};
const { options: importOptions, errors: commentErrors } =
parser.parseCommentOptions(expr.range);
if (commentErrors) {
for (const e of commentErrors) {
@ -280,9 +277,9 @@ class WorkerPlugin {
)}|${i}`;
const hash = createHash(compilation.outputOptions.hashFunction);
hash.update(name);
const digest = /** @type {string} */ (hash.digest(
compilation.outputOptions.hashDigest
));
const digest = /** @type {string} */ (
hash.digest(compilation.outputOptions.hashDigest)
);
entryOptions.runtime = digest.slice(
0,
compilation.outputOptions.hashDigestLength
@ -368,7 +365,9 @@ class WorkerPlugin {
(call ? parser.hooks.call : parser.hooks.new)
.for(harmonySpecifierTag)
.tap("WorkerPlugin", expr => {
const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
const settings = /** @type {HarmonySettings} */ (
parser.currentTagData
);
if (
!settings ||
settings.source !== source ||

View File

@ -196,8 +196,9 @@ class LazyCompilationProxyModule extends Module {
const sources = new Map();
const runtimeRequirements = new Set();
runtimeRequirements.add(RuntimeGlobals.module);
const clientDep = /** @type {CommonJsRequireDependency} */ (this
.dependencies[0]);
const clientDep = /** @type {CommonJsRequireDependency} */ (
this.dependencies[0]
);
const clientModule = moduleGraph.getModule(clientDep);
const block = this.blocks[0];
const client = Template.asString([
@ -290,8 +291,9 @@ class LazyCompilationDependencyFactory extends ModuleFactory {
* @returns {void}
*/
create(data, callback) {
const dependency = /** @type {LazyCompilationDependency} */ (data
.dependencies[0]);
const dependency = /** @type {LazyCompilationDependency} */ (
data.dependencies[0]
);
callback(null, {
module: dependency.proxyModule.originalModule
});

View File

@ -63,9 +63,9 @@ class HashedModuleIdsPlugin {
const ident = getFullModuleName(module, context, compiler.root);
const hash = createHash(options.hashFunction);
hash.update(ident || "");
const hashId = /** @type {string} */ (hash.digest(
options.hashDigest
));
const hashId = /** @type {string} */ (
hash.digest(options.hashDigest)
);
let len = options.hashDigestLength;
while (usedIds.has(hashId.substr(0, len))) len++;
const moduleId = hashId.substr(0, len);

View File

@ -98,9 +98,8 @@ class OccurrenceModuleIdsPlugin {
connections
] of moduleGraph.getIncomingConnectionsByOriginModule(module)) {
if (!originModule) continue;
const chunkModules = chunkGraph.getNumberOfModuleChunks(
originModule
);
const chunkModules =
chunkGraph.getNumberOfModuleChunks(originModule);
for (const c of connections) {
if (!c.isTargetActive(undefined)) continue;
if (!c.dependency) continue;

View File

@ -50,9 +50,11 @@ const memoize = require("./util/memoize");
*/
const lazyFunction = factory => {
const fac = memoize(factory);
const f = /** @type {any} */ ((...args) => {
return fac()(...args);
});
const f = /** @type {any} */ (
(...args) => {
return fac()(...args);
}
);
return /** @type {T} */ (f);
};

View File

@ -47,9 +47,8 @@ class ArrayPushCallbackChunkFormatPlugin {
chunk instanceof HotUpdateChunk ? chunk : null;
const globalObject = runtimeTemplate.outputOptions.globalObject;
const source = new ConcatSource();
const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(
chunk
);
const runtimeModules =
chunkGraph.getChunkRuntimeModulesInOrder(chunk);
if (hotUpdateChunk) {
const hotUpdateGlobal =
runtimeTemplate.outputOptions.hotUpdateGlobal;
@ -83,9 +82,8 @@ class ArrayPushCallbackChunkFormatPlugin {
chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)
);
if (runtimeModules.length > 0 || entries.length > 0) {
const strictBailout = hooks.strictRuntimeBailout.call(
renderContext
);
const strictBailout =
hooks.strictRuntimeBailout.call(renderContext);
const runtime = new ConcatSource(
(runtimeTemplate.supportsArrowFunction()
? "__webpack_require__ =>"

View File

@ -51,9 +51,8 @@ class CommonJsChunkFormatPlugin {
source.add(`exports.modules = `);
source.add(modules);
source.add(";\n");
const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(
chunk
);
const runtimeModules =
chunkGraph.getChunkRuntimeModulesInOrder(chunk);
if (runtimeModules.length > 0) {
source.add("exports.runtime =\n");
source.add(

View File

@ -180,7 +180,9 @@ class JavascriptGenerator extends Generator {
* @returns {void}
*/
sourceDependency(module, dependency, initFragments, source, generateContext) {
const constructor = /** @type {new (...args: any[]) => Dependency} */ (dependency.constructor);
const constructor = /** @type {new (...args: any[]) => Dependency} */ (
dependency.constructor
);
const template = generateContext.dependencyTemplates.get(constructor);
if (!template) {
throw new Error(

View File

@ -228,10 +228,11 @@ class JavascriptModulesPlugin {
chunk instanceof HotUpdateChunk ? chunk : null;
let render;
const filenameTemplate = JavascriptModulesPlugin.getChunkFilenameTemplate(
chunk,
outputOptions
);
const filenameTemplate =
JavascriptModulesPlugin.getChunkFilenameTemplate(
chunk,
outputOptions
);
if (hotUpdateChunk) {
render = () =>
this.renderChunk(
@ -394,9 +395,8 @@ class JavascriptModulesPlugin {
compilation.hooks.executeModule.tap(
"JavascriptModulesPlugin",
(options, context) => {
const source = options.codeGenerationResult.sources.get(
"javascript"
);
const source =
options.codeGenerationResult.sources.get("javascript");
if (source === undefined) return;
const { module, moduleObject } = options;
const code = source.source();
@ -468,12 +468,8 @@ class JavascriptModulesPlugin {
* @returns {Source} the newly generated source from rendering
*/
renderModule(module, renderContext, hooks, factory) {
const {
chunk,
chunkGraph,
runtimeTemplate,
codeGenerationResults
} = renderContext;
const { chunk, chunkGraph, runtimeTemplate, codeGenerationResults } =
renderContext;
try {
const moduleSource = codeGenerationResults.getSource(
module,
@ -699,9 +695,8 @@ class JavascriptModulesPlugin {
);
}
const runtimeModules = renderContext.chunkGraph.getChunkRuntimeModulesInOrder(
chunk
);
const runtimeModules =
renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk);
if (runtimeModules.length > 0) {
source.add(
@ -985,9 +980,8 @@ class JavascriptModulesPlugin {
if (chunkGraph.getNumberOfEntryModules(chunk) > 0) {
/** @type {string[]} */
const buf2 = [];
const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(
chunk
);
const runtimeRequirements =
chunkGraph.getTreeRuntimeRequirements(chunk);
buf2.push("// Load entry module and return exports");
let i = chunkGraph.getNumberOfEntryModules(chunk);
for (const [
@ -1044,10 +1038,8 @@ class JavascriptModulesPlugin {
}
i--;
const moduleId = chunkGraph.getModuleId(entryModule);
const entryRuntimeRequirements = chunkGraph.getModuleRuntimeRequirements(
entryModule,
chunk.runtime
);
const entryRuntimeRequirements =
chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime);
let moduleIdExpr = JSON.stringify(moduleId);
if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) {
moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`;

View File

@ -3336,8 +3336,10 @@ class JavascriptParser extends Parser {
if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) {
return false;
}
const items = /** @type {(MethodDefinitionNode | PropertyDefinitionNode)[]} */ (expr
.body.body);
const items =
/** @type {(MethodDefinitionNode | PropertyDefinitionNode)[]} */ (
expr.body.body
);
return items.every(
item =>
(!item.computed ||
@ -3623,10 +3625,8 @@ class JavascriptParser extends Parser {
let callee = object.callee;
let rootMembers = EMPTY_ARRAY;
if (callee.type === "MemberExpression") {
({
object: callee,
members: rootMembers
} = this.extractMemberExpressionChain(callee));
({ object: callee, members: rootMembers } =
this.extractMemberExpressionChain(callee));
}
const rootName = getRootName(callee);
if (!rootName) return undefined;
@ -3729,5 +3729,7 @@ class JavascriptParser extends Parser {
module.exports = JavascriptParser;
module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL;
module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = ALLOWED_MEMBER_TYPES_EXPRESSION;
module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;
module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION =
ALLOWED_MEMBER_TYPES_EXPRESSION;
module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION =
ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;

View File

@ -24,8 +24,10 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** @typedef {import("../util/Hash")} Hash */
/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */
const KEYWORD_REGEX = /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/;
const IDENTIFIER_REGEX = /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
const KEYWORD_REGEX =
/^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/;
const IDENTIFIER_REGEX =
/^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
/**
* Validates the library name by checking for keywords and valid characters

View File

@ -109,10 +109,11 @@ class AggressiveSplittingPlugin {
// Precompute stuff
const nameToModuleMap = new Map();
const moduleToNameMap = new Map();
const makePathsRelative = identifierUtils.makePathsRelative.bindContextCache(
compiler.context,
compiler.root
);
const makePathsRelative =
identifierUtils.makePathsRelative.bindContextCache(
compiler.context,
compiler.root
);
for (const m of compilation.modules) {
const name = makePathsRelative(m.identifier());
nameToModuleMap.set(name, m);

View File

@ -381,10 +381,9 @@ const getFinalBinding = (
}
const directExport = info.exportMap && info.exportMap.get(exportId);
if (directExport) {
const usedName = /** @type {string[]} */ (exportsInfo.getUsedName(
exportName,
runtime
));
const usedName = /** @type {string[]} */ (
exportsInfo.getUsedName(exportName, runtime)
);
if (!usedName) {
return {
info,
@ -443,10 +442,9 @@ const getFinalBinding = (
);
}
if (info.namespaceExportSymbol) {
const usedName = /** @type {string[]} */ (exportsInfo.getUsedName(
exportName,
runtime
));
const usedName = /** @type {string[]} */ (
exportsInfo.getUsedName(exportName, runtime)
);
return {
info,
rawName: info.namespaceObjectName,
@ -462,10 +460,9 @@ const getFinalBinding = (
}
case "external": {
const used = /** @type {string[]} */ (exportsInfo.getUsedName(
exportName,
runtime
));
const used = /** @type {string[]} */ (
exportsInfo.getUsedName(exportName, runtime)
);
if (!used) {
return {
info,
@ -883,8 +880,9 @@ class ConcatenatedModule extends Module {
})
.map(connection => ({
connection,
sourceOrder: /** @type {HarmonyImportDependency} */ (connection.dependency)
.sourceOrder
sourceOrder: /** @type {HarmonyImportDependency} */ (
connection.dependency
).sourceOrder
}));
references.sort(
concatComparators(bySourceOrder, keepOriginalOrder(references))
@ -1162,13 +1160,11 @@ class ConcatenatedModule extends Module {
true
);
if (!binding.ids) continue;
const {
usedNames,
alreadyCheckedScopes
} = getUsedNamesInScopeInfo(
binding.info.module.identifier(),
"name" in binding ? binding.name : ""
);
const { usedNames, alreadyCheckedScopes } =
getUsedNamesInScopeInfo(
binding.info.module.identifier(),
"name" in binding ? binding.name : ""
);
for (const expr of getSuperClassExpressions(reference.from)) {
if (
expr.range[0] <= reference.identifier.range[0] &&
@ -1361,9 +1357,9 @@ class ConcatenatedModule extends Module {
/** @type {Set<string>} */
const unusedExports = new Set();
const rootInfo = /** @type {ConcatenatedModuleInfo} */ (moduleToInfoMap.get(
this.rootModule
));
const rootInfo = /** @type {ConcatenatedModuleInfo} */ (
moduleToInfoMap.get(this.rootModule)
);
const strictHarmonyModule = rootInfo.module.buildMeta.strictHarmonyModule;
const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module);
for (const exportInfo of exportsInfo.orderedExports) {
@ -1531,9 +1527,8 @@ ${defineGetters}`
)}\n`
);
runtimeRequirements.add(RuntimeGlobals.require);
const {
runtimeCondition
} = /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo);
const { runtimeCondition } =
/** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo);
const condition = runtimeTemplate.runtimeConditionExpression({
chunkGraph,
runtimeCondition,

View File

@ -68,9 +68,8 @@ class FlagIncludedChunksPlugin {
for (const chunkA of chunks) {
const chunkAHash = chunkModulesHash.get(chunkA);
const chunkAModulesCount = chunkGraph.getNumberOfChunkModules(
chunkA
);
const chunkAModulesCount =
chunkGraph.getNumberOfChunkModules(chunkA);
if (chunkAModulesCount === 0) continue;
let bestModule = undefined;
for (const module of chunkGraph.getChunkModulesIterable(chunkA)) {
@ -88,9 +87,8 @@ class FlagIncludedChunksPlugin {
// skip if we find ourselves
if (chunkA === chunkB) continue;
const chunkBModulesCount = chunkGraph.getNumberOfChunkModules(
chunkB
);
const chunkBModulesCount =
chunkGraph.getNumberOfChunkModules(chunkB);
// ids for empty chunks are not included
if (chunkBModulesCount === 0) continue;

View File

@ -103,10 +103,9 @@ exports.addUsage = (state, symbol, usage) => {
*/
exports.addVariableUsage = (parser, name, usage) => {
const symbol =
/** @type {TopLevelSymbol} */ (parser.getTagData(
name,
topLevelSymbolTag
)) || exports.tagTopLevelSymbol(parser, name);
/** @type {TopLevelSymbol} */ (
parser.getTagData(name, topLevelSymbolTag)
) || exports.tagTopLevelSymbol(parser, name);
if (symbol) {
exports.addUsage(parser.state, symbol, usage);
}
@ -179,9 +178,9 @@ exports.inferDependencyUsage = state => {
/** @type {Map<Dependency, true | Set<string>>} */
for (const [symbol, callbacks] of usageCallbackMap) {
const usage = /** @type {true | Set<string> | undefined} */ (innerGraph.get(
symbol
));
const usage = /** @type {true | Set<string> | undefined} */ (
innerGraph.get(symbol)
);
for (const callback of callbacks) {
callback(usage === undefined ? false : usage);
}
@ -249,10 +248,9 @@ exports.tagTopLevelSymbol = (parser, name) => {
parser.defineVariable(name);
const existingTag = /** @type {TopLevelSymbol} */ (parser.getTagData(
name,
topLevelSymbolTag
));
const existingTag = /** @type {TopLevelSymbol} */ (
parser.getTagData(name, topLevelSymbolTag)
);
if (existingTag) {
return existingTag;
}

View File

@ -300,7 +300,9 @@ class InnerGraphPlugin {
parser.hooks.expression
.for(topLevelSymbolTag)
.tap("InnerGraphPlugin", () => {
const topLevelSymbol = /** @type {TopLevelSymbol} */ (parser.currentTagData);
const topLevelSymbol = /** @type {TopLevelSymbol} */ (
parser.currentTagData
);
const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol(
parser.state
);

View File

@ -316,9 +316,8 @@ class ModuleConcatenationPlugin {
}
} else {
statsEmptyConfigurations++;
const optimizationBailouts = moduleGraph.getOptimizationBailout(
currentRoot
);
const optimizationBailouts =
moduleGraph.getOptimizationBailout(currentRoot);
for (const warning of currentConfiguration.getWarningsSorted()) {
optimizationBailouts.push(
formatBailoutWarning(warning[0], warning[1])
@ -574,20 +573,18 @@ class ModuleConcatenationPlugin {
const moduleGraph = compilation.moduleGraph;
const incomingConnections = moduleGraph.getIncomingConnectionsByOriginModule(
module
);
const incomingConnections =
moduleGraph.getIncomingConnectionsByOriginModule(module);
const incomingConnectionsFromNonModules =
incomingConnections.get(null) || incomingConnections.get(undefined);
if (incomingConnectionsFromNonModules) {
const activeNonModulesConnections = incomingConnectionsFromNonModules.filter(
connection => {
const activeNonModulesConnections =
incomingConnectionsFromNonModules.filter(connection => {
// We are not interested in inactive connections
// or connections without dependency
return connection.isActive(runtime) || connection.dependency;
}
);
});
if (activeNonModulesConnections.length > 0) {
const problem = requestShortener => {
const importingExplanations = new Set(

View File

@ -194,24 +194,22 @@ class RealContentHashPlugin {
cacheAnalyse.getLazyHashedEtag(source),
Array.from(hashes).join("|")
);
[
asset.referencedHashes,
asset.ownHashes
] = await cacheAnalyse.providePromise(name, etag, () => {
const referencedHashes = new Set();
let ownHashes = new Set();
const inContent = content.match(hashRegExp);
if (inContent) {
for (const hash of inContent) {
if (hashes.has(hash)) {
ownHashes.add(hash);
continue;
[asset.referencedHashes, asset.ownHashes] =
await cacheAnalyse.providePromise(name, etag, () => {
const referencedHashes = new Set();
let ownHashes = new Set();
const inContent = content.match(hashRegExp);
if (inContent) {
for (const hash of inContent) {
if (hashes.has(hash)) {
ownHashes.add(hash);
continue;
}
referencedHashes.add(hash);
}
referencedHashes.add(hash);
}
}
return [referencedHashes, ownHashes];
});
return [referencedHashes, ownHashes];
});
})
);
const getDependencies = hash => {

View File

@ -86,11 +86,12 @@ class SideEffectsFlagPlugin {
if (module.factoryMeta === undefined) {
module.factoryMeta = {};
}
const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects(
resolveData.relativePath,
sideEffects,
cache
);
const hasSideEffects =
SideEffectsFlagPlugin.moduleHasSideEffects(
resolveData.relativePath,
sideEffects,
cache
);
module.factoryMeta.sideEffectFree = !hasSideEffects;
}
}

View File

@ -162,7 +162,10 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
const defaultGetName = /** @type {GetName} */ (() => {});
const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping);
const deterministicGroupingForModules =
/** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (
deterministicGrouping
);
/** @type {WeakMap<Module, string>} */
const getKeyCache = new WeakMap();
@ -173,9 +176,11 @@ const getKeyCache = new WeakMap();
* @returns {string} hashed filename
*/
const hashFilename = (name, outputOptions) => {
const digest = /** @type {string} */ (createHash(outputOptions.hashFunction)
.update(name)
.digest(outputOptions.hashDigest));
const digest = /** @type {string} */ (
createHash(outputOptions.hashFunction)
.update(name)
.digest(outputOptions.hashDigest)
);
return digest.slice(0, 8);
};
@ -939,10 +944,8 @@ module.exports = class SplitChunksPlugin {
const getCombinations = key => getCombinationsFactory()(key);
const getExportsCombinationsFactory = memoize(() => {
const {
chunkSetsInGraph,
singleChunkSets
} = getExportsChunkSetsInGraph();
const { chunkSetsInGraph, singleChunkSets } =
getExportsChunkSetsInGraph();
return createGetCombinations(
chunkSetsInGraph,
singleChunkSets,
@ -1182,13 +1185,8 @@ module.exports = class SplitChunksPlugin {
chunkCombination instanceof Chunk ? 1 : chunkCombination.size;
if (count < cacheGroup.minChunks) continue;
// Select chunks by configuration
const {
chunks: selectedChunks,
key: selectedChunksKey
} = getSelectedChunks(
chunkCombination,
cacheGroup.chunksFilter
);
const { chunks: selectedChunks, key: selectedChunksKey } =
getSelectedChunks(chunkCombination, cacheGroup.chunksFilter);
addModuleToChunksInfoMap(
cacheGroup,

View File

@ -26,14 +26,15 @@ class EnsureChunkRuntimeModule extends RuntimeModule {
`${handlers} = {};`,
"// This file contains only the entry chunk.",
"// The chunk loading function for additional chunks",
`${
RuntimeGlobals.ensureChunk
} = ${runtimeTemplate.basicFunction("chunkId", [
`return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction(
"promises, key",
[`${handlers}[key](chunkId, promises);`, "return promises;"]
)}, []));`
])};`
`${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction(
"chunkId",
[
`return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction(
"promises, key",
[`${handlers}[key](chunkId, promises);`, "return promises;"]
)}, []));`
]
)};`
]);
} else {
// There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure

View File

@ -65,9 +65,8 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule {
} = outputOptions;
const fn = RuntimeGlobals.loadScript;
const { createScript } = LoadScriptRuntimeModule.getCompilationHooks(
compilation
);
const { createScript } =
LoadScriptRuntimeModule.getCompilationHooks(compilation);
const code = Template.asString([
"script = document.createElement('script');",

View File

@ -21,49 +21,50 @@ class OnChunksLoadedRuntimeModule extends RuntimeModule {
const { runtimeTemplate } = compilation;
return Template.asString([
"var deferred = [];",
`${
RuntimeGlobals.onChunksLoaded
} = ${runtimeTemplate.basicFunction("result, chunkIds, fn, priority", [
"if(chunkIds) {",
Template.indent([
"priority = priority || 0;",
"for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];",
"deferred[i] = [chunkIds, fn, priority];",
"return;"
]),
"}",
"var notFulfilled = Infinity;",
"for (var i = 0; i < deferred.length; i++) {",
Template.indent([
runtimeTemplate.destructureArray(
["chunkIds", "fn", "priority"],
"deferred[i]"
),
"var fulfilled = true;",
"for (var j = 0; j < chunkIds.length; j++) {",
`${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction(
"result, chunkIds, fn, priority",
[
"if(chunkIds) {",
Template.indent([
`if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${
RuntimeGlobals.onChunksLoaded
}).every(${runtimeTemplate.returningFunction(
`${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`,
"key"
)})) {`,
Template.indent(["chunkIds.splice(j--, 1);"]),
"} else {",
"priority = priority || 0;",
"for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];",
"deferred[i] = [chunkIds, fn, priority];",
"return;"
]),
"}",
"var notFulfilled = Infinity;",
"for (var i = 0; i < deferred.length; i++) {",
Template.indent([
runtimeTemplate.destructureArray(
["chunkIds", "fn", "priority"],
"deferred[i]"
),
"var fulfilled = true;",
"for (var j = 0; j < chunkIds.length; j++) {",
Template.indent([
"fulfilled = false;",
"if(priority < notFulfilled) notFulfilled = priority;"
`if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${
RuntimeGlobals.onChunksLoaded
}).every(${runtimeTemplate.returningFunction(
`${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`,
"key"
)})) {`,
Template.indent(["chunkIds.splice(j--, 1);"]),
"} else {",
Template.indent([
"fulfilled = false;",
"if(priority < notFulfilled) notFulfilled = priority;"
]),
"}"
]),
"}",
"if(fulfilled) {",
Template.indent(["deferred.splice(i--, 1)", "result = fn();"]),
"}"
]),
"}",
"if(fulfilled) {",
Template.indent(["deferred.splice(i--, 1)", "result = fn();"]),
"}"
]),
"}",
"return result;"
])};`
"return result;"
]
)};`
]);
}
}

View File

@ -201,9 +201,8 @@ class BinaryMiddleware extends SerializerMiddleware {
if (!SerializerMiddleware.isLazy(thing))
throw new Error("Unexpected function " + thing);
/** @type {SerializedType | (() => SerializedType)} */
let serializedData = SerializerMiddleware.getLazySerializedValue(
thing
);
let serializedData =
SerializerMiddleware.getLazySerializedValue(thing);
if (serializedData === undefined) {
if (SerializerMiddleware.isLazy(thing, this)) {
const data = this._serialize(thing(), context);

View File

@ -135,7 +135,9 @@ const serialize = async (middleware, data, name, writeFile) => {
const backgroundJobs = [];
const resolvedData = (
await Promise.all(
/** @type {Promise<Buffer[] | Buffer | SerializeResult>[]} */ (processedData)
/** @type {Promise<Buffer[] | Buffer | SerializeResult>[]} */ (
processedData
)
)
).map(item => {
if (Array.isArray(item) || Buffer.isBuffer(item)) return item;

View File

@ -450,9 +450,8 @@ class ObjectMiddleware extends SerializerMiddleware {
);
}
const { request, name, serializer } = ObjectMiddleware.getSerializerFor(
item
);
const { request, name, serializer } =
ObjectMiddleware.getSerializerFor(item);
const key = `${request}/${name}`;
const lastIndex = objectTypeLookup.get(key);
@ -500,9 +499,8 @@ class ObjectMiddleware extends SerializerMiddleware {
if (!SerializerMiddleware.isLazy(item))
throw new Error("Unexpected function " + item);
/** @type {SerializedType} */
const serializedData = SerializerMiddleware.getLazySerializedValue(
item
);
const serializedData =
SerializerMiddleware.getLazySerializedValue(item);
if (serializedData !== undefined) {
if (typeof serializedData === "function") {
result.push(serializedData);
@ -539,7 +537,13 @@ class ObjectMiddleware extends SerializerMiddleware {
// This happens because the optimized code v8 generates
// is optimized for our "ctx.write" method so it will reference
// it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write
data = result = referenceable = bufferDedupeMap = objectTypeLookup = ctx = undefined;
data =
result =
referenceable =
bufferDedupeMap =
objectTypeLookup =
ctx =
undefined;
}
}

View File

@ -1078,9 +1078,8 @@ const SIMPLE_EXTRACTORS = {
const { compilation, type } = context;
const built = compilation.builtModules.has(module);
const codeGenerated = compilation.codeGeneratedModules.has(module);
const buildTimeExecuted = compilation.buildTimeExecutedModules.has(
module
);
const buildTimeExecuted =
compilation.buildTimeExecutedModules.has(module);
/** @type {{[x: string]: number}} */
const sizes = {};
for (const sourceType of module.getSourceTypes()) {

View File

@ -818,9 +818,8 @@ const SIMPLE_ITEMS_JOINER = {
"asset.chunkNames": itemsJoinCommaBracketsWithName("name"),
"asset.auxiliaryChunkNames": itemsJoinCommaBracketsWithName("auxiliary name"),
"asset.chunkIdHints": itemsJoinCommaBracketsWithName("id hint"),
"asset.auxiliaryChunkIdHints": itemsJoinCommaBracketsWithName(
"auxiliary id hint"
),
"asset.auxiliaryChunkIdHints":
itemsJoinCommaBracketsWithName("auxiliary id hint"),
"module.chunks": itemsJoinOneLine,
"module.issuerPath": items =>
items
@ -912,11 +911,13 @@ const joinExplicitNewLine = (items, indenter) => {
.trim();
};
const joinError = error => (items, { red, yellow }) =>
`${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine(
items,
""
)}`;
const joinError =
error =>
(items, { red, yellow }) =>
`${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine(
items,
""
)}`;
/** @type {Record<string, (items: ({ element: string, content: string })[], context: StatsPrinterContext) => string>} */
const SIMPLE_ELEMENT_JOINERS = {
@ -1130,7 +1131,8 @@ const AVAILABLE_FORMATS = {
format: red
},
{
regExp: /\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi,
regExp:
/\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi,
format: red
}
];

View File

@ -71,7 +71,8 @@ class StatsFactory {
getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"]))
});
const hooks = this.hooks;
this._caches = /** @type {Record<keyof typeof hooks, Map<string, SyncBailHook<[any[], StatsFactoryContext]>[]>>} */ ({});
this._caches =
/** @type {Record<keyof typeof hooks, Map<string, SyncBailHook<[any[], StatsFactoryContext]>[]>>} */ ({});
for (const key of Object.keys(hooks)) {
this._caches[key] = new Map();
}

View File

@ -87,9 +87,9 @@ class StatsPrinter {
* @returns {T[]} hooks
*/
_getAllLevelHooks(hookMap, type) {
let cache = /** @type {Map<string, T[]>} */ (this._levelHookCache.get(
hookMap
));
let cache = /** @type {Map<string, T[]>} */ (
this._levelHookCache.get(hookMap)
);
if (cache === undefined) {
cache = new Map();
this._levelHookCache.set(hookMap, cache);

View File

@ -164,9 +164,9 @@ class LazyBucketSortedSet {
}
};
} else {
const oldEntry = /** @type {LazyBucketSortedSet<T, any>} */ (this._map.get(
key
));
const oldEntry = /** @type {LazyBucketSortedSet<T, any>} */ (
this._map.get(key)
);
const finishUpdate = oldEntry.startUpdate(item);
return remove => {
if (remove) {

View File

@ -539,7 +539,9 @@ const resolveByProperty = (obj, byProperty, ...values) => {
}
const { [byProperty]: _byValue, ..._remaining } = /** @type {object} */ (obj);
const remaining = /** @type {T} */ (_remaining);
const byValue = /** @type {Record<string, T> | function(...any[]): T} */ (_byValue);
const byValue = /** @type {Record<string, T> | function(...any[]): T} */ (
_byValue
);
if (typeof byValue === "object") {
const key = values[0];
if (key in byValue) {

View File

@ -68,9 +68,8 @@ const compareModulesById = (chunkGraph, a, b) => {
return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b));
};
/** @type {ParameterizedComparator<ChunkGraph, Module>} */
exports.compareModulesById = createCachedParameterizedComparator(
compareModulesById
);
exports.compareModulesById =
createCachedParameterizedComparator(compareModulesById);
/**
* @param {number} a number
@ -138,9 +137,10 @@ const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => {
return compareIds(a.identifier(), b.identifier());
};
/** @type {ParameterizedComparator<ModuleGraph, Module>} */
exports.compareModulesByPostOrderIndexOrIdentifier = createCachedParameterizedComparator(
compareModulesByPostOrderIndexOrIdentifier
);
exports.compareModulesByPostOrderIndexOrIdentifier =
createCachedParameterizedComparator(
compareModulesByPostOrderIndexOrIdentifier
);
/**
* @param {ModuleGraph} moduleGraph the module graph
@ -157,9 +157,10 @@ const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => {
return compareIds(a.identifier(), b.identifier());
};
/** @type {ParameterizedComparator<ModuleGraph, Module>} */
exports.compareModulesByPreOrderIndexOrIdentifier = createCachedParameterizedComparator(
compareModulesByPreOrderIndexOrIdentifier
);
exports.compareModulesByPreOrderIndexOrIdentifier =
createCachedParameterizedComparator(
compareModulesByPreOrderIndexOrIdentifier
);
/**
* @param {ChunkGraph} chunkGraph the chunk graph
@ -284,10 +285,9 @@ const concatComparators = (c1, c2, ...cRest) => {
const [c3, ...cRest2] = cRest;
return concatComparators(c1, concatComparators(c2, c3, ...cRest2));
}
const cacheEntry = /** @type {Comparator<T>} */ (concatComparatorsCache.get(
c1,
c2
));
const cacheEntry = /** @type {Comparator<T>} */ (
concatComparatorsCache.get(c1, c2)
);
if (cacheEntry !== undefined) return cacheEntry;
/**
* @param {T} a first value

View File

@ -244,7 +244,8 @@ const _absolutify = (context, request) => {
const absolutify = makeCacheable(_absolutify);
exports.absolutify = absolutify;
const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/;
const PATH_QUERY_FRAGMENT_REGEXP =
/^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/;
/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */

View File

@ -21,8 +21,7 @@ const DID_YOU_MEAN = {
"output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)",
ecmaversion:
"output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)",
ecma:
"output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)",
ecma: "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)",
path: "output.path",
pathinfo: "output.pathinfo",
pathInfo: "output.pathinfo",
@ -109,7 +108,10 @@ const validateSchema = (schema, options, validationConfiguration) => {
}
if (error.keyword === "additionalProperties") {
const params = /** @type {import("ajv").AdditionalPropertiesParams} */ (error.params);
const params =
/** @type {import("ajv").AdditionalPropertiesParams} */ (
error.params
);
if (
Object.prototype.hasOwnProperty.call(
DID_YOU_MEAN,

View File

@ -91,9 +91,8 @@ class AsyncWebAssemblyModulesPlugin {
compiler.hooks.compilation.tap(
"AsyncWebAssemblyModulesPlugin",
(compilation, { normalModuleFactory }) => {
const hooks = AsyncWebAssemblyModulesPlugin.getCompilationHooks(
compilation
);
const hooks =
AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation);
compilation.dependencyFactories.set(
WebAssemblyImportDependency,
normalModuleFactory
@ -109,7 +108,8 @@ class AsyncWebAssemblyModulesPlugin {
normalModuleFactory.hooks.createGenerator
.for("webassembly/async")
.tap("AsyncWebAssemblyModulesPlugin", () => {
const AsyncWebAssemblyJavascriptGenerator = getAsyncWebAssemblyJavascriptGenerator();
const AsyncWebAssemblyJavascriptGenerator =
getAsyncWebAssemblyJavascriptGenerator();
const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator();
return Generator.byType({

View File

@ -40,10 +40,11 @@ class WasmFinalizeExportsPlugin {
connection.originModule.type.startsWith("webassembly") ===
false
) {
const referencedExports = compilation.getDependencyReferencedExports(
connection.dependency,
undefined
);
const referencedExports =
compilation.getDependencyReferencedExports(
connection.dependency,
undefined
);
for (const info of referencedExports) {
const names = Array.isArray(info) ? info : info.name;

View File

@ -240,31 +240,27 @@ const rewriteImportedGlobals = state => bin => {
* @param {RuntimeSpec} state.runtime runtime
* @returns {ArrayBufferTransform} transform
*/
const rewriteExportNames = ({
ast,
moduleGraph,
module,
externalExports,
runtime
}) => bin => {
return editWithAST(ast, bin, {
ModuleExport(path) {
const isExternal = externalExports.has(path.node.name);
if (isExternal) {
path.remove();
return;
const rewriteExportNames =
({ ast, moduleGraph, module, externalExports, runtime }) =>
bin => {
return editWithAST(ast, bin, {
ModuleExport(path) {
const isExternal = externalExports.has(path.node.name);
if (isExternal) {
path.remove();
return;
}
const usedName = moduleGraph
.getExportsInfo(module)
.getUsedName(path.node.name, runtime);
if (!usedName) {
path.remove();
return;
}
path.node.name = usedName;
}
const usedName = moduleGraph
.getExportsInfo(module)
.getUsedName(path.node.name, runtime);
if (!usedName) {
path.remove();
return;
}
path.node.name = usedName;
}
});
};
});
};
/**
* Mangle import names and modules
@ -273,20 +269,22 @@ const rewriteExportNames = ({
* @param {Map<string, UsedWasmDependency>} state.usedDependencyMap mappings to mangle names
* @returns {ArrayBufferTransform} transform
*/
const rewriteImports = ({ ast, usedDependencyMap }) => bin => {
return editWithAST(ast, bin, {
ModuleImport(path) {
const result = usedDependencyMap.get(
path.node.module + ":" + path.node.name
);
const rewriteImports =
({ ast, usedDependencyMap }) =>
bin => {
return editWithAST(ast, bin, {
ModuleImport(path) {
const result = usedDependencyMap.get(
path.node.module + ":" + path.node.name
);
if (result !== undefined) {
path.node.module = result.module;
path.node.name = result.name;
if (result !== undefined) {
path.node.module = result.module;
path.node.name = result.name;
}
}
}
});
};
});
};
/**
* Add an init function.
@ -303,63 +301,69 @@ const rewriteImports = ({ ast, usedDependencyMap }) => bin => {
* @param {t.Index} state.nextTypeIndex index of the next type
* @returns {ArrayBufferTransform} transform
*/
const addInitFunction = ({
ast,
initFuncId,
startAtFuncOffset,
importedGlobals,
additionalInitCode,
nextFuncIndex,
nextTypeIndex
}) => bin => {
const funcParams = importedGlobals.map(importedGlobal => {
// used for debugging
const id = t.identifier(`${importedGlobal.module}.${importedGlobal.name}`);
const addInitFunction =
({
ast,
initFuncId,
startAtFuncOffset,
importedGlobals,
additionalInitCode,
nextFuncIndex,
nextTypeIndex
}) =>
bin => {
const funcParams = importedGlobals.map(importedGlobal => {
// used for debugging
const id = t.identifier(
`${importedGlobal.module}.${importedGlobal.name}`
);
return t.funcParam(importedGlobal.descr.valtype, id);
});
return t.funcParam(importedGlobal.descr.valtype, id);
});
const funcBody = [];
importedGlobals.forEach((importedGlobal, index) => {
const args = [t.indexLiteral(index)];
const body = [
t.instruction("get_local", args),
t.instruction("set_global", args)
];
const funcBody = [];
importedGlobals.forEach((importedGlobal, index) => {
const args = [t.indexLiteral(index)];
const body = [
t.instruction("get_local", args),
t.instruction("set_global", args)
];
funcBody.push(...body);
});
funcBody.push(...body);
});
if (typeof startAtFuncOffset === "number") {
funcBody.push(t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset)));
}
if (typeof startAtFuncOffset === "number") {
funcBody.push(
t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset))
);
}
for (const instr of additionalInitCode) {
funcBody.push(instr);
}
for (const instr of additionalInitCode) {
funcBody.push(instr);
}
funcBody.push(t.instruction("end"));
funcBody.push(t.instruction("end"));
const funcResults = [];
const funcResults = [];
// Code section
const funcSignature = t.signature(funcParams, funcResults);
const func = t.func(initFuncId, funcSignature, funcBody);
// Code section
const funcSignature = t.signature(funcParams, funcResults);
const func = t.func(initFuncId, funcSignature, funcBody);
// Type section
const functype = t.typeInstruction(undefined, funcSignature);
// Type section
const functype = t.typeInstruction(undefined, funcSignature);
// Func section
const funcindex = t.indexInFuncSection(nextTypeIndex);
// Func section
const funcindex = t.indexInFuncSection(nextTypeIndex);
// Export section
const moduleExport = t.moduleExport(
initFuncId.value,
t.moduleExportDescr("Func", nextFuncIndex)
);
// Export section
const moduleExport = t.moduleExport(
initFuncId.value,
t.moduleExportDescr("Func", nextFuncIndex)
);
return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]);
};
return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]);
};
/**
* Extract mangle mappings from module
@ -447,7 +451,9 @@ class WebAssemblyGenerator extends Generator {
module.dependencies
.filter(d => d instanceof WebAssemblyExportImportedDependency)
.map(d => {
const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ (d);
const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ (
d
);
return wasmDep.exportName;
})
);

View File

@ -61,7 +61,8 @@ class WebAssemblyModulesPlugin {
normalModuleFactory.hooks.createGenerator
.for("webassembly/sync")
.tap("WebAssemblyModulesPlugin", () => {
const WebAssemblyJavascriptGenerator = getWebAssemblyJavascriptGenerator();
const WebAssemblyJavascriptGenerator =
getWebAssemblyJavascriptGenerator();
const WebAssemblyGenerator = getWebAssemblyGenerator();
return Generator.byType({

View File

@ -89,7 +89,8 @@ class WebAssemblyParser extends Parser {
// extract imports and exports
const exports = [];
let jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = undefined);
let jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports =
undefined);
const importedGlobals = [];
t.traverse(module, {
@ -102,13 +103,13 @@ class WebAssemblyParser extends Parser {
/** @type {t.FuncSignature} */
const funcSignature = moduleContext.getFunction(funcIdx);
const incompatibleType = getJsIncompatibleTypeOfFuncSignature(
funcSignature
);
const incompatibleType =
getJsIncompatibleTypeOfFuncSignature(funcSignature);
if (incompatibleType) {
if (jsIncompatibleExports === undefined) {
jsIncompatibleExports = state.module.buildMeta.jsIncompatibleExports = {};
jsIncompatibleExports =
state.module.buildMeta.jsIncompatibleExports = {};
}
jsIncompatibleExports[node.name] = incompatibleType;
}

View File

@ -66,10 +66,8 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
scriptType
}
} = compilation;
const {
linkPreload,
linkPrefetch
} = JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation);
const { linkPreload, linkPrefetch } =
JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation);
const fn = RuntimeGlobals.ensureChunkHandlers;
const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
const withLoading = this._runtimeRequirements.has(

View File

@ -48,7 +48,8 @@ function checkSymlinkExistsAsync() {
}
async function ensureYarnInstalledAsync() {
const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/;
const semverPattern =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/;
let hasYarn = false;
try {
const stdout = await execGetOutput("yarn", ["-v"], "Check yarn version");

View File

@ -171,51 +171,15 @@ describe("BenchmarkTestCases", function () {
if (n <= 30) {
// 1 2 ...
const data = [
6.314,
2.92,
2.353,
2.132,
2.015,
1.943,
1.895,
1.86,
1.833,
1.812,
1.796,
1.782,
1.771,
1.761,
1.753,
1.746,
1.74,
1.734,
1.729,
1.725,
1.721,
1.717,
1.714,
1.711,
1.708,
1.706,
1.703,
1.701,
1.699,
1.697
6.314, 2.92, 2.353, 2.132, 2.015, 1.943, 1.895, 1.86, 1.833, 1.812,
1.796, 1.782, 1.771, 1.761, 1.753, 1.746, 1.74, 1.734, 1.729, 1.725,
1.721, 1.717, 1.714, 1.711, 1.708, 1.706, 1.703, 1.701, 1.699, 1.697
];
return data[n - 1];
} else if (n <= 120) {
// 30 40 50 60 70 80 90 100 110 120
const data = [
1.697,
1.684,
1.676,
1.671,
1.667,
1.664,
1.662,
1.66,
1.659,
1.658
1.697, 1.684, 1.676, 1.671, 1.667, 1.664, 1.662, 1.66, 1.659, 1.658
];
var a = data[Math.floor(n / 10) - 3];
var b = data[Math.ceil(n / 10) - 3];

View File

@ -383,9 +383,10 @@ const describeCases = config => {
moduleScope.window = globalContext;
moduleScope.self = globalContext;
moduleScope.URL = URL;
moduleScope.Worker = require("./helpers/createFakeWorker")(
{ outputDirectory }
);
moduleScope.Worker =
require("./helpers/createFakeWorker")({
outputDirectory
});
runInNewContext = true;
}
if (testConfig.moduleScope) {

View File

@ -1,10 +1,8 @@
const path = require("path");
const jestDiff = require("jest-diff").default;
const stripAnsi = require("strip-ansi");
const {
applyWebpackOptionsDefaults,
getNormalizedWebpackOptions
} = require("..").config;
const { applyWebpackOptionsDefaults, getNormalizedWebpackOptions } =
require("..").config;
/**
* Escapes regular expression metacharacters

View File

@ -4,7 +4,10 @@ module.exports = {
compiler => {
compiler.hooks.done.tap("Test", ({ compilation }) => {
for (const c of compilation.chunks) {
const chunk = /** @type {{ files: string[] } & import("../../../../").Chunk} */ (c);
const chunk =
/** @type {{ files: string[] } & import("../../../../").Chunk} */ (
c
);
expect(chunk.files.length).toBe(chunk.files.size);
expect(chunk.files[0]).toBe(Array.from(chunk.files)[0]);
expect(chunk.files.join(",")).toBe(Array.from(chunk.files).join(","));

View File

@ -110,7 +110,8 @@ class HtmlInlinePlugin {
const asset = compilation.getAsset(name);
const content = asset.source.source();
const matches = [];
const regExp = /<script\s+src\s*=\s*"([^"]+)"(?:\s+[^"=\s]+(?:\s*=\s*(?:"[^"]*"|[^\s]+))?)*\s*><\/script>/g;
const regExp =
/<script\s+src\s*=\s*"([^"]+)"(?:\s+[^"=\s]+(?:\s*=\s*(?:"[^"]*"|[^\s]+))?)*\s*><\/script>/g;
let match = regExp.exec(content);
while (match) {
let url = match[1];

View File

@ -1,5 +1,5 @@
var HotModuleReplacementPlugin = require("../../../../")
.HotModuleReplacementPlugin;
var HotModuleReplacementPlugin =
require("../../../../").HotModuleReplacementPlugin;
/** @type {import("../../../../").Configuration} */
module.exports = {
entry: {

View File

@ -1,5 +1,5 @@
var HotModuleReplacementPlugin = require("../../../../")
.HotModuleReplacementPlugin;
var HotModuleReplacementPlugin =
require("../../../../").HotModuleReplacementPlugin;
/** @type {import("../../../../").Configuration} */
module.exports = {
entry: {

View File

@ -44,14 +44,16 @@ module.exports = [
},
plugins: [
new webpack.DefinePlugin({
VALUE: webpack.DefinePlugin.runtimeValue(() => read("123.txt"), [
join(__dirname, "./123.txt")
])
VALUE: webpack.DefinePlugin.runtimeValue(
() => read("123.txt"),
[join(__dirname, "./123.txt")]
)
}),
new webpack.DefinePlugin({
VALUE: webpack.DefinePlugin.runtimeValue(() => read("321.txt"), [
join(__dirname, "./321.txt")
])
VALUE: webpack.DefinePlugin.runtimeValue(
() => read("321.txt"),
[join(__dirname, "./321.txt")]
)
})
]
}

View File

@ -15,7 +15,8 @@ const files = ["lib/util/semver.js"];
const content = fs.readFileSync(filePath, "utf-8");
const exports = require(`../${file}`);
const regexp = /\n\/\/#region runtime code: (.+)\n[\s\S]+?\/\/#endregion\n/g;
const regexp =
/\n\/\/#region runtime code: (.+)\n[\s\S]+?\/\/#endregion\n/g;
const replaces = new Map();

51
types.d.ts vendored
View File

@ -5011,9 +5011,7 @@ declare class JavascriptParser extends Parser {
parseCommentOptions(
range?: any
): { options: null; errors: null } | { options: object; errors: any[] };
extractMemberExpressionChain(
expression: MemberExpression
): {
extractMemberExpressionChain(expression: MemberExpression): {
members: string[];
object:
| UnaryExpression
@ -5045,16 +5043,15 @@ declare class JavascriptParser extends Parser {
| ChainExpression
| Super;
};
getFreeInfoFromVariable(
varName: string
): { name: string; info: string | VariableInfo };
getFreeInfoFromVariable(varName: string): {
name: string;
info: string | VariableInfo;
};
getMemberExpressionInfo(
expression: MemberExpression,
allowedTypes: number
): undefined | CallExpressionInfo | ExpressionExpressionInfo;
getNameForExpression(
expression: MemberExpression
): {
getNameForExpression(expression: MemberExpression): {
name: string;
rootInfo: ExportedVariableInfo;
getMembers: () => string[];
@ -5805,13 +5802,11 @@ type LoaderContext<OptionsType> = NormalModuleLoaderContext<OptionsType> &
LoaderRunnerLoaderContext<OptionsType> &
LoaderPluginLoaderContext &
HotModuleReplacementPluginLoaderContext;
type LoaderDefinition<
OptionsType = {},
ContextAdditions = {}
> = LoaderDefinitionFunction<OptionsType, ContextAdditions> & {
raw?: false;
pitch?: PitchLoaderDefinitionFunction<OptionsType, ContextAdditions>;
};
type LoaderDefinition<OptionsType = {}, ContextAdditions = {}> =
LoaderDefinitionFunction<OptionsType, ContextAdditions> & {
raw?: false;
pitch?: PitchLoaderDefinitionFunction<OptionsType, ContextAdditions>;
};
declare interface LoaderDefinitionFunction<
OptionsType = {},
ContextAdditions = {}
@ -7197,9 +7192,7 @@ declare interface NormalModuleLoaderContext<OptionsType> {
arg2?: ResolveRequest
) => void
): any;
getResolve(
options?: ResolveOptionsWithDependencyType
): {
getResolve(options?: ResolveOptionsWithDependencyType): {
(
context: string,
request: string,
@ -8671,13 +8664,11 @@ declare interface RawChunkGroupOptions {
preloadOrder?: number;
prefetchOrder?: number;
}
type RawLoaderDefinition<
OptionsType = {},
ContextAdditions = {}
> = RawLoaderDefinitionFunction<OptionsType, ContextAdditions> & {
raw: true;
pitch?: PitchLoaderDefinitionFunction<OptionsType, ContextAdditions>;
};
type RawLoaderDefinition<OptionsType = {}, ContextAdditions = {}> =
RawLoaderDefinitionFunction<OptionsType, ContextAdditions> & {
raw: true;
pitch?: PitchLoaderDefinitionFunction<OptionsType, ContextAdditions>;
};
declare interface RawLoaderDefinitionFunction<
OptionsType = {},
ContextAdditions = {}
@ -9730,9 +9721,7 @@ declare interface RuleSetRule {
*/
options?: string | { [index: string]: any };
}
| ((
data: object
) =>
| ((data: object) =>
| string
| {
/**
@ -11923,9 +11912,7 @@ declare interface WithOptions {
declare interface WriteOnlySet<T> {
add: (T?: any) => void;
}
type __TypeWebpackOptions = (
data: object
) =>
type __TypeWebpackOptions = (data: object) =>
| string
| {
/**