code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const LazySet = require("../util/LazySet");
const makeSerializable = require("../util/makeSerializable");

/** @typedef {import("enhanced-resolve").Resolver} Resolver */
/** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../FileSystemInfo")} FileSystemInfo */
/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */

class CacheEntry {
	constructor(result, snapshot) {
		this.result = result;
		this.snapshot = snapshot;
	}

	serialize({ write }) {
		write(this.result);
		write(this.snapshot);
	}

	deserialize({ read }) {
		this.result = read();
		this.snapshot = read();
	}
}

makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin");

/**
 * @template T
 * @param {Set<T> | LazySet<T>} set set to add items to
 * @param {Set<T> | LazySet<T>} otherSet set to add items from
 * @returns {void}
 */
const addAllToSet = (set, otherSet) => {
	if (set instanceof LazySet) {
		set.addAll(otherSet);
	} else {
		for (const item of otherSet) {
			set.add(item);
		}
	}
};

/**
 * @param {object} object an object
 * @param {boolean} excludeContext if true, context is not included in string
 * @returns {string} stringified version
 */
const objectToString = (object, excludeContext) => {
	let str = "";
	for (const key in object) {
		if (excludeContext && key === "context") continue;
		const value = object[key];
		if (typeof value === "object" && value !== null) {
			str += `|${key}=[${objectToString(value, false)}|]`;
		} else {
			str += `|${key}=|${value}`;
		}
	}
	return str;
};

class ResolverCachePlugin {
	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const cache = compiler.getCache("ResolverCachePlugin");
		/** @type {FileSystemInfo} */
		let fileSystemInfo;
		let snapshotOptions;
		let realResolves = 0;
		let cachedResolves = 0;
		let cacheInvalidResolves = 0;
		let concurrentResolves = 0;
		compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => {
			snapshotOptions = compilation.options.snapshot.resolve;
			fileSystemInfo = compilation.fileSystemInfo;
			compilation.hooks.finishModules.tap("ResolverCachePlugin", () => {
				if (realResolves + cachedResolves > 0) {
					const logger = compilation.getLogger("webpack.ResolverCachePlugin");
					logger.log(
						`${Math.round(
							(100 * realResolves) / (realResolves + cachedResolves)
						)}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)`
					);
					realResolves = 0;
					cachedResolves = 0;
					cacheInvalidResolves = 0;
					concurrentResolves = 0;
				}
			});
		});
		/**
		 * @param {ItemCacheFacade} itemCache cache
		 * @param {Resolver} resolver the resolver
		 * @param {object} resolveContext context for resolving meta info
		 * @param {object} request the request info object
		 * @param {function((Error | null)=, object=): void} callback callback function
		 * @returns {void}
		 */
		const doRealResolve = (
			itemCache,
			resolver,
			resolveContext,
			request,
			callback
		) => {
			realResolves++;
			const newRequest = {
				_ResolverCachePluginCacheMiss: true,
				...request
			};
			const newResolveContext = {
				...resolveContext,
				stack: new Set(),
				/** @type {LazySet<string>} */
				missingDependencies: new LazySet(),
				/** @type {LazySet<string>} */
				fileDependencies: new LazySet(),
				/** @type {LazySet<string>} */
				contextDependencies: new LazySet()
			};
			let yieldResult;
			let withYield = false;
			if (typeof newResolveContext.yield === "function") {
				yieldResult = [];
				withYield = true;
				newResolveContext.yield = obj => yieldResult.push(obj);
			}
			const propagate = key => {
				if (resolveContext[key]) {
					addAllToSet(resolveContext[key], newResolveContext[key]);
				}
			};
			const resolveTime = Date.now();
			resolver.doResolve(
				resolver.hooks.resolve,
				newRequest,
				"Cache miss",
				newResolveContext,
				(err, result) => {
					propagate("fileDependencies");
					propagate("contextDependencies");
					propagate("missingDependencies");
					if (err) return callback(err);
					const fileDependencies = newResolveContext.fileDependencies;
					const contextDependencies = newResolveContext.contextDependencies;
					const missingDependencies = newResolveContext.missingDependencies;
					fileSystemInfo.createSnapshot(
						resolveTime,
						fileDependencies,
						contextDependencies,
						missingDependencies,
						snapshotOptions,
						(err, snapshot) => {
							if (err) return callback(err);
							const resolveResult = withYield ? yieldResult : result;
							// since we intercept resolve hook
							// we still can get result in callback
							if (withYield && result) yieldResult.push(result);
							if (!snapshot) {
								if (resolveResult) return callback(null, resolveResult);
								return callback();
							}
							itemCache.store(
								new CacheEntry(resolveResult, snapshot),
								storeErr => {
									if (storeErr) return callback(storeErr);
									if (resolveResult) return callback(null, resolveResult);
									callback();
								}
							);
						}
					);
				}
			);
		};
		compiler.resolverFactory.hooks.resolver.intercept({
			factory(type, hook) {
				/** @type {Map<string, (function(Error=, object=): void)[]>} */
				const activeRequests = new Map();
				/** @type {Map<string, [function(Error=, object=): void, function(Error=, object=): void][]>} */
				const activeRequestsWithYield = new Map();
				hook.tap(
					"ResolverCachePlugin",
					/**
					 * @param {Resolver} resolver the resolver
					 * @param {object} options resolve options
					 * @param {object} userOptions resolve options passed by the user
					 * @returns {void}
					 */
					(resolver, options, userOptions) => {
						if (options.cache !== true) return;
						const optionsIdent = objectToString(userOptions, false);
						const cacheWithContext =
							options.cacheWithContext !== undefined
								? options.cacheWithContext
								: false;
						resolver.hooks.resolve.tapAsync(
							{
								name: "ResolverCachePlugin",
								stage: -100
							},
							(request, resolveContext, callback) => {
								if (
									/** @type {TODO} */ (request)._ResolverCachePluginCacheMiss ||
									!fileSystemInfo
								) {
									return callback();
								}
								const withYield = typeof resolveContext.yield === "function";
								const identifier = `${type}${
									withYield ? "|yield" : "|default"
								}${optionsIdent}${objectToString(request, !cacheWithContext)}`;

								if (withYield) {
									const activeRequest = activeRequestsWithYield.get(identifier);
									if (activeRequest) {
										activeRequest[0].push(callback);
										activeRequest[1].push(
											/** @type {TODO} */ (resolveContext.yield)
										);
										return;
									}
								} else {
									const activeRequest = activeRequests.get(identifier);
									if (activeRequest) {
										activeRequest.push(callback);
										return;
									}
								}
								const itemCache = cache.getItemCache(identifier, null);
								let callbacks, yields;
								const done = withYield
									? (err, result) => {
											if (callbacks === undefined) {
												if (err) {
													callback(err);
												} else {
													if (result)
														for (const r of result) resolveContext.yield(r);
													callback(null, null);
												}
												yields = undefined;
												callbacks = false;
											} else {
												if (err) {
													for (const cb of callbacks) cb(err);
												} else {
													for (let i = 0; i < callbacks.length; i++) {
														const cb = callbacks[i];
														const yield_ = yields[i];
														if (result) for (const r of result) yield_(r);
														cb(null, null);
													}
												}
												activeRequestsWithYield.delete(identifier);
												yields = undefined;
												callbacks = false;
											}
										}
									: (err, result) => {
											if (callbacks === undefined) {
												callback(err, result);
												callbacks = false;
											} else {
												for (const callback of callbacks) {
													callback(err, result);
												}
												activeRequests.delete(identifier);
												callbacks = false;
											}
										};
								/**
								 * @param {Error=} err error if any
								 * @param {CacheEntry=} cacheEntry cache entry
								 * @returns {void}
								 */
								const processCacheResult = (err, cacheEntry) => {
									if (err) return done(err);

									if (cacheEntry) {
										const { snapshot, result } = cacheEntry;
										fileSystemInfo.checkSnapshotValid(
											snapshot,
											(err, valid) => {
												if (err || !valid) {
													cacheInvalidResolves++;
													return doRealResolve(
														itemCache,
														resolver,
														resolveContext,
														request,
														done
													);
												}
												cachedResolves++;
												if (resolveContext.missingDependencies) {
													addAllToSet(
														/** @type {LazySet<string>} */
														(resolveContext.missingDependencies),
														snapshot.getMissingIterable()
													);
												}
												if (resolveContext.fileDependencies) {
													addAllToSet(
														/** @type {LazySet<string>} */
														(resolveContext.fileDependencies),
														snapshot.getFileIterable()
													);
												}
												if (resolveContext.contextDependencies) {
													addAllToSet(
														/** @type {LazySet<string>} */
														(resolveContext.contextDependencies),
														snapshot.getContextIterable()
													);
												}
												done(null, result);
											}
										);
									} else {
										doRealResolve(
											itemCache,
											resolver,
											resolveContext,
											request,
											done
										);
									}
								};
								itemCache.get(processCacheResult);
								if (withYield && callbacks === undefined) {
									callbacks = [callback];
									yields = [resolveContext.yield];
									activeRequestsWithYield.set(
										identifier,
										/** @type {[any, any]} */ ([callbacks, yields])
									);
								} else if (callbacks === undefined) {
									callbacks = [callback];
									activeRequests.set(identifier, callbacks);
								}
							}
						);
					}
				);
				return hook;
			}
		});
	}
}

module.exports = ResolverCachePlugin;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const createHash = require("../util/createHash");

/** @typedef {import("../util/Hash")} Hash */
/** @typedef {typeof import("../util/Hash")} HashConstructor */

/**
 * @typedef {object} HashableObject
 * @property {function(Hash): void} updateHash
 */

class LazyHashedEtag {
	/**
	 * @param {HashableObject} obj object with updateHash method
	 * @param {string | HashConstructor} hashFunction the hash function to use
	 */
	constructor(obj, hashFunction = "md4") {
		this._obj = obj;
		this._hash = undefined;
		this._hashFunction = hashFunction;
	}

	/**
	 * @returns {string} hash of object
	 */
	toString() {
		if (this._hash === undefined) {
			const hash = createHash(this._hashFunction);
			this._obj.updateHash(hash);
			this._hash = /** @type {string} */ (hash.digest("base64"));
		}
		return this._hash;
	}
}

/** @type {Map<string | HashConstructor, WeakMap<HashableObject, LazyHashedEtag>>} */
const mapStrings = new Map();

/** @type {WeakMap<HashConstructor, WeakMap<HashableObject, LazyHashedEtag>>} */
const mapObjects = new WeakMap();

/**
 * @param {HashableObject} obj object with updateHash method
 * @param {(string | HashConstructor)=} hashFunction the hash function to use
 * @returns {LazyHashedEtag} etag
 */
const getter = (obj, hashFunction = "md4") => {
	let innerMap;
	if (typeof hashFunction === "string") {
		innerMap = mapStrings.get(hashFunction);
		if (innerMap === undefined) {
			const newHash = new LazyHashedEtag(obj, hashFunction);
			innerMap = new WeakMap();
			innerMap.set(obj, newHash);
			mapStrings.set(hashFunction, innerMap);
			return newHash;
		}
	} else {
		innerMap = mapObjects.get(hashFunction);
		if (innerMap === undefined) {
			const newHash = new LazyHashedEtag(obj, hashFunction);
			innerMap = new WeakMap();
			innerMap.set(obj, newHash);
			mapObjects.set(hashFunction, innerMap);
			return newHash;
		}
	}
	const hash = innerMap.get(obj);
	if (hash !== undefined) return hash;
	const newHash = new LazyHashedEtag(obj, hashFunction);
	innerMap.set(obj, newHash);
	return newHash;
};

module.exports = getter;

license: mit


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

/** @typedef {import("../Cache").Etag} Etag */

class MergedEtag {
	/**
	 * @param {Etag} a first
	 * @param {Etag} b second
	 */
	constructor(a, b) {
		this.a = a;
		this.b = b;
	}

	toString() {
		return `${this.a.toString()}|${this.b.toString()}`;
	}
}

const dualObjectMap = new WeakMap();
const objectStringMap = new WeakMap();

/**
 * @param {Etag} a first
 * @param {Etag} b second
 * @returns {Etag} result
 */
const mergeEtags = (a, b) => {
	if (typeof a === "string") {
		if (typeof b === "string") {
			return `${a}|${b}`;
		} else {
			const temp = b;
			b = a;
			a = temp;
		}
	} else {
		if (typeof b !== "string") {
			// both a and b are objects
			let map = dualObjectMap.get(a);
			if (map === undefined) {
				dualObjectMap.set(a, (map = new WeakMap()));
			}
			const mergedEtag = map.get(b);
			if (mergedEtag === undefined) {
				const newMergedEtag = new MergedEtag(a, b);
				map.set(b, newMergedEtag);
				return newMergedEtag;
			} else {
				return mergedEtag;
			}
		}
	}
	// a is object, b is string
	let map = objectStringMap.get(a);
	if (map === undefined) {
		objectStringMap.set(a, (map = new Map()));
	}
	const mergedEtag = map.get(b);
	if (mergedEtag === undefined) {
		const newMergedEtag = new MergedEtag(a, b);
		map.set(b, newMergedEtag);
		return newMergedEtag;
	} else {
		return mergedEtag;
	}
};

module.exports = mergeEtags;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const path = require("path");
const webpackSchema = require("../schemas/WebpackOptions.json");

// TODO add originPath to PathItem for better errors
/**
 * @typedef {object} PathItem
 * @property {any} schema the part of the schema
 * @property {string} path the path in the config
 */

/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */

/**
 * @typedef {object} Problem
 * @property {ProblemType} type
 * @property {string} path
 * @property {string} argument
 * @property {any=} value
 * @property {number=} index
 * @property {string=} expected
 */

/**
 * @typedef {object} LocalProblem
 * @property {ProblemType} type
 * @property {string} path
 * @property {string=} expected
 */

/**
 * @typedef {object} ArgumentConfig
 * @property {string} description
 * @property {string} [negatedDescription]
 * @property {string} path
 * @property {boolean} multiple
 * @property {"enum"|"string"|"path"|"number"|"boolean"|"RegExp"|"reset"} type
 * @property {any[]=} values
 */

/**
 * @typedef {object} Argument
 * @property {string} description
 * @property {"string"|"number"|"boolean"} simpleType
 * @property {boolean} multiple
 * @property {ArgumentConfig[]} configs
 */

/**
 * @param {any=} schema a json schema to create arguments for (by default webpack schema is used)
 * @returns {Record<string, Argument>} object of arguments
 */
const getArguments = (schema = webpackSchema) => {
	/** @type {Record<string, Argument>} */
	const flags = {};

	const pathToArgumentName = input => {
		return input
			.replace(/\./g, "-")
			.replace(/\[\]/g, "")
			.replace(
				/(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu,
				"$1-$2"
			)
			.replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-")
			.toLowerCase();
	};

	const getSchemaPart = path => {
		const newPath = path.split("/");

		let schemaPart = schema;

		for (let i = 1; i < newPath.length; i++) {
			const inner = schemaPart[newPath[i]];

			if (!inner) {
				break;
			}

			schemaPart = inner;
		}

		return schemaPart;
	};

	/**
	 *
	 * @param {PathItem[]} path path in the schema
	 * @returns {string | undefined} description
	 */
	const getDescription = path => {
		for (const { schema } of path) {
			if (schema.cli) {
				if (schema.cli.helper) continue;
				if (schema.cli.description) return schema.cli.description;
			}
			if (schema.description) return schema.description;
		}
	};

	/**
	 *
	 * @param {PathItem[]} path path in the schema
	 * @returns {string | undefined} negative description
	 */
	const getNegatedDescription = path => {
		for (const { schema } of path) {
			if (schema.cli) {
				if (schema.cli.helper) continue;
				if (schema.cli.negatedDescription) return schema.cli.negatedDescription;
			}
		}
	};

	/**
	 *
	 * @param {PathItem[]} path path in the schema
	 * @returns {string | undefined} reset description
	 */
	const getResetDescription = path => {
		for (const { schema } of path) {
			if (schema.cli) {
				if (schema.cli.helper) continue;
				if (schema.cli.resetDescription) return schema.cli.resetDescription;
			}
		}
	};

	/**
	 *
	 * @param {any} schemaPart schema
	 * @returns {Pick<ArgumentConfig, "type"|"values">} partial argument config
	 */
	const schemaToArgumentConfig = schemaPart => {
		if (schemaPart.enum) {
			return {
				type: "enum",
				values: schemaPart.enum
			};
		}
		switch (schemaPart.type) {
			case "number":
				return {
					type: "number"
				};
			case "string":
				return {
					type: schemaPart.absolutePath ? "path" : "string"
				};
			case "boolean":
				return {
					type: "boolean"
				};
		}
		if (schemaPart.instanceof === "RegExp") {
			return {
				type: "RegExp"
			};
		}
		return undefined;
	};

	/**
	 * @param {PathItem[]} path path in the schema
	 * @returns {void}
	 */
	const addResetFlag = path => {
		const schemaPath = path[0].path;
		const name = pathToArgumentName(`${schemaPath}.reset`);
		const description =
			getResetDescription(path) ||
			`Clear all items provided in '${schemaPath}' configuration. ${getDescription(
				path
			)}`;
		flags[name] = {
			configs: [
				{
					type: "reset",
					multiple: false,
					description,
					path: schemaPath
				}
			],
			description: undefined,
			simpleType: undefined,
			multiple: undefined
		};
	};

	/**
	 * @param {PathItem[]} path full path in schema
	 * @param {boolean} multiple inside of an array
	 * @returns {number} number of arguments added
	 */
	const addFlag = (path, multiple) => {
		const argConfigBase = schemaToArgumentConfig(path[0].schema);
		if (!argConfigBase) return 0;

		const negatedDescription = getNegatedDescription(path);
		const name = pathToArgumentName(path[0].path);
		/** @type {ArgumentConfig} */
		const argConfig = {
			...argConfigBase,
			multiple,
			description: getDescription(path),
			path: path[0].path
		};

		if (negatedDescription) {
			argConfig.negatedDescription = negatedDescription;
		}

		if (!flags[name]) {
			flags[name] = {
				configs: [],
				description: undefined,
				simpleType: undefined,
				multiple: undefined
			};
		}

		if (
			flags[name].configs.some(
				item => JSON.stringify(item) === JSON.stringify(argConfig)
			)
		) {
			return 0;
		}

		if (
			flags[name].configs.some(
				item => item.type === argConfig.type && item.multiple !== multiple
			)
		) {
			if (multiple) {
				throw new Error(
					`Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)`
				);
			}
			return 0;
		}

		flags[name].configs.push(argConfig);

		return 1;
	};

	// TODO support `not` and `if/then/else`
	// TODO support `const`, but we don't use it on our schema
	/**
	 *
	 * @param {object} schemaPart the current schema
	 * @param {string} schemaPath the current path in the schema
	 * @param {{schema: object, path: string}[]} path all previous visited schemaParts
	 * @param {string | null} inArray if inside of an array, the path to the array
	 * @returns {number} added arguments
	 */
	const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => {
		while (schemaPart.$ref) {
			schemaPart = getSchemaPart(schemaPart.$ref);
		}

		const repetitions = path.filter(({ schema }) => schema === schemaPart);
		if (
			repetitions.length >= 2 ||
			repetitions.some(({ path }) => path === schemaPath)
		) {
			return 0;
		}

		if (schemaPart.cli && schemaPart.cli.exclude) return 0;

		const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path];

		let addedArguments = 0;

		addedArguments += addFlag(fullPath, !!inArray);

		if (schemaPart.type === "object") {
			if (schemaPart.properties) {
				for (const property of Object.keys(schemaPart.properties)) {
					addedArguments += traverse(
						schemaPart.properties[property],
						schemaPath ? `${schemaPath}.${property}` : property,
						fullPath,
						inArray
					);
				}
			}

			return addedArguments;
		}

		if (schemaPart.type === "array") {
			if (inArray) {
				return 0;
			}
			if (Array.isArray(schemaPart.items)) {
				let i = 0;
				for (const item of schemaPart.items) {
					addedArguments += traverse(
						item,
						`${schemaPath}.${i}`,
						fullPath,
						schemaPath
					);
				}

				return addedArguments;
			}

			addedArguments += traverse(
				schemaPart.items,
				`${schemaPath}[]`,
				fullPath,
				schemaPath
			);

			if (addedArguments > 0) {
				addResetFlag(fullPath);
				addedArguments++;
			}

			return addedArguments;
		}

		const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf;

		if (maybeOf) {
			const items = maybeOf;

			for (let i = 0; i < items.length; i++) {
				addedArguments += traverse(items[i], schemaPath, fullPath, inArray);
			}

			return addedArguments;
		}

		return addedArguments;
	};

	traverse(schema);

	// Summarize flags
	for (const name of Object.keys(flags)) {
		const argument = flags[name];
		argument.description = argument.configs.reduce((desc, { description }) => {
			if (!desc) return description;
			if (!description) return desc;
			if (desc.includes(description)) return desc;
			return `${desc} ${description}`;
		}, /** @type {string | undefined} */ (undefined));
		argument.simpleType = argument.configs.reduce((t, argConfig) => {
			/** @type {"string" | "number" | "boolean"} */
			let type = "string";
			switch (argConfig.type) {
				case "number":
					type = "number";
					break;
				case "reset":
				case "boolean":
					type = "boolean";
					break;
				case "enum":
					if (argConfig.values.every(v => typeof v === "boolean"))
						type = "boolean";
					if (argConfig.values.every(v => typeof v === "number"))
						type = "number";
					break;
			}
			if (t === undefined) return type;
			return t === type ? t : "string";
		}, /** @type {"string" | "number" | "boolean" | undefined} */ (undefined));
		argument.multiple = argument.configs.some(c => c.multiple);
	}

	return flags;
};

const cliAddedItems = new WeakMap();

/**
 * @param {any} config configuration
 * @param {string} schemaPath path in the config
 * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
 * @returns {{ problem?: LocalProblem, object?: any, property?: string | number, value?: any }} problem or object with property and value
 */
const getObjectAndProperty = (config, schemaPath, index = 0) => {
	if (!schemaPath) return { value: config };
	const parts = schemaPath.split(".");
	let property = parts.pop();
	let current = config;
	let i = 0;
	for (const part of parts) {
		const isArray = part.endsWith("[]");
		const name = isArray ? part.slice(0, -2) : part;
		let value = current[name];
		if (isArray) {
			if (value === undefined) {
				value = {};
				current[name] = [...Array.from({ length: index }), value];
				cliAddedItems.set(current[name], index + 1);
			} else if (!Array.isArray(value)) {
				return {
					problem: {
						type: "unexpected-non-array-in-path",
						path: parts.slice(0, i).join(".")
					}
				};
			} else {
				let addedItems = cliAddedItems.get(value) || 0;
				while (addedItems <= index) {
					value.push(undefined);
					addedItems++;
				}
				cliAddedItems.set(value, addedItems);
				const x = value.length - addedItems + index;
				if (value[x] === undefined) {
					value[x] = {};
				} else if (value[x] === null || typeof value[x] !== "object") {
					return {
						problem: {
							type: "unexpected-non-object-in-path",
							path: parts.slice(0, i).join(".")
						}
					};
				}
				value = value[x];
			}
		} else {
			if (value === undefined) {
				value = current[name] = {};
			} else if (value === null || typeof value !== "object") {
				return {
					problem: {
						type: "unexpected-non-object-in-path",
						path: parts.slice(0, i).join(".")
					}
				};
			}
		}
		current = value;
		i++;
	}
	let value = current[property];
	if (property.endsWith("[]")) {
		const name = property.slice(0, -2);
		const value = current[name];
		if (value === undefined) {
			current[name] = [...Array.from({ length: index }), undefined];
			cliAddedItems.set(current[name], index + 1);
			return { object: current[name], property: index, value: undefined };
		} else if (!Array.isArray(value)) {
			current[name] = [value, ...Array.from({ length: index }), undefined];
			cliAddedItems.set(current[name], index + 1);
			return { object: current[name], property: index + 1, value: undefined };
		} else {
			let addedItems = cliAddedItems.get(value) || 0;
			while (addedItems <= index) {
				value.push(undefined);
				addedItems++;
			}
			cliAddedItems.set(value, addedItems);
			const x = value.length - addedItems + index;
			if (value[x] === undefined) {
				value[x] = {};
			} else if (value[x] === null || typeof value[x] !== "object") {
				return {
					problem: {
						type: "unexpected-non-object-in-path",
						path: schemaPath
					}
				};
			}
			return {
				object: value,
				property: x,
				value: value[x]
			};
		}
	}
	return { object: current, property, value };
};

/**
 * @param {any} config configuration
 * @param {string} schemaPath path in the config
 * @param {any} value parsed value
 * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
 * @returns {LocalProblem | null} problem or null for success
 */
const setValue = (config, schemaPath, value, index) => {
	const { problem, object, property } = getObjectAndProperty(
		config,
		schemaPath,
		index
	);
	if (problem) return problem;
	object[property] = value;
	return null;
};

/**
 * @param {ArgumentConfig} argConfig processing instructions
 * @param {any} config configuration
 * @param {any} value the value
 * @param {number | undefined} index the index if multiple values provided
 * @returns {LocalProblem | null} a problem if any
 */
const processArgumentConfig = (argConfig, config, value, index) => {
	if (index !== undefined && !argConfig.multiple) {
		return {
			type: "multiple-values-unexpected",
			path: argConfig.path
		};
	}
	const parsed = parseValueForArgumentConfig(argConfig, value);
	if (parsed === undefined) {
		return {
			type: "invalid-value",
			path: argConfig.path,
			expected: getExpectedValue(argConfig)
		};
	}
	const problem = setValue(config, argConfig.path, parsed, index);
	if (problem) return problem;
	return null;
};

/**
 * @param {ArgumentConfig} argConfig processing instructions
 * @returns {string | undefined} expected message
 */
const getExpectedValue = argConfig => {
	switch (argConfig.type) {
		default:
			return argConfig.type;
		case "boolean":
			return "true | false";
		case "RegExp":
			return "regular expression (example: /ab?c*/)";
		case "enum":
			return argConfig.values.map(v => `${v}`).join(" | ");
		case "reset":
			return "true (will reset the previous value to an empty array)";
	}
};

/**
 * @param {ArgumentConfig} argConfig processing instructions
 * @param {any} value the value
 * @returns {any | undefined} parsed value
 */
const parseValueForArgumentConfig = (argConfig, value) => {
	switch (argConfig.type) {
		case "string":
			if (typeof value === "string") {
				return value;
			}
			break;
		case "path":
			if (typeof value === "string") {
				return path.resolve(value);
			}
			break;
		case "number":
			if (typeof value === "number") return value;
			if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) {
				const n = +value;
				if (!isNaN(n)) return n;
			}
			break;
		case "boolean":
			if (typeof value === "boolean") return value;
			if (value === "true") return true;
			if (value === "false") return false;
			break;
		case "RegExp":
			if (value instanceof RegExp) return value;
			if (typeof value === "string") {
				// cspell:word yugi
				const match = /^\/(.*)\/([yugi]*)$/.exec(value);
				if (match && !/[^\\]\//.test(match[1]))
					return new RegExp(match[1], match[2]);
			}
			break;
		case "enum":
			if (argConfig.values.includes(value)) return value;
			for (const item of argConfig.values) {
				if (`${item}` === value) return item;
			}
			break;
		case "reset":
			if (value === true) return [];
			break;
	}
};

/**
 * @param {Record<string, Argument>} args object of arguments
 * @param {any} config configuration
 * @param {Record<string, string | number | boolean | RegExp | (string | number | boolean | RegExp)[]>} values object with values
 * @returns {Problem[] | null} problems or null for success
 */
const processArguments = (args, config, values) => {
	/** @type {Problem[]} */
	const problems = [];
	for (const key of Object.keys(values)) {
		const arg = args[key];
		if (!arg) {
			problems.push({
				type: "unknown-argument",
				path: "",
				argument: key
			});
			continue;
		}
		const processValue = (value, i) => {
			const currentProblems = [];
			for (const argConfig of arg.configs) {
				const problem = processArgumentConfig(argConfig, config, value, i);
				if (!problem) {
					return;
				}
				currentProblems.push({
					...problem,
					argument: key,
					value: value,
					index: i
				});
			}
			problems.push(...currentProblems);
		};
		let value = values[key];
		if (Array.isArray(value)) {
			for (let i = 0; i < value.length; i++) {
				processValue(value[i], i);
			}
		} else {
			processValue(value, undefined);
		}
	}
	if (problems.length === 0) return null;
	return problems;
};

exports.getArguments = getArguments;
exports.processArguments = processArguments;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Sergey Melyukov @smelukov
*/

"use strict";

const browserslist = require("browserslist");
const path = require("path");

/** @typedef {import("./target").ApiTargetProperties} ApiTargetProperties */
/** @typedef {import("./target").EcmaTargetProperties} EcmaTargetProperties */
/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */

// [[C:]/path/to/config][:env]
const inputRx = /^(?:((?:[A-Z]:)?[/\\].*?))?(?::(.+?))?$/i;

/**
 * @typedef {object} BrowserslistHandlerConfig
 * @property {string=} configPath
 * @property {string=} env
 * @property {string=} query
 */

/**
 * @param {string | null | undefined} input input string
 * @param {string} context the context directory
 * @returns {BrowserslistHandlerConfig} config
 */
const parse = (input, context) => {
	if (!input) {
		return {};
	}

	if (path.isAbsolute(input)) {
		const [, configPath, env] = inputRx.exec(input) || [];
		return { configPath, env };
	}

	const config = browserslist.findConfig(context);

	if (config && Object.keys(config).includes(input)) {
		return { env: input };
	}

	return { query: input };
};

/**
 * @param {string | null | undefined} input input string
 * @param {string} context the context directory
 * @returns {string[] | undefined} selected browsers
 */
const load = (input, context) => {
	const { configPath, env, query } = parse(input, context);

	// if a query is specified, then use it, else
	// if a path to a config is specified then load it, else
	// find a nearest config
	const config = query
		? query
		: configPath
			? browserslist.loadConfig({
					config: configPath,
					env
				})
			: browserslist.loadConfig({ path: context, env });

	if (!config) return;
	return browserslist(config);
};

/**
 * @param {string[]} browsers supported browsers list
 * @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties
 */
const resolve = browsers => {
	/**
	 * Checks all against a version number
	 * @param {Record<string, number | [number, number]>} versions first supported version
	 * @returns {boolean} true if supports
	 */
	const rawChecker = versions => {
		return browsers.every(v => {
			const [name, parsedVersion] = v.split(" ");
			if (!name) return false;
			const requiredVersion = versions[name];
			if (!requiredVersion) return false;
			const [parsedMajor, parserMinor] =
				// safari TP supports all features for normal safari
				parsedVersion === "TP"
					? [Infinity, Infinity]
					: parsedVersion.includes("-")
						? parsedVersion.split("-")[0].split(".")
						: parsedVersion.split(".");
			if (typeof requiredVersion === "number") {
				return +parsedMajor >= requiredVersion;
			}
			return requiredVersion[0] === +parsedMajor
				? +parserMinor >= requiredVersion[1]
				: +parsedMajor > requiredVersion[0];
		});
	};
	const anyNode = browsers.some(b => /^node /.test(b));
	const anyBrowser = browsers.some(b => /^(?!node)/.test(b));
	const browserProperty = !anyBrowser ? false : anyNode ? null : true;
	const nodeProperty = !anyNode ? false : anyBrowser ? null : true;
	// Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features
	const es6DynamicImport = rawChecker({
		chrome: 63,
		and_chr: 63,
		edge: 79,
		firefox: 67,
		and_ff: 67,
		// ie: Not supported
		opera: 50,
		op_mob: 46,
		safari: [11, 1],
		ios_saf: [11, 3],
		samsung: [8, 2],
		android: 63,
		and_qq: [10, 4],
		baidu: [13, 18],
		and_uc: [15, 5],
		kaios: [3, 0],
		node: [12, 17]
	});

	return {
		const: rawChecker({
			chrome: 49,
			and_chr: 49,
			edge: 12,
			// Prior to Firefox 13, const is implemented, but re-assignment is not failing.
			// Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError.
			firefox: 36,
			and_ff: 36,
			// Not supported in for-in and for-of loops
			// ie: Not supported
			opera: 36,
			op_mob: 36,
			safari: [10, 0],
			ios_saf: [10, 0],
			// Before 5.0 supported correctly in strict mode, otherwise supported without block scope
			samsung: [5, 0],
			android: 37,
			and_qq: [10, 4],
			// Supported correctly in strict mode, otherwise supported without block scope
			baidu: [13, 18],
			and_uc: [12, 12],
			kaios: [2, 5],
			node: [6, 0]
		}),
		arrowFunction: rawChecker({
			chrome: 45,
			and_chr: 45,
			edge: 12,
			// The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required.
			// Prior to Firefox 39, a line terminator (\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\n => {} will now throw a SyntaxError in this and later versions.
			firefox: 39,
			and_ff: 39,
			// ie: Not supported,
			opera: 32,
			op_mob: 32,
			safari: 10,
			ios_saf: 10,
			samsung: [5, 0],
			android: 45,
			and_qq: [10, 4],
			baidu: [7, 12],
			and_uc: [12, 12],
			kaios: [2, 5],
			node: [6, 0]
		}),
		forOf: rawChecker({
			chrome: 38,
			and_chr: 38,
			edge: 12,
			// Prior to Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError ("missing = in const declaration").
			firefox: 51,
			and_ff: 51,
			// ie: Not supported,
			opera: 25,
			op_mob: 25,
			safari: 7,
			ios_saf: 7,
			samsung: [3, 0],
			android: 38,
			// and_qq: Unknown support
			// baidu: Unknown support
			// and_uc: Unknown support
			kaios: [3, 0],
			node: [0, 12]
		}),
		destructuring: rawChecker({
			chrome: 49,
			and_chr: 49,
			edge: 14,
			firefox: 41,
			and_ff: 41,
			// ie: Not supported,
			opera: 36,
			op_mob: 36,
			safari: 8,
			ios_saf: 8,
			samsung: [5, 0],
			android: 49,
			// and_qq: Unknown support
			// baidu: Unknown support
			// and_uc: Unknown support
			kaios: [2, 5],
			node: [6, 0]
		}),
		bigIntLiteral: rawChecker({
			chrome: 67,
			and_chr: 67,
			edge: 79,
			firefox: 68,
			and_ff: 68,
			// ie: Not supported,
			opera: 54,
			op_mob: 48,
			safari: 14,
			ios_saf: 14,
			samsung: [9, 2],
			android: 67,
			and_qq: [13, 1],
			baidu: [13, 18],
			and_uc: [15, 5],
			kaios: [3, 0],
			node: [10, 4]
		}),
		// Support syntax `import` and `export` and no limitations and bugs on Node.js
		// Not include `export * as namespace`
		module: rawChecker({
			chrome: 61,
			and_chr: 61,
			edge: 16,
			firefox: 60,
			and_ff: 60,
			// ie: Not supported,
			opera: 48,
			op_mob: 45,
			safari: [10, 1],
			ios_saf: [10, 3],
			samsung: [8, 0],
			android: 61,
			and_qq: [10, 4],
			baidu: [13, 18],
			and_uc: [15, 5],
			kaios: [3, 0],
			node: [12, 17]
		}),
		dynamicImport: es6DynamicImport,
		dynamicImportInWorker: es6DynamicImport && !anyNode,
		// browserslist does not have info about globalThis
		// so this is based on mdn-browser-compat-data
		globalThis: rawChecker({
			chrome: 71,
			and_chr: 71,
			edge: 79,
			firefox: 65,
			and_ff: 65,
			// ie: Not supported,
			opera: 58,
			op_mob: 50,
			safari: [12, 1],
			ios_saf: [12, 2],
			samsung: [10, 1],
			android: 71,
			// and_qq: Unknown support
			// baidu: Unknown support
			// and_uc: Unknown support
			kaios: [3, 0],
			node: 12
		}),
		optionalChaining: rawChecker({
			chrome: 80,
			and_chr: 80,
			edge: 80,
			firefox: 74,
			and_ff: 79,
			// ie: Not supported,
			opera: 67,
			op_mob: 64,
			safari: [13, 1],
			ios_saf: [13, 4],
			samsung: 13,
			android: 80,
			// and_qq: Not supported
			// baidu: Not supported
			// and_uc: Not supported
			kaios: [3, 0],
			node: 14
		}),
		templateLiteral: rawChecker({
			chrome: 41,
			and_chr: 41,
			edge: 13,
			firefox: 34,
			and_ff: 34,
			// ie: Not supported,
			opera: 29,
			op_mob: 64,
			safari: [9, 1],
			ios_saf: 9,
			samsung: 4,
			android: 41,
			and_qq: [10, 4],
			baidu: [7, 12],
			and_uc: [12, 12],
			kaios: [2, 5],
			node: 4
		}),
		asyncFunction: rawChecker({
			chrome: 55,
			and_chr: 55,
			edge: 15,
			firefox: 52,
			and_ff: 52,
			// ie: Not supported,
			opera: 42,
			op_mob: 42,
			safari: 11,
			ios_saf: 11,
			samsung: [6, 2],
			android: 55,
			and_qq: [13, 1],
			baidu: [13, 18],
			and_uc: [15, 5],
			kaios: 3,
			node: [7, 6]
		}),
		browser: browserProperty,
		electron: false,
		node: nodeProperty,
		nwjs: false,
		web: browserProperty,
		webworker: false,

		document: browserProperty,
		fetchWasm: browserProperty,
		global: nodeProperty,
		importScripts: false,
		importScriptsInWorker: true,
		nodeBuiltins: nodeProperty,
		nodePrefixForCoreModules:
			nodeProperty &&
			!browsers.some(b => /^node 15/.test(b)) &&
			rawChecker({
				node: [14, 18]
			}),
		require: nodeProperty
	};
};

module.exports = {
	resolve,
	load
};


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const fs = require("fs");
const path = require("path");
const {
	JAVASCRIPT_MODULE_TYPE_AUTO,
	JSON_MODULE_TYPE,
	WEBASSEMBLY_MODULE_TYPE_ASYNC,
	JAVASCRIPT_MODULE_TYPE_ESM,
	JAVASCRIPT_MODULE_TYPE_DYNAMIC,
	WEBASSEMBLY_MODULE_TYPE_SYNC,
	ASSET_MODULE_TYPE,
	CSS_MODULE_TYPE_AUTO,
	CSS_MODULE_TYPE,
	CSS_MODULE_TYPE_MODULE
} = require("../ModuleTypeConstants");
const Template = require("../Template");
const { cleverMerge } = require("../util/cleverMerge");
const {
	getTargetsProperties,
	getTargetProperties,
	getDefaultTarget
} = require("./target");

/** @typedef {import("../../declarations/WebpackOptions").CacheOptions} CacheOptions */
/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptionsNormalized */
/** @typedef {import("../../declarations/WebpackOptions").Context} Context */
/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorOptions} CssGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssParserOptions} CssParserOptions */
/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */
/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */
/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
/** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */
/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */
/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */
/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */
/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */
/** @typedef {import("../../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */
/** @typedef {import("../../declarations/WebpackOptions").GeneratorOptionsByModuleTypeKnown} GeneratorOptionsByModuleTypeKnown */
/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */
/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("../../declarations/WebpackOptions").Library} Library */
/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */
/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */
/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */
/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */
/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
/** @typedef {import("../../declarations/WebpackOptions").ParserOptionsByModuleTypeKnown} ParserOptionsByModuleTypeKnown */
/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */
/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */
/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */
/** @typedef {import("../../declarations/WebpackOptions").Target} Target */
/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */
/** @typedef {import("./target").TargetProperties} TargetProperties */

/**
 * @typedef {object} ResolvedOptions
 * @property {PlatformTargetProperties | false} platform - platform target properties
 */

const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
const DEFAULT_CACHE_NAME = "default";

/**
 * Sets a constant default value when undefined
 * @template T
 * @template {keyof T} P
 * @param {T} obj an object
 * @param {P} prop a property of this object
 * @param {T[P]} value a default value of the property
 * @returns {void}
 */
const D = (obj, prop, value) => {
	if (obj[prop] === undefined) {
		obj[prop] = value;
	}
};

/**
 * Sets a dynamic default value when undefined, by calling the factory function
 * @template T
 * @template {keyof T} P
 * @param {T} obj an object
 * @param {P} prop a property of this object
 * @param {function(): T[P]} factory a default value factory for the property
 * @returns {void}
 */
const F = (obj, prop, factory) => {
	if (obj[prop] === undefined) {
		obj[prop] = factory();
	}
};

/**
 * Sets a dynamic default value when undefined, by calling the factory function.
 * factory must return an array or undefined
 * When the current value is already an array an contains "..." it's replaced with
 * the result of the factory function
 * @template T
 * @template {keyof T} P
 * @param {T} obj an object
 * @param {P} prop a property of this object
 * @param {function(): T[P]} factory a default value factory for the property
 * @returns {void}
 */
const A = (obj, prop, factory) => {
	const value = obj[prop];
	if (value === undefined) {
		obj[prop] = factory();
	} else if (Array.isArray(value)) {
		/** @type {any[] | undefined} */
		let newArray = undefined;
		for (let i = 0; i < value.length; i++) {
			const item = value[i];
			if (item === "...") {
				if (newArray === undefined) {
					newArray = value.slice(0, i);
					obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
				}
				const items = /** @type {any[]} */ (/** @type {unknown} */ (factory()));
				if (items !== undefined) {
					for (const item of items) {
						newArray.push(item);
					}
				}
			} else if (newArray !== undefined) {
				newArray.push(item);
			}
		}
	}
};

/**
 * @param {WebpackOptionsNormalized} options options to be modified
 * @returns {void}
 */
const applyWebpackOptionsBaseDefaults = options => {
	F(options, "context", () => process.cwd());
	applyInfrastructureLoggingDefaults(options.infrastructureLogging);
};

/**
 * @param {WebpackOptionsNormalized} options options to be modified
 * @param {number} [compilerIndex] index of compiler
 * @returns {ResolvedOptions} Resolved options after apply defaults
 */
const applyWebpackOptionsDefaults = (options, compilerIndex) => {
	F(options, "context", () => process.cwd());
	F(options, "target", () => {
		return getDefaultTarget(/** @type {string} */ (options.context));
	});

	const { mode, name, target } = options;

	let targetProperties =
		target === false
			? /** @type {false} */ (false)
			: typeof target === "string"
				? getTargetProperties(target, /** @type {Context} */ (options.context))
				: getTargetsProperties(
						/** @type {string[]} */ (target),
						/** @type {Context} */ (options.context)
					);

	const development = mode === "development";
	const production = mode === "production" || !mode;

	if (typeof options.entry !== "function") {
		for (const key of Object.keys(options.entry)) {
			F(
				options.entry[key],
				"import",
				() => /** @type {[string]} */ (["./src"])
			);
		}
	}

	F(options, "devtool", () => (development ? "eval" : false));
	D(options, "watch", false);
	D(options, "profile", false);
	D(options, "parallelism", 100);
	D(options, "recordsInputPath", false);
	D(options, "recordsOutputPath", false);

	applyExperimentsDefaults(options.experiments, {
		production,
		development,
		targetProperties
	});

	const futureDefaults =
		/** @type {NonNullable<ExperimentsNormalized["futureDefaults"]>} */
		(options.experiments.futureDefaults);

	F(options, "cache", () =>
		development ? { type: /** @type {"memory"} */ ("memory") } : false
	);
	applyCacheDefaults(options.cache, {
		name: name || DEFAULT_CACHE_NAME,
		mode: mode || "production",
		development,
		cacheUnaffected: options.experiments.cacheUnaffected,
		compilerIndex
	});
	const cache = !!options.cache;

	applySnapshotDefaults(options.snapshot, {
		production,
		futureDefaults
	});

	applyModuleDefaults(options.module, {
		cache,
		syncWebAssembly:
			/** @type {NonNullable<ExperimentsNormalized["syncWebAssembly"]>} */
			(options.experiments.syncWebAssembly),
		asyncWebAssembly:
			/** @type {NonNullable<ExperimentsNormalized["asyncWebAssembly"]>} */
			(options.experiments.asyncWebAssembly),
		css:
			/** @type {NonNullable<ExperimentsNormalized["css"]>} */
			(options.experiments.css),
		futureDefaults,
		isNode: targetProperties && targetProperties.node === true,
		targetProperties
	});

	applyOutputDefaults(options.output, {
		context: /** @type {Context} */ (options.context),
		targetProperties,
		isAffectedByBrowserslist:
			target === undefined ||
			(typeof target === "string" && target.startsWith("browserslist")) ||
			(Array.isArray(target) &&
				target.some(target => target.startsWith("browserslist"))),
		outputModule:
			/** @type {NonNullable<ExperimentsNormalized["outputModule"]>} */
			(options.experiments.outputModule),
		development,
		entry: options.entry,
		futureDefaults
	});

	applyExternalsPresetsDefaults(options.externalsPresets, {
		targetProperties,
		buildHttp: !!options.experiments.buildHttp
	});

	applyLoaderDefaults(
		/** @type {NonNullable<WebpackOptionsNormalized["loader"]>} */ (
			options.loader
		),
		{ targetProperties, environment: options.output.environment }
	);

	F(options, "externalsType", () => {
		const validExternalTypes = require("../../schemas/WebpackOptions.json")
			.definitions.ExternalsType.enum;
		return options.output.library &&
			validExternalTypes.includes(options.output.library.type)
			? /** @type {ExternalsType} */ (options.output.library.type)
			: options.output.module
				? "module"
				: "var";
	});

	applyNodeDefaults(options.node, {
		futureDefaults:
			/** @type {NonNullable<WebpackOptionsNormalized["experiments"]["futureDefaults"]>} */
			(options.experiments.futureDefaults),
		outputModule: options.output.module,
		targetProperties
	});

	F(options, "performance", () =>
		production &&
		targetProperties &&
		(targetProperties.browser || targetProperties.browser === null)
			? {}
			: false
	);
	applyPerformanceDefaults(
		/** @type {NonNullable<WebpackOptionsNormalized["performance"]>} */
		(options.performance),
		{
			production
		}
	);

	applyOptimizationDefaults(options.optimization, {
		development,
		production,
		css:
			/** @type {NonNullable<ExperimentsNormalized["css"]>} */
			(options.experiments.css),
		records: !!(options.recordsInputPath || options.recordsOutputPath)
	});

	options.resolve = cleverMerge(
		getResolveDefaults({
			cache,
			context: /** @type {Context} */ (options.context),
			targetProperties,
			mode: /** @type {Mode} */ (options.mode),
			css:
				/** @type {NonNullable<ExperimentsNormalized["css"]>} */
				(options.experiments.css)
		}),
		options.resolve
	);

	options.resolveLoader = cleverMerge(
		getResolveLoaderDefaults({ cache }),
		options.resolveLoader
	);

	return {
		platform:
			targetProperties === false
				? targetProperties
				: {
						web: targetProperties.web,
						browser: targetProperties.browser,
						webworker: targetProperties.webworker,
						node: targetProperties.node,
						nwjs: targetProperties.nwjs,
						electron: targetProperties.electron
					}
	};
};

/**
 * @param {ExperimentsNormalized} experiments options
 * @param {object} options options
 * @param {boolean} options.production is production
 * @param {boolean} options.development is development mode
 * @param {TargetProperties | false} options.targetProperties target properties
 * @returns {void}
 */
const applyExperimentsDefaults = (
	experiments,
	{ production, development, targetProperties }
) => {
	D(experiments, "futureDefaults", false);
	D(experiments, "backCompat", !experiments.futureDefaults);
	D(experiments, "syncWebAssembly", false);
	D(experiments, "asyncWebAssembly", experiments.futureDefaults);
	D(experiments, "outputModule", false);
	D(experiments, "layers", false);
	D(experiments, "lazyCompilation", undefined);
	D(experiments, "buildHttp", undefined);
	D(experiments, "cacheUnaffected", experiments.futureDefaults);
	F(experiments, "css", () => (experiments.futureDefaults ? true : undefined));

	// TODO webpack 6: remove this. topLevelAwait should be enabled by default
	let shouldEnableTopLevelAwait = true;
	if (typeof experiments.topLevelAwait === "boolean") {
		shouldEnableTopLevelAwait = experiments.topLevelAwait;
	}
	D(experiments, "topLevelAwait", shouldEnableTopLevelAwait);

	if (typeof experiments.buildHttp === "object") {
		D(experiments.buildHttp, "frozen", production);
		D(experiments.buildHttp, "upgrade", false);
	}
};

/**
 * @param {CacheOptionsNormalized} cache options
 * @param {object} options options
 * @param {string} options.name name
 * @param {Mode} options.mode mode
 * @param {boolean} options.development is development mode
 * @param {number} [options.compilerIndex] index of compiler
 * @param {Experiments["cacheUnaffected"]} options.cacheUnaffected the cacheUnaffected experiment is enabled
 * @returns {void}
 */
const applyCacheDefaults = (
	cache,
	{ name, mode, development, cacheUnaffected, compilerIndex }
) => {
	if (cache === false) return;
	switch (cache.type) {
		case "filesystem":
			F(cache, "name", () =>
				compilerIndex !== undefined
					? `${name + "-" + mode}__compiler${compilerIndex + 1}__`
					: name + "-" + mode
			);
			D(cache, "version", "");
			F(cache, "cacheDirectory", () => {
				const cwd = process.cwd();
				/** @type {string | undefined} */
				let dir = cwd;
				for (;;) {
					try {
						if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
						// eslint-disable-next-line no-empty
					} catch (e) {}
					const parent = path.dirname(dir);
					if (dir === parent) {
						dir = undefined;
						break;
					}
					dir = parent;
				}
				if (!dir) {
					return path.resolve(cwd, ".cache/webpack");
				} else if (process.versions.pnp === "1") {
					return path.resolve(dir, ".pnp/.cache/webpack");
				} else if (process.versions.pnp === "3") {
					return path.resolve(dir, ".yarn/.cache/webpack");
				} else {
					return path.resolve(dir, "node_modules/.cache/webpack");
				}
			});
			F(cache, "cacheLocation", () =>
				path.resolve(
					/** @type {NonNullable<FileCacheOptions["cacheDirectory"]>} */
					(cache.cacheDirectory),
					/** @type {NonNullable<FileCacheOptions["name"]>} */ (cache.name)
				)
			);
			D(cache, "hashAlgorithm", "md4");
			D(cache, "store", "pack");
			D(cache, "compression", false);
			D(cache, "profile", false);
			D(cache, "idleTimeout", 60000);
			D(cache, "idleTimeoutForInitialStore", 5000);
			D(cache, "idleTimeoutAfterLargeChanges", 1000);
			D(cache, "maxMemoryGenerations", development ? 5 : Infinity);
			D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month
			D(cache, "allowCollectingMemory", development);
			D(cache, "memoryCacheUnaffected", development && cacheUnaffected);
			D(cache, "readonly", false);
			D(
				/** @type {NonNullable<FileCacheOptions["buildDependencies"]>} */
				(cache.buildDependencies),
				"defaultWebpack",
				[path.resolve(__dirname, "..") + path.sep]
			);
			break;
		case "memory":
			D(cache, "maxGenerations", Infinity);
			D(cache, "cacheUnaffected", development && cacheUnaffected);
			break;
	}
};

/**
 * @param {SnapshotOptions} snapshot options
 * @param {object} options options
 * @param {boolean} options.production is production
 * @param {boolean} options.futureDefaults is future defaults enabled
 * @returns {void}
 */
const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
	if (futureDefaults) {
		F(snapshot, "managedPaths", () =>
			process.versions.pnp === "3"
				? [
						/^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/
					]
				: [/^(.+?[\\/]node_modules[\\/])/]
		);
		F(snapshot, "immutablePaths", () =>
			process.versions.pnp === "3"
				? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/]
				: []
		);
	} else {
		A(snapshot, "managedPaths", () => {
			if (process.versions.pnp === "3") {
				const match =
					/^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
						require.resolve("watchpack")
					);
				if (match) {
					return [path.resolve(match[1], "unplugged")];
				}
			} else {
				const match = /^(.+?[\\/]node_modules[\\/])/.exec(
					require.resolve("watchpack")
				);
				if (match) {
					return [match[1]];
				}
			}
			return [];
		});
		A(snapshot, "immutablePaths", () => {
			if (process.versions.pnp === "1") {
				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")
					);
				if (match) {
					return [match[1]];
				}
			}
			return [];
		});
	}
	F(snapshot, "unmanagedPaths", () => []);
	F(snapshot, "resolveBuildDependencies", () => ({
		timestamp: true,
		hash: true
	}));
	F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true }));
	F(snapshot, "module", () =>
		production ? { timestamp: true, hash: true } : { timestamp: true }
	);
	F(snapshot, "resolve", () =>
		production ? { timestamp: true, hash: true } : { timestamp: true }
	);
};

/**
 * @param {JavascriptParserOptions} parserOptions parser options
 * @param {object} options options
 * @param {boolean} options.futureDefaults is future defaults enabled
 * @param {boolean} options.isNode is node target platform
 * @returns {void}
 */
const applyJavascriptParserOptionsDefaults = (
	parserOptions,
	{ futureDefaults, isNode }
) => {
	D(parserOptions, "unknownContextRequest", ".");
	D(parserOptions, "unknownContextRegExp", false);
	D(parserOptions, "unknownContextRecursive", true);
	D(parserOptions, "unknownContextCritical", true);
	D(parserOptions, "exprContextRequest", ".");
	D(parserOptions, "exprContextRegExp", false);
	D(parserOptions, "exprContextRecursive", true);
	D(parserOptions, "exprContextCritical", true);
	D(parserOptions, "wrappedContextRegExp", /.*/);
	D(parserOptions, "wrappedContextRecursive", true);
	D(parserOptions, "wrappedContextCritical", false);
	D(parserOptions, "strictThisContextOnImports", false);
	D(parserOptions, "importMeta", true);
	D(parserOptions, "dynamicImportMode", "lazy");
	D(parserOptions, "dynamicImportPrefetch", false);
	D(parserOptions, "dynamicImportPreload", false);
	D(parserOptions, "dynamicImportFetchPriority", false);
	D(parserOptions, "createRequire", isNode);
	if (futureDefaults) D(parserOptions, "exportsPresence", "error");
};

/**
 * @param {CssGeneratorOptions} generatorOptions generator options
 * @param {object} options options
 * @param {TargetProperties | false} options.targetProperties target properties
 * @returns {void}
 */
const applyCssGeneratorOptionsDefaults = (
	generatorOptions,
	{ targetProperties }
) => {
	D(
		generatorOptions,
		"exportsOnly",
		!targetProperties || !targetProperties.document
	);
	D(generatorOptions, "esModule", true);
};

/**
 * @param {ModuleOptions} module options
 * @param {object} options options
 * @param {boolean} options.cache is caching enabled
 * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled
 * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
 * @param {boolean} options.css is css enabled
 * @param {boolean} options.futureDefaults is future defaults enabled
 * @param {boolean} options.isNode is node target platform
 * @param {TargetProperties | false} options.targetProperties target properties
 * @returns {void}
 */
const applyModuleDefaults = (
	module,
	{
		cache,
		syncWebAssembly,
		asyncWebAssembly,
		css,
		futureDefaults,
		isNode,
		targetProperties
	}
) => {
	if (cache) {
		D(
			module,
			"unsafeCache",
			/**
			 * @param {Module} module module
			 * @returns {boolean | null | string} true, if we want to cache the module
			 */
			module => {
				const name = module.nameForCondition();
				return name && NODE_MODULES_REGEXP.test(name);
			}
		);
	} else {
		D(module, "unsafeCache", false);
	}

	F(module.parser, ASSET_MODULE_TYPE, () => ({}));
	F(
		/** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
		(module.parser.asset),
		"dataUrlCondition",
		() => ({})
	);
	if (
		typeof (
			/** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
			(module.parser.asset).dataUrlCondition
		) === "object"
	) {
		D(
			/** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
			(module.parser.asset).dataUrlCondition,
			"maxSize",
			8096
		);
	}

	F(module.parser, "javascript", () => ({}));

	applyJavascriptParserOptionsDefaults(
		/** @type {NonNullable<ParserOptionsByModuleTypeKnown["javascript"]>} */
		(module.parser.javascript),
		{
			futureDefaults,
			isNode
		}
	);

	if (css) {
		F(module.parser, "css", () => ({}));

		D(module.parser.css, "namedExports", true);

		F(module.generator, "css", () => ({}));

		applyCssGeneratorOptionsDefaults(
			/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown["css"]>} */
			(module.generator.css),
			{ targetProperties }
		);

		F(module.generator, "css/auto", () => ({}));
		D(
			module.generator["css/auto"],
			"localIdentName",
			"[uniqueName]-[id]-[local]"
		);
		D(module.generator["css/auto"], "exportsConvention", "as-is");

		F(module.generator, "css/module", () => ({}));
		D(
			module.generator["css/module"],
			"localIdentName",
			"[uniqueName]-[id]-[local]"
		);
		D(module.generator["css/module"], "exportsConvention", "as-is");

		F(module.generator, "css/global", () => ({}));
		D(
			module.generator["css/global"],
			"localIdentName",
			"[uniqueName]-[id]-[local]"
		);
		D(module.generator["css/global"], "exportsConvention", "as-is");
	}

	A(module, "defaultRules", () => {
		const esm = {
			type: JAVASCRIPT_MODULE_TYPE_ESM,
			resolve: {
				byDependency: {
					esm: {
						fullySpecified: true
					}
				}
			}
		};
		const commonjs = {
			type: JAVASCRIPT_MODULE_TYPE_DYNAMIC
		};
		/** @type {RuleSetRules} */
		const rules = [
			{
				mimetype: "application/node",
				type: JAVASCRIPT_MODULE_TYPE_AUTO
			},
			{
				test: /\.json$/i,
				type: JSON_MODULE_TYPE
			},
			{
				mimetype: "application/json",
				type: JSON_MODULE_TYPE
			},
			{
				test: /\.mjs$/i,
				...esm
			},
			{
				test: /\.js$/i,
				descriptionData: {
					type: "module"
				},
				...esm
			},
			{
				test: /\.cjs$/i,
				...commonjs
			},
			{
				test: /\.js$/i,
				descriptionData: {
					type: "commonjs"
				},
				...commonjs
			},
			{
				mimetype: {
					or: ["text/javascript", "application/javascript"]
				},
				...esm
			}
		];
		if (asyncWebAssembly) {
			const wasm = {
				type: WEBASSEMBLY_MODULE_TYPE_ASYNC,
				rules: [
					{
						descriptionData: {
							type: "module"
						},
						resolve: {
							fullySpecified: true
						}
					}
				]
			};
			rules.push({
				test: /\.wasm$/i,
				...wasm
			});
			rules.push({
				mimetype: "application/wasm",
				...wasm
			});
		} else if (syncWebAssembly) {
			const wasm = {
				type: WEBASSEMBLY_MODULE_TYPE_SYNC,
				rules: [
					{
						descriptionData: {
							type: "module"
						},
						resolve: {
							fullySpecified: true
						}
					}
				]
			};
			rules.push({
				test: /\.wasm$/i,
				...wasm
			});
			rules.push({
				mimetype: "application/wasm",
				...wasm
			});
		}
		if (css) {
			const resolve = {
				fullySpecified: true,
				preferRelative: true
			};
			rules.push({
				test: /\.css$/i,
				type: CSS_MODULE_TYPE_AUTO,
				resolve
			});
			rules.push({
				mimetype: "text/css+module",
				type: CSS_MODULE_TYPE_MODULE,
				resolve
			});
			rules.push({
				mimetype: "text/css",
				type: CSS_MODULE_TYPE,
				resolve
			});
		}
		rules.push(
			{
				dependency: "url",
				oneOf: [
					{
						scheme: /^data$/,
						type: "asset/inline"
					},
					{
						type: "asset/resource"
					}
				]
			},
			{
				assert: { type: "json" },
				type: JSON_MODULE_TYPE
			},
			{
				with: { type: "json" },
				type: JSON_MODULE_TYPE
			}
		);
		return rules;
	});
};

/**
 * @param {Output} output options
 * @param {object} options options
 * @param {string} options.context context
 * @param {TargetProperties | false} options.targetProperties target properties
 * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist
 * @param {boolean} options.outputModule is outputModule experiment enabled
 * @param {boolean} options.development is development mode
 * @param {Entry} options.entry entry option
 * @param {boolean} options.futureDefaults is future defaults enabled
 * @returns {void}
 */
const applyOutputDefaults = (
	output,
	{
		context,
		targetProperties: tp,
		isAffectedByBrowserslist,
		outputModule,
		development,
		entry,
		futureDefaults
	}
) => {
	/**
	 * @param {Library=} library the library option
	 * @returns {string} a readable library name
	 */
	const getLibraryName = library => {
		const libraryName =
			typeof library === "object" &&
			library &&
			!Array.isArray(library) &&
			"type" in library
				? library.name
				: /** @type {LibraryName} */ (library);
		if (Array.isArray(libraryName)) {
			return libraryName.join(".");
		} else if (typeof libraryName === "object") {
			return getLibraryName(libraryName.root);
		} else if (typeof libraryName === "string") {
			return libraryName;
		}
		return "";
	};

	F(output, "uniqueName", () => {
		const libraryName = getLibraryName(output.library).replace(
			/^\[(\\*[\w:]+\\*)\](\.)|(\.)\[(\\*[\w:]+\\*)\](?=\.|$)|\[(\\*[\w:]+\\*)\]/g,
			(m, a, d1, d2, b, c) => {
				const content = a || b || c;
				return content.startsWith("\\") && content.endsWith("\\")
					? `${d2 || ""}[${content.slice(1, -1)}]${d1 || ""}`
					: "";
			}
		);
		if (libraryName) return libraryName;
		const pkgPath = path.resolve(context, "package.json");
		try {
			const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
			return packageInfo.name || "";
		} catch (e) {
			if (/** @type {Error & { code: string }} */ (e).code !== "ENOENT") {
				/** @type {Error & { code: string }} */
				(e).message +=
					`\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
				throw e;
			}
			return "";
		}
	});

	F(output, "module", () => !!outputModule);
	D(output, "filename", output.module ? "[name].mjs" : "[name].js");
	F(output, "iife", () => !output.module);
	D(output, "importFunctionName", "import");
	D(output, "importMetaName", "import.meta");
	F(output, "chunkFilename", () => {
		const filename =
			/** @type {NonNullable<Output["chunkFilename"]>} */
			(output.filename);
		if (typeof filename !== "function") {
			const hasName = filename.includes("[name]");
			const hasId = filename.includes("[id]");
			const hasChunkHash = filename.includes("[chunkhash]");
			const hasContentHash = filename.includes("[contenthash]");
			// Anything changing depending on chunk is fine
			if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
			// Otherwise prefix "[id]." in front of the basename to make it changing
			return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
		}
		return output.module ? "[id].mjs" : "[id].js";
	});
	F(output, "cssFilename", () => {
		const filename =
			/** @type {NonNullable<Output["cssFilename"]>} */
			(output.filename);
		if (typeof filename !== "function") {
			return filename.replace(/\.[mc]?js(\?|$)/, ".css$1");
		}
		return "[id].css";
	});
	F(output, "cssChunkFilename", () => {
		const chunkFilename =
			/** @type {NonNullable<Output["cssChunkFilename"]>} */
			(output.chunkFilename);
		if (typeof chunkFilename !== "function") {
			return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1");
		}
		return "[id].css";
	});
	D(output, "cssHeadDataCompression", !development);
	D(output, "assetModuleFilename", "[hash][ext][query]");
	D(output, "webassemblyModuleFilename", "[hash].module.wasm");
	D(output, "compareBeforeEmit", true);
	D(output, "charset", true);
	const uniqueNameId = Template.toIdentifier(
		/** @type {NonNullable<Output["uniqueName"]>} */ (output.uniqueName)
	);
	F(output, "hotUpdateGlobal", () => "webpackHotUpdate" + uniqueNameId);
	F(output, "chunkLoadingGlobal", () => "webpackChunk" + uniqueNameId);
	F(output, "globalObject", () => {
		if (tp) {
			if (tp.global) return "global";
			if (tp.globalThis) return "globalThis";
		}
		return "self";
	});
	F(output, "chunkFormat", () => {
		if (tp) {
			const helpMessage = isAffectedByBrowserslist
				? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly."
				: "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
			if (output.module) {
				if (tp.dynamicImport) return "module";
				if (tp.document) return "array-push";
				throw new Error(
					"For the selected environment is no default ESM chunk format available:\n" +
						"ESM exports can be chosen when 'import()' is available.\n" +
						"JSONP Array push can be chosen when 'document' is available.\n" +
						helpMessage
				);
			} else {
				if (tp.document) return "array-push";
				if (tp.require) return "commonjs";
				if (tp.nodeBuiltins) return "commonjs";
				if (tp.importScripts) return "array-push";
				throw new Error(
					"For the selected environment is no default script chunk format available:\n" +
						"JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" +
						"CommonJs exports can be chosen when 'require' or node builtins are available.\n" +
						helpMessage
				);
			}
		}
		throw new Error(
			"Chunk format can't be selected by default when no target is specified"
		);
	});
	D(output, "asyncChunks", true);
	F(output, "chunkLoading", () => {
		if (tp) {
			switch (output.chunkFormat) {
				case "array-push":
					if (tp.document) return "jsonp";
					if (tp.importScripts) return "import-scripts";
					break;
				case "commonjs":
					if (tp.require) return "require";
					if (tp.nodeBuiltins) return "async-node";
					break;
				case "module":
					if (tp.dynamicImport || output.module) return "import";
					break;
			}
			if (
				tp.require === null ||
				tp.nodeBuiltins === null ||
				tp.document === null ||
				tp.importScripts === null
			) {
				return "universal";
			}
		}
		return false;
	});
	F(output, "workerChunkLoading", () => {
		if (tp) {
			switch (output.chunkFormat) {
				case "array-push":
					if (tp.importScriptsInWorker) return "import-scripts";
					break;
				case "commonjs":
					if (tp.require) return "require";
					if (tp.nodeBuiltins) return "async-node";
					break;
				case "module":
					if (tp.dynamicImportInWorker || output.module) return "import";
					break;
			}
			if (
				tp.require === null ||
				tp.nodeBuiltins === null ||
				tp.importScriptsInWorker === null
			) {
				return "universal";
			}
		}
		return false;
	});
	F(output, "wasmLoading", () => {
		if (tp) {
			if (tp.fetchWasm) return "fetch";
			if (tp.nodeBuiltins)
				return output.module ? "async-node-module" : "async-node";
			if (tp.nodeBuiltins === null || tp.fetchWasm === null) {
				return "universal";
			}
		}
		return false;
	});
	F(output, "workerWasmLoading", () => output.wasmLoading);
	F(output, "devtoolNamespace", () => output.uniqueName);
	if (output.library) {
		F(output.library, "type", () => (output.module ? "module" : "var"));
	}
	F(output, "path", () => path.join(process.cwd(), "dist"));
	F(output, "pathinfo", () => development);
	D(output, "sourceMapFilename", "[file].map[query]");
	D(
		output,
		"hotUpdateChunkFilename",
		`[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
	);
	D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json");
	D(output, "crossOriginLoading", false);
	F(output, "scriptType", () => (output.module ? "module" : false));
	D(
		output,
		"publicPath",
		(tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
			? "auto"
			: ""
	);
	D(output, "workerPublicPath", "");
	D(output, "chunkLoadTimeout", 120000);
	D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4");
	D(output, "hashDigest", "hex");
	D(output, "hashDigestLength", futureDefaults ? 16 : 20);
	D(output, "strictModuleErrorHandling", false);
	D(output, "strictModuleExceptionHandling", false);

	const environment = /** @type {Environment} */ (output.environment);
	/**
	 * @param {boolean | undefined} v value
	 * @returns {boolean} true, when v is truthy or undefined
	 */
	const optimistic = v => v || v === undefined;
	/**
	 * @param {boolean | undefined} v value
	 * @param {boolean | undefined} c condition
	 * @returns {boolean | undefined} true, when v is truthy or undefined, or c is truthy
	 */
	const conditionallyOptimistic = (v, c) => (v === undefined && c) || v;

	F(
		environment,
		"globalThis",
		() => /** @type {boolean | undefined} */ (tp && tp.globalThis)
	);
	F(
		environment,
		"bigIntLiteral",
		() => /** @type {boolean | undefined} */ (tp && tp.bigIntLiteral)
	);
	F(
		environment,
		"const",
		() => tp && optimistic(/** @type {boolean | undefined} */ (tp.const))
	);
	F(
		environment,
		"arrowFunction",
		() =>
			tp && optimistic(/** @type {boolean | undefined} */ (tp.arrowFunction))
	);
	F(
		environment,
		"asyncFunction",
		() =>
			tp && optimistic(/** @type {boolean | undefined} */ (tp.asyncFunction))
	);
	F(
		environment,
		"forOf",
		() => tp && optimistic(/** @type {boolean | undefined} */ (tp.forOf))
	);
	F(
		environment,
		"destructuring",
		() =>
			tp && optimistic(/** @type {boolean | undefined} */ (tp.destructuring))
	);
	F(
		environment,
		"optionalChaining",
		() =>
			tp && optimistic(/** @type {boolean | undefined} */ (tp.optionalChaining))
	);
	F(
		environment,
		"nodePrefixForCoreModules",
		() =>
			tp &&
			optimistic(
				/** @type {boolean | undefined} */ (tp.nodePrefixForCoreModules)
			)
	);
	F(
		environment,
		"templateLiteral",
		() =>
			tp && optimistic(/** @type {boolean | undefined} */ (tp.templateLiteral))
	);
	F(environment, "dynamicImport", () =>
		conditionallyOptimistic(
			/** @type {boolean | undefined} */ (tp && tp.dynamicImport),
			output.module
		)
	);
	F(environment, "dynamicImportInWorker", () =>
		conditionallyOptimistic(
			/** @type {boolean | undefined} */ (tp && tp.dynamicImportInWorker),
			output.module
		)
	);
	F(environment, "module", () =>
		conditionallyOptimistic(
			/** @type {boolean | undefined} */ (tp && tp.module),
			output.module
		)
	);
	F(
		environment,
		"document",
		() => tp && optimistic(/** @type {boolean | undefined} */ (tp.document))
	);

	const { trustedTypes } = output;
	if (trustedTypes) {
		F(
			trustedTypes,
			"policyName",
			() =>
				/** @type {NonNullable<Output["uniqueName"]>} */
				(output.uniqueName).replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack"
		);
		D(trustedTypes, "onPolicyCreationFailure", "stop");
	}

	/**
	 * @param {function(EntryDescription): void} fn iterator
	 * @returns {void}
	 */
	const forEachEntry = fn => {
		for (const name of Object.keys(entry)) {
			fn(/** @type {{[k: string] : EntryDescription}} */ (entry)[name]);
		}
	};
	A(output, "enabledLibraryTypes", () => {
		/** @type {LibraryType[]} */
		const enabledLibraryTypes = [];
		if (output.library) {
			enabledLibraryTypes.push(output.library.type);
		}
		forEachEntry(desc => {
			if (desc.library) {
				enabledLibraryTypes.push(desc.library.type);
			}
		});
		return enabledLibraryTypes;
	});

	A(output, "enabledChunkLoadingTypes", () => {
		const enabledChunkLoadingTypes = new Set();
		if (output.chunkLoading) {
			enabledChunkLoadingTypes.add(output.chunkLoading);
		}
		if (output.workerChunkLoading) {
			enabledChunkLoadingTypes.add(output.workerChunkLoading);
		}
		forEachEntry(desc => {
			if (desc.chunkLoading) {
				enabledChunkLoadingTypes.add(desc.chunkLoading);
			}
		});
		return Array.from(enabledChunkLoadingTypes);
	});

	A(output, "enabledWasmLoadingTypes", () => {
		const enabledWasmLoadingTypes = new Set();
		if (output.wasmLoading) {
			enabledWasmLoadingTypes.add(output.wasmLoading);
		}
		if (output.workerWasmLoading) {
			enabledWasmLoadingTypes.add(output.workerWasmLoading);
		}
		forEachEntry(desc => {
			if (desc.wasmLoading) {
				enabledWasmLoadingTypes.add(desc.wasmLoading);
			}
		});
		return Array.from(enabledWasmLoadingTypes);
	});
};

/**
 * @param {ExternalsPresets} externalsPresets options
 * @param {object} options options
 * @param {TargetProperties | false} options.targetProperties target properties
 * @param {boolean} options.buildHttp buildHttp experiment enabled
 * @returns {void}
 */
const applyExternalsPresetsDefaults = (
	externalsPresets,
	{ targetProperties, buildHttp }
) => {
	D(
		externalsPresets,
		"web",
		/** @type {boolean | undefined} */
		(!buildHttp && targetProperties && targetProperties.web)
	);
	D(
		externalsPresets,
		"node",
		/** @type {boolean | undefined} */
		(targetProperties && targetProperties.node)
	);
	D(
		externalsPresets,
		"nwjs",
		/** @type {boolean | undefined} */
		(targetProperties && targetProperties.nwjs)
	);
	D(
		externalsPresets,
		"electron",
		/** @type {boolean | undefined} */
		(targetProperties && targetProperties.electron)
	);
	D(
		externalsPresets,
		"electronMain",
		/** @type {boolean | undefined} */
		(
			targetProperties &&
				targetProperties.electron &&
				targetProperties.electronMain
		)
	);
	D(
		externalsPresets,
		"electronPreload",
		/** @type {boolean | undefined} */
		(
			targetProperties &&
				targetProperties.electron &&
				targetProperties.electronPreload
		)
	);
	D(
		externalsPresets,
		"electronRenderer",
		/** @type {boolean | undefined} */
		(
			targetProperties &&
				targetProperties.electron &&
				targetProperties.electronRenderer
		)
	);
};

/**
 * @param {Loader} loader options
 * @param {object} options options
 * @param {TargetProperties | false} options.targetProperties target properties
 * @param {Environment} options.environment environment
 * @returns {void}
 */
const applyLoaderDefaults = (loader, { targetProperties, environment }) => {
	F(loader, "target", () => {
		if (targetProperties) {
			if (targetProperties.electron) {
				if (targetProperties.electronMain) return "electron-main";
				if (targetProperties.electronPreload) return "electron-preload";
				if (targetProperties.electronRenderer) return "electron-renderer";
				return "electron";
			}
			if (targetProperties.nwjs) return "nwjs";
			if (targetProperties.node) return "node";
			if (targetProperties.web) return "web";
		}
	});
	D(loader, "environment", environment);
};

/**
 * @param {WebpackNode} node options
 * @param {object} options options
 * @param {TargetProperties | false} options.targetProperties target properties
 * @param {boolean} options.futureDefaults is future defaults enabled
 * @param {boolean} options.outputModule is output type is module
 * @returns {void}
 */
const applyNodeDefaults = (
	node,
	{ futureDefaults, outputModule, targetProperties }
) => {
	if (node === false) return;

	F(node, "global", () => {
		if (targetProperties && targetProperties.global) return false;
		// TODO webpack 6 should always default to false
		return futureDefaults ? "warn" : true;
	});

	const handlerForNames = () => {
		if (targetProperties && targetProperties.node)
			return outputModule ? "node-module" : "eval-only";
		// TODO webpack 6 should always default to false
		return futureDefaults ? "warn-mock" : "mock";
	};

	F(node, "__filename", handlerForNames);
	F(node, "__dirname", handlerForNames);
};

/**
 * @param {Performance} performance options
 * @param {object} options options
 * @param {boolean} options.production is production
 * @returns {void}
 */
const applyPerformanceDefaults = (performance, { production }) => {
	if (performance === false) return;
	D(performance, "maxAssetSize", 250000);
	D(performance, "maxEntrypointSize", 250000);
	F(performance, "hints", () => (production ? "warning" : false));
};

/**
 * @param {Optimization} optimization options
 * @param {object} options options
 * @param {boolean} options.production is production
 * @param {boolean} options.development is development
 * @param {boolean} options.css is css enabled
 * @param {boolean} options.records using records
 * @returns {void}
 */
const applyOptimizationDefaults = (
	optimization,
	{ production, development, css, records }
) => {
	D(optimization, "removeAvailableModules", false);
	D(optimization, "removeEmptyChunks", true);
	D(optimization, "mergeDuplicateChunks", true);
	D(optimization, "flagIncludedChunks", production);
	F(optimization, "moduleIds", () => {
		if (production) return "deterministic";
		if (development) return "named";
		return "natural";
	});
	F(optimization, "chunkIds", () => {
		if (production) return "deterministic";
		if (development) return "named";
		return "natural";
	});
	F(optimization, "sideEffects", () => (production ? true : "flag"));
	D(optimization, "providedExports", true);
	D(optimization, "usedExports", production);
	D(optimization, "innerGraph", production);
	D(optimization, "mangleExports", production);
	D(optimization, "concatenateModules", production);
	D(optimization, "runtimeChunk", false);
	D(optimization, "emitOnErrors", !production);
	D(optimization, "checkWasmTypes", production);
	D(optimization, "mangleWasmImports", false);
	D(optimization, "portableRecords", records);
	D(optimization, "realContentHash", production);
	D(optimization, "minimize", production);
	A(optimization, "minimizer", () => [
		{
			apply: compiler => {
				// Lazy load the Terser plugin
				const TerserPlugin = require("terser-webpack-plugin");
				new TerserPlugin({
					terserOptions: {
						compress: {
							passes: 2
						}
					}
				}).apply(compiler);
			}
		}
	]);
	F(optimization, "nodeEnv", () => {
		if (production) return "production";
		if (development) return "development";
		return false;
	});
	const { splitChunks } = optimization;
	if (splitChunks) {
		A(splitChunks, "defaultSizeTypes", () =>
			css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"]
		);
		D(splitChunks, "hidePathInfo", production);
		D(splitChunks, "chunks", "async");
		D(splitChunks, "usedExports", optimization.usedExports === true);
		D(splitChunks, "minChunks", 1);
		F(splitChunks, "minSize", () => (production ? 20000 : 10000));
		F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined));
		F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000));
		F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity));
		F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity));
		D(splitChunks, "automaticNameDelimiter", "-");
		const cacheGroups =
			/** @type {NonNullable<OptimizationSplitChunksOptions["cacheGroups"]>} */
			(splitChunks.cacheGroups);
		F(cacheGroups, "default", () => ({
			idHint: "",
			reuseExistingChunk: true,
			minChunks: 2,
			priority: -20
		}));
		F(cacheGroups, "defaultVendors", () => ({
			idHint: "vendors",
			reuseExistingChunk: true,
			test: NODE_MODULES_REGEXP,
			priority: -10
		}));
	}
};

/**
 * @param {object} options options
 * @param {boolean} options.cache is cache enable
 * @param {string} options.context build context
 * @param {TargetProperties | false} options.targetProperties target properties
 * @param {Mode} options.mode mode
 * @param {boolean} options.css is css enabled
 * @returns {ResolveOptions} resolve options
 */
const getResolveDefaults = ({
	cache,
	context,
	targetProperties,
	mode,
	css
}) => {
	/** @type {string[]} */
	const conditions = ["webpack"];

	conditions.push(mode === "development" ? "development" : "production");

	if (targetProperties) {
		if (targetProperties.webworker) conditions.push("worker");
		if (targetProperties.node) conditions.push("node");
		if (targetProperties.web) conditions.push("browser");
		if (targetProperties.electron) conditions.push("electron");
		if (targetProperties.nwjs) conditions.push("nwjs");
	}

	const jsExtensions = [".js", ".json", ".wasm"];

	const tp = targetProperties;
	const browserField =
		tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer));

	/** @type {function(): ResolveOptions} */
	const cjsDeps = () => ({
		aliasFields: browserField ? ["browser"] : [],
		mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
		conditionNames: ["require", "module", "..."],
		extensions: [...jsExtensions]
	});
	/** @type {function(): ResolveOptions} */
	const esmDeps = () => ({
		aliasFields: browserField ? ["browser"] : [],
		mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
		conditionNames: ["import", "module", "..."],
		extensions: [...jsExtensions]
	});

	/** @type {ResolveOptions} */
	const resolveOptions = {
		cache,
		modules: ["node_modules"],
		conditionNames: conditions,
		mainFiles: ["index"],
		extensions: [],
		aliasFields: [],
		exportsFields: ["exports"],
		roots: [context],
		mainFields: ["main"],
		importsFields: ["imports"],
		byDependency: {
			wasm: esmDeps(),
			esm: esmDeps(),
			loaderImport: esmDeps(),
			url: {
				preferRelative: true
			},
			worker: {
				...esmDeps(),
				preferRelative: true
			},
			commonjs: cjsDeps(),
			amd: cjsDeps(),
			// for backward-compat: loadModule
			loader: cjsDeps(),
			// for backward-compat: Custom Dependency
			unknown: cjsDeps(),
			// for backward-compat: getResolve without dependencyType
			undefined: cjsDeps()
		}
	};

	if (css) {
		const styleConditions = [];

		styleConditions.push("webpack");
		styleConditions.push(mode === "development" ? "development" : "production");
		styleConditions.push("style");

		resolveOptions.byDependency["css-import"] = {
			// We avoid using any main files because we have to be consistent with CSS `@import`
			// and CSS `@import` does not handle `main` files in directories,
			// you should always specify the full URL for styles
			mainFiles: [],
			mainFields: ["style", "..."],
			conditionNames: styleConditions,
			extensions: [".css"],
			preferRelative: true
		};
	}

	return resolveOptions;
};

/**
 * @param {object} options options
 * @param {boolean} options.cache is cache enable
 * @returns {ResolveOptions} resolve options
 */
const getResolveLoaderDefaults = ({ cache }) => {
	/** @type {ResolveOptions} */
	const resolveOptions = {
		cache,
		conditionNames: ["loader", "require", "node"],
		exportsFields: ["exports"],
		mainFields: ["loader", "main"],
		extensions: [".js"],
		mainFiles: ["index"]
	};

	return resolveOptions;
};

/**
 * @param {InfrastructureLogging} infrastructureLogging options
 * @returns {void}
 */
const applyInfrastructureLoggingDefaults = infrastructureLogging => {
	F(infrastructureLogging, "stream", () => process.stderr);
	const tty =
		/** @type {any} */ (infrastructureLogging.stream).isTTY &&
		process.env.TERM !== "dumb";
	D(infrastructureLogging, "level", "info");
	D(infrastructureLogging, "debug", false);
	D(infrastructureLogging, "colors", tty);
	D(infrastructureLogging, "appendOnly", !tty);
};

exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults;
exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;