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

"use strict";

const util = require("util");

/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */
/** @typedef {import("../../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */
/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */
/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
/** @typedef {import("../../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptionsNormalized */
/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */
/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */
/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
/** @typedef {import("../../declarations/WebpackOptions").Plugins} Plugins */
/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */
/** @typedef {import("../Entrypoint")} Entrypoint */

const handledDeprecatedNoEmitOnErrors = util.deprecate(
	/**
	 * @param {boolean} noEmitOnErrors no emit on errors
	 * @param {boolean | undefined} emitOnErrors emit on errors
	 * @returns {boolean} emit on errors
	 */
	(noEmitOnErrors, emitOnErrors) => {
		if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) {
			throw new Error(
				"Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config."
			);
		}
		return !noEmitOnErrors;
	},
	"optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors",
	"DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS"
);

/**
 * @template T
 * @template R
 * @param {T|undefined} value value or not
 * @param {function(T): R} fn nested handler
 * @returns {R} result value
 */
const nestedConfig = (value, fn) =>
	value === undefined ? fn(/** @type {T} */ ({})) : fn(value);

/**
 * @template T
 * @param {T|undefined} value value or not
 * @returns {T} result value
 */
const cloneObject = value => {
	return /** @type {T} */ ({ ...value });
};

/**
 * @template T
 * @template R
 * @param {T|undefined} value value or not
 * @param {function(T): R} fn nested handler
 * @returns {R|undefined} result value
 */
const optionalNestedConfig = (value, fn) =>
	value === undefined ? undefined : fn(value);

/**
 * @template T
 * @template R
 * @param {T[]|undefined} value array or not
 * @param {function(T[]): R[]} fn nested handler
 * @returns {R[]|undefined} cloned value
 */
const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([]));

/**
 * @template T
 * @template R
 * @param {T[]|undefined} value array or not
 * @param {function(T[]): R[]} fn nested handler
 * @returns {R[]|undefined} cloned value
 */
const optionalNestedArray = (value, fn) =>
	Array.isArray(value) ? fn(value) : undefined;

/**
 * @template T
 * @template R
 * @param {Record<string, T>|undefined} value value or not
 * @param {function(T): R} fn nested handler
 * @param {Record<string, function(T): R>=} customKeys custom nested handler for some keys
 * @returns {Record<string, R>} result value
 */
const keyedNestedConfig = (value, fn, customKeys) => {
	const result =
		value === undefined
			? {}
			: Object.keys(value).reduce(
					(obj, key) => (
						(obj[key] = (
							customKeys && key in customKeys ? customKeys[key] : fn
						)(value[key])),
						obj
					),
					/** @type {Record<string, R>} */ ({})
				);
	if (customKeys) {
		for (const key of Object.keys(customKeys)) {
			if (!(key in result)) {
				result[key] = customKeys[key](/** @type {T} */ ({}));
			}
		}
	}
	return result;
};

/**
 * @param {WebpackOptions} config input config
 * @returns {WebpackOptionsNormalized} normalized options
 */
const getNormalizedWebpackOptions = config => {
	return {
		amd: config.amd,
		bail: config.bail,
		cache:
			/** @type {NonNullable<CacheOptions>} */
			(
				optionalNestedConfig(config.cache, cache => {
					if (cache === false) return false;
					if (cache === true) {
						return {
							type: "memory",
							maxGenerations: undefined
						};
					}
					switch (cache.type) {
						case "filesystem":
							return {
								type: "filesystem",
								allowCollectingMemory: cache.allowCollectingMemory,
								maxMemoryGenerations: cache.maxMemoryGenerations,
								maxAge: cache.maxAge,
								profile: cache.profile,
								buildDependencies: cloneObject(cache.buildDependencies),
								cacheDirectory: cache.cacheDirectory,
								cacheLocation: cache.cacheLocation,
								hashAlgorithm: cache.hashAlgorithm,
								compression: cache.compression,
								idleTimeout: cache.idleTimeout,
								idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore,
								idleTimeoutAfterLargeChanges:
									cache.idleTimeoutAfterLargeChanges,
								name: cache.name,
								store: cache.store,
								version: cache.version,
								readonly: cache.readonly
							};
						case undefined:
						case "memory":
							return {
								type: "memory",
								maxGenerations: cache.maxGenerations
							};
						default:
							// @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
							throw new Error(`Not implemented cache.type ${cache.type}`);
					}
				})
			),
		context: config.context,
		dependencies: config.dependencies,
		devServer: optionalNestedConfig(config.devServer, devServer => {
			if (devServer === false) return false;
			return { ...devServer };
		}),
		devtool: config.devtool,
		entry:
			config.entry === undefined
				? { main: {} }
				: typeof config.entry === "function"
					? (
							fn => () =>
								Promise.resolve().then(fn).then(getNormalizedEntryStatic)
						)(config.entry)
					: getNormalizedEntryStatic(config.entry),
		experiments: nestedConfig(config.experiments, experiments => ({
			...experiments,
			buildHttp: optionalNestedConfig(experiments.buildHttp, options =>
				Array.isArray(options) ? { allowedUris: options } : options
			),
			lazyCompilation: optionalNestedConfig(
				experiments.lazyCompilation,
				options => (options === true ? {} : options)
			)
		})),
		externals: /** @type {NonNullable<Externals>} */ (config.externals),
		externalsPresets: cloneObject(config.externalsPresets),
		externalsType: config.externalsType,
		ignoreWarnings: config.ignoreWarnings
			? config.ignoreWarnings.map(ignore => {
					if (typeof ignore === "function") return ignore;
					const i = ignore instanceof RegExp ? { message: ignore } : ignore;
					return (warning, { requestShortener }) => {
						if (!i.message && !i.module && !i.file) return false;
						if (i.message && !i.message.test(warning.message)) {
							return false;
						}
						if (
							i.module &&
							(!warning.module ||
								!i.module.test(
									warning.module.readableIdentifier(requestShortener)
								))
						) {
							return false;
						}
						if (i.file && (!warning.file || !i.file.test(warning.file))) {
							return false;
						}
						return true;
					};
				})
			: undefined,
		infrastructureLogging: cloneObject(config.infrastructureLogging),
		loader: cloneObject(config.loader),
		mode: config.mode,
		module:
			/** @type {ModuleOptionsNormalized} */
			(
				nestedConfig(config.module, module => ({
					noParse: module.noParse,
					unsafeCache: module.unsafeCache,
					parser: keyedNestedConfig(module.parser, cloneObject, {
						javascript: parserOptions => ({
							unknownContextRequest: module.unknownContextRequest,
							unknownContextRegExp: module.unknownContextRegExp,
							unknownContextRecursive: module.unknownContextRecursive,
							unknownContextCritical: module.unknownContextCritical,
							exprContextRequest: module.exprContextRequest,
							exprContextRegExp: module.exprContextRegExp,
							exprContextRecursive: module.exprContextRecursive,
							exprContextCritical: module.exprContextCritical,
							wrappedContextRegExp: module.wrappedContextRegExp,
							wrappedContextRecursive: module.wrappedContextRecursive,
							wrappedContextCritical: module.wrappedContextCritical,
							// TODO webpack 6 remove
							strictExportPresence: module.strictExportPresence,
							strictThisContextOnImports: module.strictThisContextOnImports,
							...parserOptions
						})
					}),
					generator: cloneObject(module.generator),
					defaultRules: optionalNestedArray(module.defaultRules, r => [...r]),
					rules: nestedArray(module.rules, r => [...r])
				}))
			),
		name: config.name,
		node: nestedConfig(
			config.node,
			node =>
				node && {
					...node
				}
		),
		optimization: nestedConfig(config.optimization, optimization => {
			return {
				...optimization,
				runtimeChunk: getNormalizedOptimizationRuntimeChunk(
					optimization.runtimeChunk
				),
				splitChunks: nestedConfig(
					optimization.splitChunks,
					splitChunks =>
						splitChunks && {
							...splitChunks,
							defaultSizeTypes: splitChunks.defaultSizeTypes
								? [...splitChunks.defaultSizeTypes]
								: ["..."],
							cacheGroups: cloneObject(splitChunks.cacheGroups)
						}
				),
				emitOnErrors:
					optimization.noEmitOnErrors !== undefined
						? handledDeprecatedNoEmitOnErrors(
								optimization.noEmitOnErrors,
								optimization.emitOnErrors
							)
						: optimization.emitOnErrors
			};
		}),
		output: nestedConfig(config.output, output => {
			const { library } = output;
			const libraryAsName = /** @type {LibraryName} */ (library);
			const libraryBase =
				typeof library === "object" &&
				library &&
				!Array.isArray(library) &&
				"type" in library
					? library
					: libraryAsName || output.libraryTarget
						? /** @type {LibraryOptions} */ ({
								name: libraryAsName
							})
						: undefined;
			/** @type {OutputNormalized} */
			const result = {
				assetModuleFilename: output.assetModuleFilename,
				asyncChunks: output.asyncChunks,
				charset: output.charset,
				chunkFilename: output.chunkFilename,
				chunkFormat: output.chunkFormat,
				chunkLoading: output.chunkLoading,
				chunkLoadingGlobal: output.chunkLoadingGlobal,
				chunkLoadTimeout: output.chunkLoadTimeout,
				cssFilename: output.cssFilename,
				cssChunkFilename: output.cssChunkFilename,
				cssHeadDataCompression: output.cssHeadDataCompression,
				clean: output.clean,
				compareBeforeEmit: output.compareBeforeEmit,
				crossOriginLoading: output.crossOriginLoading,
				devtoolFallbackModuleFilenameTemplate:
					output.devtoolFallbackModuleFilenameTemplate,
				devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate,
				devtoolNamespace: output.devtoolNamespace,
				environment: cloneObject(output.environment),
				enabledChunkLoadingTypes: output.enabledChunkLoadingTypes
					? [...output.enabledChunkLoadingTypes]
					: ["..."],
				enabledLibraryTypes: output.enabledLibraryTypes
					? [...output.enabledLibraryTypes]
					: ["..."],
				enabledWasmLoadingTypes: output.enabledWasmLoadingTypes
					? [...output.enabledWasmLoadingTypes]
					: ["..."],
				filename: output.filename,
				globalObject: output.globalObject,
				hashDigest: output.hashDigest,
				hashDigestLength: output.hashDigestLength,
				hashFunction: output.hashFunction,
				hashSalt: output.hashSalt,
				hotUpdateChunkFilename: output.hotUpdateChunkFilename,
				hotUpdateGlobal: output.hotUpdateGlobal,
				hotUpdateMainFilename: output.hotUpdateMainFilename,
				ignoreBrowserWarnings: output.ignoreBrowserWarnings,
				iife: output.iife,
				importFunctionName: output.importFunctionName,
				importMetaName: output.importMetaName,
				scriptType: output.scriptType,
				library: libraryBase && {
					type:
						output.libraryTarget !== undefined
							? output.libraryTarget
							: libraryBase.type,
					auxiliaryComment:
						output.auxiliaryComment !== undefined
							? output.auxiliaryComment
							: libraryBase.auxiliaryComment,
					amdContainer:
						output.amdContainer !== undefined
							? output.amdContainer
							: libraryBase.amdContainer,
					export:
						output.libraryExport !== undefined
							? output.libraryExport
							: libraryBase.export,
					name: libraryBase.name,
					umdNamedDefine:
						output.umdNamedDefine !== undefined
							? output.umdNamedDefine
							: libraryBase.umdNamedDefine
				},
				module: output.module,
				path: output.path,
				pathinfo: output.pathinfo,
				publicPath: output.publicPath,
				sourceMapFilename: output.sourceMapFilename,
				sourcePrefix: output.sourcePrefix,
				strictModuleErrorHandling: output.strictModuleErrorHandling,
				strictModuleExceptionHandling: output.strictModuleExceptionHandling,
				trustedTypes: optionalNestedConfig(
					output.trustedTypes,
					trustedTypes => {
						if (trustedTypes === true) return {};
						if (typeof trustedTypes === "string")
							return { policyName: trustedTypes };
						return { ...trustedTypes };
					}
				),
				uniqueName: output.uniqueName,
				wasmLoading: output.wasmLoading,
				webassemblyModuleFilename: output.webassemblyModuleFilename,
				workerPublicPath: output.workerPublicPath,
				workerChunkLoading: output.workerChunkLoading,
				workerWasmLoading: output.workerWasmLoading
			};
			return result;
		}),
		parallelism: config.parallelism,
		performance: optionalNestedConfig(config.performance, performance => {
			if (performance === false) return false;
			return {
				...performance
			};
		}),
		plugins: /** @type {Plugins} */ (nestedArray(config.plugins, p => [...p])),
		profile: config.profile,
		recordsInputPath:
			config.recordsInputPath !== undefined
				? config.recordsInputPath
				: config.recordsPath,
		recordsOutputPath:
			config.recordsOutputPath !== undefined
				? config.recordsOutputPath
				: config.recordsPath,
		resolve: nestedConfig(config.resolve, resolve => ({
			...resolve,
			byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
		})),
		resolveLoader: cloneObject(config.resolveLoader),
		snapshot: nestedConfig(config.snapshot, snapshot => ({
			resolveBuildDependencies: optionalNestedConfig(
				snapshot.resolveBuildDependencies,
				resolveBuildDependencies => ({
					timestamp: resolveBuildDependencies.timestamp,
					hash: resolveBuildDependencies.hash
				})
			),
			buildDependencies: optionalNestedConfig(
				snapshot.buildDependencies,
				buildDependencies => ({
					timestamp: buildDependencies.timestamp,
					hash: buildDependencies.hash
				})
			),
			resolve: optionalNestedConfig(snapshot.resolve, resolve => ({
				timestamp: resolve.timestamp,
				hash: resolve.hash
			})),
			module: optionalNestedConfig(snapshot.module, module => ({
				timestamp: module.timestamp,
				hash: module.hash
			})),
			immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]),
			managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]),
			unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, p => [...p])
		})),
		stats: nestedConfig(config.stats, stats => {
			if (stats === false) {
				return {
					preset: "none"
				};
			}
			if (stats === true) {
				return {
					preset: "normal"
				};
			}
			if (typeof stats === "string") {
				return {
					preset: stats
				};
			}
			return {
				...stats
			};
		}),
		target: config.target,
		watch: config.watch,
		watchOptions: cloneObject(config.watchOptions)
	};
};

/**
 * @param {EntryStatic} entry static entry options
 * @returns {EntryStaticNormalized} normalized static entry options
 */
const getNormalizedEntryStatic = entry => {
	if (typeof entry === "string") {
		return {
			main: {
				import: [entry]
			}
		};
	}
	if (Array.isArray(entry)) {
		return {
			main: {
				import: entry
			}
		};
	}
	/** @type {EntryStaticNormalized} */
	const result = {};
	for (const key of Object.keys(entry)) {
		const value = entry[key];
		if (typeof value === "string") {
			result[key] = {
				import: [value]
			};
		} else if (Array.isArray(value)) {
			result[key] = {
				import: value
			};
		} else {
			result[key] = {
				import:
					/** @type {EntryDescriptionNormalized["import"]} */
					(
						value.import &&
							(Array.isArray(value.import) ? value.import : [value.import])
					),
				filename: value.filename,
				layer: value.layer,
				runtime: value.runtime,
				baseUri: value.baseUri,
				publicPath: value.publicPath,
				chunkLoading: value.chunkLoading,
				asyncChunks: value.asyncChunks,
				wasmLoading: value.wasmLoading,
				dependOn:
					/** @type {EntryDescriptionNormalized["dependOn"]} */
					(
						value.dependOn &&
							(Array.isArray(value.dependOn)
								? value.dependOn
								: [value.dependOn])
					),
				library: value.library
			};
		}
	}
	return result;
};

/**
 * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
 * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
 */
const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
	if (runtimeChunk === undefined) return undefined;
	if (runtimeChunk === false) return false;
	if (runtimeChunk === "single") {
		return {
			name: () => "runtime"
		};
	}
	if (runtimeChunk === true || runtimeChunk === "multiple") {
		return {
			/**
			 * @param {Entrypoint} entrypoint entrypoint
			 * @returns {string} runtime chunk name
			 */
			name: entrypoint => `runtime~${entrypoint.name}`
		};
	}
	const { name } = runtimeChunk;
	return {
		name: typeof name === "function" ? name : () => name
	};
};

exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;


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

"use strict";

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

const getBrowserslistTargetHandler = memoize(() =>
	require("./browserslistTargetHandler")
);

/**
 * @param {string} context the context directory
 * @returns {string} default target
 */
const getDefaultTarget = context => {
	const browsers = getBrowserslistTargetHandler().load(null, context);
	return browsers ? "browserslist" : "web";
};

/**
 * @typedef {object} PlatformTargetProperties
 * @property {boolean | null} web web platform, importing of http(s) and std: is available
 * @property {boolean | null} browser browser platform, running in a normal web browser
 * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker
 * @property {boolean | null} node node platform, require of node built-in modules is available
 * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available
 * @property {boolean | null} electron electron platform, require of some electron built-in modules is available
 */

/**
 * @typedef {object} ElectronContextTargetProperties
 * @property {boolean | null} electronMain in main context
 * @property {boolean | null} electronPreload in preload context
 * @property {boolean | null} electronRenderer in renderer context with node integration
 */

/**
 * @typedef {object} ApiTargetProperties
 * @property {boolean | null} require has require function available
 * @property {boolean | null} nodeBuiltins has node.js built-in modules available
 * @property {boolean | null} nodePrefixForCoreModules node.js allows to use `node:` prefix for core modules
 * @property {boolean | null} document has document available (allows script tags)
 * @property {boolean | null} importScripts has importScripts available
 * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker
 * @property {boolean | null} fetchWasm has fetch function available for WebAssembly
 * @property {boolean | null} global has global variable available
 */

/**
 * @typedef {object} EcmaTargetProperties
 * @property {boolean | null} globalThis has globalThis variable available
 * @property {boolean | null} bigIntLiteral big int literal syntax is available
 * @property {boolean | null} const const and let variable declarations are available
 * @property {boolean | null} arrowFunction arrow functions are available
 * @property {boolean | null} forOf for of iteration is available
 * @property {boolean | null} destructuring destructuring is available
 * @property {boolean | null} dynamicImport async import() is available
 * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker
 * @property {boolean | null} module ESM syntax is available (when in module)
 * @property {boolean | null} optionalChaining optional chaining is available
 * @property {boolean | null} templateLiteral template literal is available
 * @property {boolean | null} asyncFunction async functions and await are available
 */

///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */

/**
 * @template T
 * @typedef {{ [P in keyof T]?: never }} Never<T>
 */

/**
 * @template A
 * @template B
 * @typedef {(A & Never<B>) | (Never<A> & B) | (A & B)} Mix<A, B>
 */

/** @typedef {Mix<Mix<PlatformTargetProperties, ElectronContextTargetProperties>, Mix<ApiTargetProperties, EcmaTargetProperties>>} TargetProperties */

/**
 * @param {string} major major version
 * @param {string | undefined} minor minor version
 * @returns {(vMajor: number, vMinor?: number) => boolean | undefined} check if version is greater or equal
 */
const versionDependent = (major, minor) => {
	if (!major) {
		return () => /** @type {undefined} */ (undefined);
	}
	/** @type {number} */
	const nMajor = +major;
	/** @type {number} */
	const nMinor = minor ? +minor : 0;
	return (vMajor, vMinor = 0) => {
		return nMajor > vMajor || (nMajor === vMajor && nMinor >= vMinor);
	};
};

/** @type {[string, string, RegExp, (...args: string[]) => Partial<TargetProperties>][]} */
const TARGETS = [
	[
		"browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env",
		"Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config",
		/^browserslist(?::(.+))?$/,
		(rest, context) => {
			const browserslistTargetHandler = getBrowserslistTargetHandler();
			const browsers = browserslistTargetHandler.load(
				rest ? rest.trim() : null,
				context
			);
			if (!browsers) {
				throw new Error(`No browserslist config found to handle the 'browserslist' target.
See https://github.com/browserslist/browserslist#queries for possible ways to provide a config.
The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions).
You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`);
			}

			return browserslistTargetHandler.resolve(browsers);
		}
	],
	[
		"web",
		"Web browser.",
		/^web$/,
		() => {
			return {
				web: true,
				browser: true,
				webworker: null,
				node: false,
				electron: false,
				nwjs: false,

				document: true,
				importScriptsInWorker: true,
				fetchWasm: true,
				nodeBuiltins: false,
				importScripts: false,
				require: false,
				global: false
			};
		}
	],
	[
		"webworker",
		"Web Worker, SharedWorker or Service Worker.",
		/^webworker$/,
		() => {
			return {
				web: true,
				browser: true,
				webworker: true,
				node: false,
				electron: false,
				nwjs: false,

				importScripts: true,
				importScriptsInWorker: true,
				fetchWasm: true,
				nodeBuiltins: false,
				require: false,
				document: false,
				global: false
			};
		}
	],
	[
		"[async-]node[X[.Y]]",
		"Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.",
		/^(async-)?node((\d+)(?:\.(\d+))?)?$/,
		(asyncFlag, _, major, minor) => {
			const v = versionDependent(major, minor);
			// see https://node.green/
			return {
				node: true,
				electron: false,
				nwjs: false,
				web: false,
				webworker: false,
				browser: false,

				require: !asyncFlag,
				nodeBuiltins: true,
				// v16.0.0, v14.18.0
				nodePrefixForCoreModules: +major < 15 ? v(14, 18) : v(16),
				global: true,
				document: false,
				fetchWasm: false,
				importScripts: false,
				importScriptsInWorker: false,

				globalThis: v(12),
				const: v(6),
				templateLiteral: v(4),
				optionalChaining: v(14),
				arrowFunction: v(6),
				asyncFunction: v(7, 6),
				forOf: v(5),
				destructuring: v(6),
				bigIntLiteral: v(10, 4),
				dynamicImport: v(12, 17),
				dynamicImportInWorker: major ? false : undefined,
				module: v(12, 17)
			};
		}
	],
	[
		"electron[X[.Y]]-main/preload/renderer",
		"Electron in version X.Y. Script is running in main, preload resp. renderer context.",
		/^electron((\d+)(?:\.(\d+))?)?-(main|preload|renderer)$/,
		(_, major, minor, context) => {
			const v = versionDependent(major, minor);
			// see https://node.green/ + https://github.com/electron/releases
			return {
				node: true,
				electron: true,
				web: context !== "main",
				webworker: false,
				browser: false,
				nwjs: false,

				electronMain: context === "main",
				electronPreload: context === "preload",
				electronRenderer: context === "renderer",

				global: true,
				nodeBuiltins: true,
				// 15.0.0	- Node.js	v16.5
				// 14.0.0 - Mode.js v14.17, but prefixes only since v14.18
				nodePrefixForCoreModules: v(15),

				require: true,
				document: context === "renderer",
				fetchWasm: context === "renderer",
				importScripts: false,
				importScriptsInWorker: true,

				globalThis: v(5),
				const: v(1, 1),
				templateLiteral: v(1, 1),
				optionalChaining: v(8),
				arrowFunction: v(1, 1),
				asyncFunction: v(1, 7),
				forOf: v(0, 36),
				destructuring: v(1, 1),
				bigIntLiteral: v(4),
				dynamicImport: v(11),
				dynamicImportInWorker: major ? false : undefined,
				module: v(11)
			};
		}
	],
	[
		"nwjs[X[.Y]] / node-webkit[X[.Y]]",
		"NW.js in version X.Y.",
		/^(?:nwjs|node-webkit)((\d+)(?:\.(\d+))?)?$/,
		(_, major, minor) => {
			const v = versionDependent(major, minor);
			// see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md
			return {
				node: true,
				web: true,
				nwjs: true,
				webworker: null,
				browser: false,
				electron: false,

				global: true,
				nodeBuiltins: true,
				document: false,
				importScriptsInWorker: false,
				fetchWasm: false,
				importScripts: false,
				require: false,

				globalThis: v(0, 43),
				const: v(0, 15),
				templateLiteral: v(0, 13),
				optionalChaining: v(0, 44),
				arrowFunction: v(0, 15),
				asyncFunction: v(0, 21),
				forOf: v(0, 13),
				destructuring: v(0, 15),
				bigIntLiteral: v(0, 32),
				dynamicImport: v(0, 43),
				dynamicImportInWorker: major ? false : undefined,
				module: v(0, 43)
			};
		}
	],
	[
		"esX",
		"EcmaScript in this version. Examples: es2020, es5.",
		/^es(\d+)$/,
		version => {
			let v = +version;
			if (v < 1000) v = v + 2009;
			return {
				const: v >= 2015,
				templateLiteral: v >= 2015,
				optionalChaining: v >= 2020,
				arrowFunction: v >= 2015,
				forOf: v >= 2015,
				destructuring: v >= 2015,
				module: v >= 2015,
				asyncFunction: v >= 2017,
				globalThis: v >= 2020,
				bigIntLiteral: v >= 2020,
				dynamicImport: v >= 2020,
				dynamicImportInWorker: v >= 2020
			};
		}
	]
];

/**
 * @param {string} target the target
 * @param {string} context the context directory
 * @returns {TargetProperties} target properties
 */
const getTargetProperties = (target, context) => {
	for (const [, , regExp, handler] of TARGETS) {
		const match = regExp.exec(target);
		if (match) {
			const [, ...args] = match;
			const result = handler(...args, context);
			if (result) return /** @type {TargetProperties} */ (result);
		}
	}
	throw new Error(
		`Unknown target '${target}'. The following targets are supported:\n${TARGETS.map(
			([name, description]) => `* ${name}: ${description}`
		).join("\n")}`
	);
};

/**
 * @param {TargetProperties[]} targetProperties array of target properties
 * @returns {TargetProperties} merged target properties
 */
const mergeTargetProperties = targetProperties => {
	/** @type {Set<keyof TargetProperties>} */
	const keys = new Set();
	for (const tp of targetProperties) {
		for (const key of Object.keys(tp)) {
			keys.add(/** @type {keyof TargetProperties} */ (key));
		}
	}
	/** @type {object} */
	const result = {};
	for (const key of keys) {
		let hasTrue = false;
		let hasFalse = false;
		for (const tp of targetProperties) {
			const value = tp[key];
			switch (value) {
				case true:
					hasTrue = true;
					break;
				case false:
					hasFalse = true;
					break;
			}
		}
		if (hasTrue || hasFalse)
			/** @type {TargetProperties} */
			(result)[key] = hasFalse && hasTrue ? null : hasTrue ? true : false;
	}
	return /** @type {TargetProperties} */ (result);
};

/**
 * @param {string[]} targets the targets
 * @param {string} context the context directory
 * @returns {TargetProperties} target properties
 */
const getTargetsProperties = (targets, context) => {
	return mergeTargetProperties(
		targets.map(t => getTargetProperties(t, context))
	);
};

exports.getDefaultTarget = getDefaultTarget;
exports.getTargetProperties = getTargetProperties;
exports.getTargetsProperties = getTargetsProperties;

license: mit


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/

"use strict";

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

/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */
/** @typedef {import("./ContainerEntryModule").ExposesList} ExposesList */

class ContainerEntryDependency extends Dependency {
	/**
	 * @param {string} name entry name
	 * @param {ExposesList} exposes list of exposed modules
	 * @param {string} shareScope name of the share scope
	 */
	constructor(name, exposes, shareScope) {
		super();
		this.name = name;
		this.exposes = exposes;
		this.shareScope = shareScope;
	}

	/**
	 * @returns {string | null} an identifier to merge equal requests
	 */
	getResourceIdentifier() {
		return `container-entry-${this.name}`;
	}

	get type() {
		return "container entry";
	}

	get category() {
		return "esm";
	}
}

makeSerializable(
	ContainerEntryDependency,
	"webpack/lib/container/ContainerEntryDependency"
);

module.exports = ContainerEntryDependency;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/

"use strict";

const { OriginalSource, RawSource } = require("webpack-sources");
const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
const Module = require("../Module");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
const makeSerializable = require("../util/makeSerializable");
const ContainerExposedDependency = require("./ContainerExposedDependency");

/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../ChunkGroup")} ChunkGroup */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../RequestShortener")} RequestShortener */
/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */

/**
 * @typedef {object} ExposeOptions
 * @property {string[]} import requests to exposed modules (last one is exported)
 * @property {string} name custom chunk name for the exposed module
 */

/** @typedef {[string, ExposeOptions][]} ExposesList */

const SOURCE_TYPES = new Set(["javascript"]);

class ContainerEntryModule extends Module {
	/**
	 * @param {string} name container entry name
	 * @param {ExposesList} exposes list of exposed modules
	 * @param {string} shareScope name of the share scope
	 */
	constructor(name, exposes, shareScope) {
		super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
		this._name = name;
		this._exposes = exposes;
		this._shareScope = shareScope;
	}

	/**
	 * @returns {SourceTypes} types available (do not mutate)
	 */
	getSourceTypes() {
		return SOURCE_TYPES;
	}

	/**
	 * @returns {string} a unique identifier of the module
	 */
	identifier() {
		return `container entry (${this._shareScope}) ${JSON.stringify(
			this._exposes
		)}`;
	}

	/**
	 * @param {RequestShortener} requestShortener the request shortener
	 * @returns {string} a user readable identifier of the module
	 */
	readableIdentifier(requestShortener) {
		return `container entry`;
	}

	/**
	 * @param {LibIdentOptions} options options
	 * @returns {string | null} an identifier for library inclusion
	 */
	libIdent(options) {
		return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${
			this._name
		}`;
	}

	/**
	 * @param {NeedBuildContext} context context info
	 * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
	 * @returns {void}
	 */
	needBuild(context, callback) {
		return callback(null, !this.buildMeta);
	}

	/**
	 * @param {WebpackOptions} options webpack options
	 * @param {Compilation} compilation the compilation
	 * @param {ResolverWithOptions} resolver the resolver
	 * @param {InputFileSystem} fs the file system
	 * @param {function(WebpackError=): void} callback callback function
	 * @returns {void}
	 */
	build(options, compilation, resolver, fs, callback) {
		this.buildMeta = {};
		this.buildInfo = {
			strict: true,
			topLevelDeclarations: new Set(["moduleMap", "get", "init"])
		};
		this.buildMeta.exportsType = "namespace";

		this.clearDependenciesAndBlocks();

		for (const [name, options] of this._exposes) {
			const block = new AsyncDependenciesBlock(
				{
					name: options.name
				},
				{ name },
				options.import[options.import.length - 1]
			);
			let idx = 0;
			for (const request of options.import) {
				const dep = new ContainerExposedDependency(name, request);
				dep.loc = {
					name,
					index: idx++
				};

				block.addDependency(dep);
			}
			this.addBlock(block);
		}
		this.addDependency(new StaticExportsDependency(["get", "init"], false));

		callback();
	}

	/**
	 * @param {CodeGenerationContext} context context for code generation
	 * @returns {CodeGenerationResult} result
	 */
	codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) {
		const sources = new Map();
		const runtimeRequirements = new Set([
			RuntimeGlobals.definePropertyGetters,
			RuntimeGlobals.hasOwnProperty,
			RuntimeGlobals.exports
		]);
		const getters = [];

		for (const block of this.blocks) {
			const { dependencies } = block;

			const modules = dependencies.map(dependency => {
				const dep = /** @type {ContainerExposedDependency} */ (dependency);
				return {
					name: dep.exposedName,
					module: moduleGraph.getModule(dep),
					request: dep.userRequest
				};
			});

			let str;

			if (modules.some(m => !m.module)) {
				str = runtimeTemplate.throwMissingModuleErrorBlock({
					request: modules.map(m => m.request).join(", ")
				});
			} else {
				str = `return ${runtimeTemplate.blockPromise({
					block,
					message: "",
					chunkGraph,
					runtimeRequirements
				})}.then(${runtimeTemplate.returningFunction(
					runtimeTemplate.returningFunction(
						`(${modules
							.map(({ module, request }) =>
								runtimeTemplate.moduleRaw({
									module,
									chunkGraph,
									request,
									weak: false,
									runtimeRequirements
								})
							)
							.join(", ")})`
					)
				)});`;
			}

			getters.push(
				`${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction(
					"",
					str
				)}`
			);
		}

		const source = Template.asString([
			`var moduleMap = {`,
			Template.indent(getters.join(",\n")),
			"};",
			`var get = ${runtimeTemplate.basicFunction("module, getScope", [
				`${RuntimeGlobals.currentRemoteGetScope} = getScope;`,
				// reusing the getScope variable to avoid creating a new var (and module is also used later)
				"getScope = (",
				Template.indent([
					`${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`,
					Template.indent([
						"? moduleMap[module]()",
						`: Promise.resolve().then(${runtimeTemplate.basicFunction(
							"",
							"throw new Error('Module \"' + module + '\" does not exist in container.');"
						)})`
					])
				]),
				");",
				`${RuntimeGlobals.currentRemoteGetScope} = undefined;`,
				"return getScope;"
			])};`,
			`var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [
				`if (!${RuntimeGlobals.shareScopeMap}) return;`,
				`var name = ${JSON.stringify(this._shareScope)}`,
				`var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`,
				`if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`,
				`${RuntimeGlobals.shareScopeMap}[name] = shareScope;`,
				`return ${RuntimeGlobals.initializeSharing}(name, initScope);`
			])};`,
			"",
			"// This exports getters to disallow modifications",
			`${RuntimeGlobals.definePropertyGetters}(exports, {`,
			Template.indent([
				`get: ${runtimeTemplate.returningFunction("get")},`,
				`init: ${runtimeTemplate.returningFunction("init")}`
			]),
			"});"
		]);

		sources.set(
			"javascript",
			this.useSourceMap || this.useSimpleSourceMap
				? new OriginalSource(source, "webpack/container-entry")
				: new RawSource(source)
		);

		return {
			sources,
			runtimeRequirements
		};
	}

	/**
	 * @param {string=} type the source type for which the size should be estimated
	 * @returns {number} the estimated size of the module (must be non-zero)
	 */
	size(type) {
		return 42;
	}

	/**
	 * @param {ObjectSerializerContext} context context
	 */
	serialize(context) {
		const { write } = context;
		write(this._name);
		write(this._exposes);
		write(this._shareScope);
		super.serialize(context);
	}

	/**
	 * @param {ObjectDeserializerContext} context context
	 * @returns {ContainerEntryModule} deserialized container entry module
	 */
	static deserialize(context) {
		const { read } = context;
		const obj = new ContainerEntryModule(read(), read(), read());
		obj.deserialize(context);
		return obj;
	}
}

makeSerializable(
	ContainerEntryModule,
	"webpack/lib/container/ContainerEntryModule"
);

module.exports = ContainerEntryModule;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/

"use strict";

const ModuleFactory = require("../ModuleFactory");
const ContainerEntryModule = require("./ContainerEntryModule");

/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */

module.exports = class ContainerEntryModuleFactory extends ModuleFactory {
	/**
	 * @param {ModuleFactoryCreateData} data data object
	 * @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
	 * @returns {void}
	 */
	create({ dependencies: [dependency] }, callback) {
		const dep = /** @type {ContainerEntryDependency} */ (dependency);
		callback(null, {
			module: new ContainerEntryModule(dep.name, dep.exposes, dep.shareScope)
		});
	}
};


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/

"use strict";

const ModuleDependency = require("../dependencies/ModuleDependency");
const makeSerializable = require("../util/makeSerializable");

/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */

class ContainerExposedDependency extends ModuleDependency {
	/**
	 * @param {string} exposedName public name
	 * @param {string} request request to module
	 */
	constructor(exposedName, request) {
		super(request);
		this.exposedName = exposedName;
	}

	get type() {
		return "container exposed";
	}

	get category() {
		return "esm";
	}

	/**
	 * @returns {string | null} an identifier to merge equal requests
	 */
	getResourceIdentifier() {
		return `exposed dependency ${this.exposedName}=${this.request}`;
	}

	/**
	 * @param {ObjectSerializerContext} context context
	 */
	serialize(context) {
		context.write(this.exposedName);
		super.serialize(context);
	}

	/**
	 * @param {ObjectDeserializerContext} context context
	 */
	deserialize(context) {
		this.exposedName = context.read();
		super.deserialize(context);
	}
}

makeSerializable(
	ContainerExposedDependency,
	"webpack/lib/container/ContainerExposedDependency"
);

module.exports = ContainerExposedDependency;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/

"use strict";

const createSchemaValidation = require("../util/create-schema-validation");
const ContainerEntryDependency = require("./ContainerEntryDependency");
const ContainerEntryModuleFactory = require("./ContainerEntryModuleFactory");
const ContainerExposedDependency = require("./ContainerExposedDependency");
const { parseOptions } = require("./options");

/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */
/** @typedef {import("./ContainerEntryModule").ExposesList} ExposesList */

const validate = createSchemaValidation(
	require("../../schemas/plugins/container/ContainerPlugin.check.js"),
	() => require("../../schemas/plugins/container/ContainerPlugin.json"),
	{
		name: "Container Plugin",
		baseDataPath: "options"
	}
);

const PLUGIN_NAME = "ContainerPlugin";

class ContainerPlugin {
	/**
	 * @param {ContainerPluginOptions} options options
	 */
	constructor(options) {
		validate(options);

		this._options = {
			name: options.name,
			shareScope: options.shareScope || "default",
			library: options.library || {
				type: "var",
				name: options.name
			},
			runtime: options.runtime,
			filename: options.filename || undefined,
			exposes: /** @type {ExposesList} */ (
				parseOptions(
					options.exposes,
					item => ({
						import: Array.isArray(item) ? item : [item],
						name: undefined
					}),
					item => ({
						import: Array.isArray(item.import) ? item.import : [item.import],
						name: item.name || undefined
					})
				)
			)
		};
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const { name, exposes, shareScope, filename, library, runtime } =
			this._options;

		if (!compiler.options.output.enabledLibraryTypes.includes(library.type)) {
			compiler.options.output.enabledLibraryTypes.push(library.type);
		}

		compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
			const dep = new ContainerEntryDependency(name, exposes, shareScope);
			dep.loc = { name };
			compilation.addEntry(
				compilation.options.context,
				dep,
				{
					name,
					filename,
					runtime,
					library
				},
				error => {
					if (error) return callback(error);
					callback();
				}
			);
		});

		compiler.hooks.thisCompilation.tap(
			PLUGIN_NAME,
			(compilation, { normalModuleFactory }) => {
				compilation.dependencyFactories.set(
					ContainerEntryDependency,
					new ContainerEntryModuleFactory()
				);

				compilation.dependencyFactories.set(
					ContainerExposedDependency,
					normalModuleFactory
				);
			}
		);
	}
}

module.exports = ContainerPlugin;


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

"use strict";

const ExternalsPlugin = require("../ExternalsPlugin");
const RuntimeGlobals = require("../RuntimeGlobals");
const createSchemaValidation = require("../util/create-schema-validation");
const FallbackDependency = require("./FallbackDependency");
const FallbackItemDependency = require("./FallbackItemDependency");
const FallbackModuleFactory = require("./FallbackModuleFactory");
const RemoteModule = require("./RemoteModule");
const RemoteRuntimeModule = require("./RemoteRuntimeModule");
const RemoteToExternalDependency = require("./RemoteToExternalDependency");
const { parseOptions } = require("./options");

/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").ContainerReferencePluginOptions} ContainerReferencePluginOptions */
/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").RemotesConfig} RemotesConfig */
/** @typedef {import("../Compiler")} Compiler */

const validate = createSchemaValidation(
	require("../../schemas/plugins/container/ContainerReferencePlugin.check.js"),
	() =>
		require("../../schemas/plugins/container/ContainerReferencePlugin.json"),
	{
		name: "Container Reference Plugin",
		baseDataPath: "options"
	}
);

const slashCode = "/".charCodeAt(0);

class ContainerReferencePlugin {
	/**
	 * @param {ContainerReferencePluginOptions} options options
	 */
	constructor(options) {
		validate(options);

		this._remoteType = options.remoteType;
		this._remotes = parseOptions(
			options.remotes,
			item => ({
				external: Array.isArray(item) ? item : [item],
				shareScope: options.shareScope || "default"
			}),
			item => ({
				external: Array.isArray(item.external)
					? item.external
					: [item.external],
				shareScope: item.shareScope || options.shareScope || "default"
			})
		);
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const { _remotes: remotes, _remoteType: remoteType } = this;

		/** @type {Record<string, string>} */
		const remoteExternals = {};
		for (const [key, config] of remotes) {
			let i = 0;
			for (const external of config.external) {
				if (external.startsWith("internal ")) continue;
				remoteExternals[
					`webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}`
				] = external;
				i++;
			}
		}

		new ExternalsPlugin(remoteType, remoteExternals).apply(compiler);

		compiler.hooks.compilation.tap(
			"ContainerReferencePlugin",
			(compilation, { normalModuleFactory }) => {
				compilation.dependencyFactories.set(
					RemoteToExternalDependency,
					normalModuleFactory
				);

				compilation.dependencyFactories.set(
					FallbackItemDependency,
					normalModuleFactory
				);

				compilation.dependencyFactories.set(
					FallbackDependency,
					new FallbackModuleFactory()
				);

				normalModuleFactory.hooks.factorize.tap(
					"ContainerReferencePlugin",
					data => {
						if (!data.request.includes("!")) {
							for (const [key, config] of remotes) {
								if (
									data.request.startsWith(`${key}`) &&
									(data.request.length === key.length ||
										data.request.charCodeAt(key.length) === slashCode)
								) {
									return new RemoteModule(
										data.request,
										config.external.map((external, i) =>
											external.startsWith("internal ")
												? external.slice(9)
												: `webpack/container/reference/${key}${
														i ? `/fallback-${i}` : ""
													}`
										),
										`.${data.request.slice(key.length)}`,
										config.shareScope
									);
								}
							}
						}
					}
				);

				compilation.hooks.runtimeRequirementInTree
					.for(RuntimeGlobals.ensureChunkHandlers)
					.tap("ContainerReferencePlugin", (chunk, set) => {
						set.add(RuntimeGlobals.module);
						set.add(RuntimeGlobals.moduleFactoriesAddOnly);
						set.add(RuntimeGlobals.hasOwnProperty);
						set.add(RuntimeGlobals.initializeSharing);
						set.add(RuntimeGlobals.shareScopeMap);
						compilation.addRuntimeModule(chunk, new RemoteRuntimeModule());
					});
			}
		);
	}
}

module.exports = ContainerReferencePlugin;


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

"use strict";

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

/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */

class FallbackDependency extends Dependency {
	/**
	 * @param {string[]} requests requests
	 */
	constructor(requests) {
		super();
		this.requests = requests;
	}

	/**
	 * @returns {string | null} an identifier to merge equal requests
	 */
	getResourceIdentifier() {
		return `fallback ${this.requests.join(" ")}`;
	}

	get type() {
		return "fallback";
	}

	get category() {
		return "esm";
	}

	/**
	 * @param {ObjectSerializerContext} context context
	 */
	serialize(context) {
		const { write } = context;
		write(this.requests);
		super.serialize(context);
	}

	/**
	 * @param {ObjectDeserializerContext} context context
	 * @returns {FallbackDependency} deserialize fallback dependency
	 */
	static deserialize(context) {
		const { read } = context;
		const obj = new FallbackDependency(read());
		obj.deserialize(context);
		return obj;
	}
}

makeSerializable(
	FallbackDependency,
	"webpack/lib/container/FallbackDependency"
);

module.exports = FallbackDependency;


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

"use strict";

const ModuleDependency = require("../dependencies/ModuleDependency");
const makeSerializable = require("../util/makeSerializable");

class FallbackItemDependency extends ModuleDependency {
	/**
	 * @param {string} request request
	 */
	constructor(request) {
		super(request);
	}

	get type() {
		return "fallback item";
	}

	get category() {
		return "esm";
	}
}

makeSerializable(
	FallbackItemDependency,
	"webpack/lib/container/FallbackItemDependency"
);

module.exports = FallbackItemDependency;


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

"use strict";

const { RawSource } = require("webpack-sources");
const Module = require("../Module");
const { WEBPACK_MODULE_TYPE_FALLBACK } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const makeSerializable = require("../util/makeSerializable");
const FallbackItemDependency = require("./FallbackItemDependency");

/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../ChunkGroup")} ChunkGroup */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../RequestShortener")} RequestShortener */
/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */

const TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);

class FallbackModule extends Module {
	/**
	 * @param {string[]} requests list of requests to choose one
	 */
	constructor(requests) {
		super(WEBPACK_MODULE_TYPE_FALLBACK);
		this.requests = requests;
		this._identifier = `fallback ${this.requests.join(" ")}`;
	}

	/**
	 * @returns {string} a unique identifier of the module
	 */
	identifier() {
		return this._identifier;
	}

	/**
	 * @param {RequestShortener} requestShortener the request shortener
	 * @returns {string} a user readable identifier of the module
	 */
	readableIdentifier(requestShortener) {
		return this._identifier;
	}

	/**
	 * @param {LibIdentOptions} options options
	 * @returns {string | null} an identifier for library inclusion
	 */
	libIdent(options) {
		return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${
			this.requests[0]
		}/and ${this.requests.length - 1} more`;
	}

	/**
	 * @param {Chunk} chunk the chunk which condition should be checked
	 * @param {Compilation} compilation the compilation
	 * @returns {boolean} true, if the chunk is ok for the module
	 */
	chunkCondition(chunk, { chunkGraph }) {
		return chunkGraph.getNumberOfEntryModules(chunk) > 0;
	}

	/**
	 * @param {NeedBuildContext} context context info
	 * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
	 * @returns {void}
	 */
	needBuild(context, callback) {
		callback(null, !this.buildInfo);
	}

	/**
	 * @param {WebpackOptions} options webpack options
	 * @param {Compilation} compilation the compilation
	 * @param {ResolverWithOptions} resolver the resolver
	 * @param {InputFileSystem} fs the file system
	 * @param {function(WebpackError=): void} callback callback function
	 * @returns {void}
	 */
	build(options, compilation, resolver, fs, callback) {
		this.buildMeta = {};
		this.buildInfo = {
			strict: true
		};

		this.clearDependenciesAndBlocks();
		for (const request of this.requests)
			this.addDependency(new FallbackItemDependency(request));

		callback();
	}

	/**
	 * @param {string=} type the source type for which the size should be estimated
	 * @returns {number} the estimated size of the module (must be non-zero)
	 */
	size(type) {
		return this.requests.length * 5 + 42;
	}

	/**
	 * @returns {SourceTypes} types available (do not mutate)
	 */
	getSourceTypes() {
		return TYPES;
	}

	/**
	 * @param {CodeGenerationContext} context context for code generation
	 * @returns {CodeGenerationResult} result
	 */
	codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
		const ids = this.dependencies.map(dep =>
			chunkGraph.getModuleId(/** @type {Module} */ (moduleGraph.getModule(dep)))
		);
		const code = Template.asString([
			`var ids = ${JSON.stringify(ids)};`,
			"var error, result, i = 0;",
			`var loop = ${runtimeTemplate.basicFunction("next", [
				"while(i < ids.length) {",
				Template.indent([
					`try { next = ${RuntimeGlobals.require}(ids[i++]); } catch(e) { return handleError(e); }`,
					"if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);"
				]),
				"}",
				"if(error) throw error;"
			])}`,
			`var handleResult = ${runtimeTemplate.basicFunction("result", [
				"if(result) return result;",
				"return loop();"
			])};`,
			`var handleError = ${runtimeTemplate.basicFunction("e", [
				"error = e;",
				"return loop();"
			])};`,
			"module.exports = loop();"
		]);
		const sources = new Map();
		sources.set("javascript", new RawSource(code));
		return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS };
	}

	/**
	 * @param {ObjectSerializerContext} context context
	 */
	serialize(context) {
		const { write } = context;
		write(this.requests);
		super.serialize(context);
	}

	/**
	 * @param {ObjectDeserializerContext} context context
	 * @returns {FallbackModule} deserialized fallback module
	 */
	static deserialize(context) {
		const { read } = context;
		const obj = new FallbackModule(read());
		obj.deserialize(context);
		return obj;
	}
}

makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule");

module.exports = FallbackModule;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/

"use strict";

const ModuleFactory = require("../ModuleFactory");
const FallbackModule = require("./FallbackModule");

/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./FallbackDependency")} FallbackDependency */

module.exports = class FallbackModuleFactory extends ModuleFactory {
	/**
	 * @param {ModuleFactoryCreateData} data data object
	 * @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
	 * @returns {void}
	 */
	create({ dependencies: [dependency] }, callback) {
		const dep = /** @type {FallbackDependency} */ (dependency);
		callback(null, {
			module: new FallbackModule(dep.requests)
		});
	}
};


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

"use strict";

const isValidExternalsType = require("../../schemas/plugins/container/ExternalsType.check.js");
const SharePlugin = require("../sharing/SharePlugin");
const createSchemaValidation = require("../util/create-schema-validation");
const ContainerPlugin = require("./ContainerPlugin");
const ContainerReferencePlugin = require("./ContainerReferencePlugin");

/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */
/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */
/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").Shared} Shared */
/** @typedef {import("../Compiler")} Compiler */

const validate = createSchemaValidation(
	require("../../schemas/plugins/container/ModuleFederationPlugin.check.js"),
	() => require("../../schemas/plugins/container/ModuleFederationPlugin.json"),
	{
		name: "Module Federation Plugin",
		baseDataPath: "options"
	}
);
class ModuleFederationPlugin {
	/**
	 * @param {ModuleFederationPluginOptions} options options
	 */
	constructor(options) {
		validate(options);

		this._options = options;
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const { _options: options } = this;
		const library = options.library || { type: "var", name: options.name };
		const remoteType =
			options.remoteType ||
			(options.library && isValidExternalsType(options.library.type)
				? /** @type {ExternalsType} */ (options.library.type)
				: "script");
		if (
			library &&
			!compiler.options.output.enabledLibraryTypes.includes(library.type)
		) {
			compiler.options.output.enabledLibraryTypes.push(library.type);
		}
		compiler.hooks.afterPlugins.tap("ModuleFederationPlugin", () => {
			if (
				options.exposes &&
				(Array.isArray(options.exposes)
					? options.exposes.length > 0
					: Object.keys(options.exposes).length > 0)
			) {
				new ContainerPlugin({
					name: options.name,
					library,
					filename: options.filename,
					runtime: options.runtime,
					shareScope: options.shareScope,
					exposes: options.exposes
				}).apply(compiler);
			}
			if (
				options.remotes &&
				(Array.isArray(options.remotes)
					? options.remotes.length > 0
					: Object.keys(options.remotes).length > 0)
			) {
				new ContainerReferencePlugin({
					remoteType,
					shareScope: options.shareScope,
					remotes: options.remotes
				}).apply(compiler);
			}
			if (options.shared) {
				new SharePlugin({
					shared: options.shared,
					shareScope: options.shareScope
				}).apply(compiler);
			}
		});
	}
}

module.exports = ModuleFederationPlugin;


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

"use strict";

const { RawSource } = require("webpack-sources");
const Module = require("../Module");
const { WEBPACK_MODULE_TYPE_REMOTE } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const makeSerializable = require("../util/makeSerializable");
const FallbackDependency = require("./FallbackDependency");
const RemoteToExternalDependency = require("./RemoteToExternalDependency");

/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../ChunkGroup")} ChunkGroup */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../RequestShortener")} RequestShortener */
/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */

const TYPES = new Set(["remote", "share-init"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);

class RemoteModule extends Module {
	/**
	 * @param {string} request request string
	 * @param {string[]} externalRequests list of external requests to containers
	 * @param {string} internalRequest name of exposed module in container
	 * @param {string} shareScope the used share scope name
	 */
	constructor(request, externalRequests, internalRequest, shareScope) {
		super(WEBPACK_MODULE_TYPE_REMOTE);
		this.request = request;
		this.externalRequests = externalRequests;
		this.internalRequest = internalRequest;
		this.shareScope = shareScope;
		this._identifier = `remote (${shareScope}) ${this.externalRequests.join(
			" "
		)} ${this.internalRequest}`;
	}

	/**
	 * @returns {string} a unique identifier of the module
	 */
	identifier() {
		return this._identifier;
	}

	/**
	 * @param {RequestShortener} requestShortener the request shortener
	 * @returns {string} a user readable identifier of the module
	 */
	readableIdentifier(requestShortener) {
		return `remote ${this.request}`;
	}

	/**
	 * @param {LibIdentOptions} options options
	 * @returns {string | null} an identifier for library inclusion
	 */
	libIdent(options) {
		return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${
			this.request
		}`;
	}

	/**
	 * @param {NeedBuildContext} context context info
	 * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
	 * @returns {void}
	 */
	needBuild(context, callback) {
		callback(null, !this.buildInfo);
	}

	/**
	 * @param {WebpackOptions} options webpack options
	 * @param {Compilation} compilation the compilation
	 * @param {ResolverWithOptions} resolver the resolver
	 * @param {InputFileSystem} fs the file system
	 * @param {function(WebpackError=): void} callback callback function
	 * @returns {void}
	 */
	build(options, compilation, resolver, fs, callback) {
		this.buildMeta = {};
		this.buildInfo = {
			strict: true
		};

		this.clearDependenciesAndBlocks();
		if (this.externalRequests.length === 1) {
			this.addDependency(
				new RemoteToExternalDependency(this.externalRequests[0])
			);
		} else {
			this.addDependency(new FallbackDependency(this.externalRequests));
		}

		callback();
	}

	/**
	 * @param {string=} type the source type for which the size should be estimated
	 * @returns {number} the estimated size of the module (must be non-zero)
	 */
	size(type) {
		return 6;
	}

	/**
	 * @returns {SourceTypes} types available (do not mutate)
	 */
	getSourceTypes() {
		return TYPES;
	}

	/**
	 * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
	 */
	nameForCondition() {
		return this.request;
	}

	/**
	 * @param {CodeGenerationContext} context context for code generation
	 * @returns {CodeGenerationResult} result
	 */
	codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
		const module = moduleGraph.getModule(this.dependencies[0]);
		const id = module && chunkGraph.getModuleId(module);
		const sources = new Map();
		sources.set("remote", new RawSource(""));
		const data = new Map();
		data.set("share-init", [
			{
				shareScope: this.shareScope,
				initStage: 20,
				init: id === undefined ? "" : `initExternal(${JSON.stringify(id)});`
			}
		]);
		return { sources, data, runtimeRequirements: RUNTIME_REQUIREMENTS };
	}

	/**
	 * @param {ObjectSerializerContext} context context
	 */
	serialize(context) {
		const { write } = context;
		write(this.request);
		write(this.externalRequests);
		write(this.internalRequest);
		write(this.shareScope);
		super.serialize(context);
	}

	/**
	 * @param {ObjectDeserializerContext} context context
	 * @returns {RemoteModule} deserialized module
	 */
	static deserialize(context) {
		const { read } = context;
		const obj = new RemoteModule(read(), read(), read(), read());
		obj.deserialize(context);
		return obj;
	}
}

makeSerializable(RemoteModule, "webpack/lib/container/RemoteModule");

module.exports = RemoteModule;


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

"use strict";

const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");

/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Chunk").ChunkId} ChunkId */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("./RemoteModule")} RemoteModule */

class RemoteRuntimeModule extends RuntimeModule {
	constructor() {
		super("remotes loading");
	}

	/**
	 * @returns {string | null} runtime code
	 */
	generate() {
		const compilation = /** @type {Compilation} */ (this.compilation);
		const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
		const { runtimeTemplate, moduleGraph } = compilation;
		/** @type {Record<ChunkId, (string | number)[]>} */
		const chunkToRemotesMapping = {};
		/** @type {Record<string | number, [string, string, string | number | null]>} */
		const idToExternalAndNameMapping = {};
		for (const chunk of /** @type {Chunk} */ (this.chunk).getAllAsyncChunks()) {
			const modules = chunkGraph.getChunkModulesIterableBySourceType(
				chunk,
				"remote"
			);
			if (!modules) continue;
			/** @type {(string | number)[]} */
			const remotes = (chunkToRemotesMapping[
				/** @type {ChunkId} */ (chunk.id)
			] = []);
			for (const m of modules) {
				const module = /** @type {RemoteModule} */ (m);
				const name = module.internalRequest;
				const id = chunkGraph.getModuleId(module);
				const shareScope = module.shareScope;
				const dep = module.dependencies[0];
				const externalModule = moduleGraph.getModule(dep);
				const externalModuleId =
					externalModule && chunkGraph.getModuleId(externalModule);
				remotes.push(id);
				idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId];
			}
		}
		return Template.asString([
			`var chunkMapping = ${JSON.stringify(
				chunkToRemotesMapping,
				null,
				"\t"
			)};`,
			`var idToExternalAndNameMapping = ${JSON.stringify(
				idToExternalAndNameMapping,
				null,
				"\t"
			)};`,
			`${
				RuntimeGlobals.ensureChunkHandlers
			}.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [
				`if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`,
				Template.indent([
					`chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [
						`var getScope = ${RuntimeGlobals.currentRemoteGetScope};`,
						"if(!getScope) getScope = [];",
						"var data = idToExternalAndNameMapping[id];",
						"if(getScope.indexOf(data) >= 0) return;",
						"getScope.push(data);",
						`if(data.p) return promises.push(data.p);`,
						`var onError = ${runtimeTemplate.basicFunction("error", [
							'if(!error) error = new Error("Container missing");',
							'if(typeof error.message === "string")',
							Template.indent(
								`error.message += '\\nwhile loading "' + data[1] + '" from ' + data[2];`
							),
							`${
								RuntimeGlobals.moduleFactories
							}[id] = ${runtimeTemplate.basicFunction("", ["throw error;"])}`,
							"data.p = 0;"
						])};`,
						`var handleFunction = ${runtimeTemplate.basicFunction(
							"fn, arg1, arg2, d, next, first",
							[
								"try {",
								Template.indent([
									"var promise = fn(arg1, arg2);",
									"if(promise && promise.then) {",
									Template.indent([
										`var p = promise.then(${runtimeTemplate.returningFunction(
											"next(result, d)",
											"result"
										)}, onError);`,
										`if(first) promises.push(data.p = p); else return p;`
									]),
									"} else {",
									Template.indent(["return next(promise, d, first);"]),
									"}"
								]),
								"} catch(error) {",
								Template.indent(["onError(error);"]),
								"}"
							]
						)}`,
						`var onExternal = ${runtimeTemplate.returningFunction(
							`external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`,
							"external, _, first"
						)};`,
						`var onInitialized = ${runtimeTemplate.returningFunction(
							`handleFunction(external.get, data[1], getScope, 0, onFactory, first)`,
							"_, external, first"
						)};`,
						`var onFactory = ${runtimeTemplate.basicFunction("factory", [
							"data.p = 1;",
							`${
								RuntimeGlobals.moduleFactories
							}[id] = ${runtimeTemplate.basicFunction("module", [
								"module.exports = factory();"
							])}`
						])};`,
						`handleFunction(${RuntimeGlobals.require}, data[2], 0, 0, onExternal, 1);`
					])});`
				]),
				"}"
			])}`
		]);
	}
}

module.exports = RemoteRuntimeModule;


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

"use strict";

const ModuleDependency = require("../dependencies/ModuleDependency");
const makeSerializable = require("../util/makeSerializable");

class RemoteToExternalDependency extends ModuleDependency {
	/**
	 * @param {string} request request
	 */
	constructor(request) {
		super(request);
	}

	get type() {
		return "remote to external";
	}

	get category() {
		return "esm";
	}
}

makeSerializable(
	RemoteToExternalDependency,
	"webpack/lib/container/RemoteToExternalDependency"
);

module.exports = RemoteToExternalDependency;


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

"use strict";

/** @template T @typedef {(string | Record<string, string | string[] | T>)[] | Record<string, string | string[] | T>} ContainerOptionsFormat */

/**
 * @template T
 * @template N
 * @param {ContainerOptionsFormat<T>} options options passed by the user
 * @param {function(string | string[], string) : N} normalizeSimple normalize a simple item
 * @param {function(T, string) : N} normalizeOptions normalize a complex item
 * @param {function(string, N): void} fn processing function
 * @returns {void}
 */
const process = (options, normalizeSimple, normalizeOptions, fn) => {
	const array = items => {
		for (const item of items) {
			if (typeof item === "string") {
				fn(item, normalizeSimple(item, item));
			} else if (item && typeof item === "object") {
				object(item);
			} else {
				throw new Error("Unexpected options format");
			}
		}
	};
	const object = obj => {
		for (const [key, value] of Object.entries(obj)) {
			if (typeof value === "string" || Array.isArray(value)) {
				fn(key, normalizeSimple(value, key));
			} else {
				fn(key, normalizeOptions(value, key));
			}
		}
	};
	if (!options) {
		return;
	} else if (Array.isArray(options)) {
		array(options);
	} else if (typeof options === "object") {
		object(options);
	} else {
		throw new Error("Unexpected options format");
	}
};

/**
 * @template T
 * @template R
 * @param {ContainerOptionsFormat<T>} options options passed by the user
 * @param {function(string | string[], string) : R} normalizeSimple normalize a simple item
 * @param {function(T, string) : R} normalizeOptions normalize a complex item
 * @returns {[string, R][]} parsed options
 */
const parseOptions = (options, normalizeSimple, normalizeOptions) => {
	/** @type {[string, R][]} */
	const items = [];
	process(options, normalizeSimple, normalizeOptions, (key, value) => {
		items.push([key, value]);
	});
	return items;
};

/**
 * @template T
 * @param {string} scope scope name
 * @param {ContainerOptionsFormat<T>} options options passed by the user
 * @returns {Record<string, string | string[] | T>} options to spread or pass
 */
const scope = (scope, options) => {
	/** @type {Record<string, string | string[] | T>} */
	const obj = {};
	process(
		options,
		item => /** @type {string | string[] | T} */ (item),
		item => /** @type {string | string[] | T} */ (item),
		(key, value) => {
			obj[
				key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}`
			] = value;
		}
	);
	return obj;
};

exports.parseOptions = parseOptions;
exports.scope = scope;


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

"use strict";

const { ReplaceSource, RawSource, ConcatSource } = require("webpack-sources");
const { UsageState } = require("../ExportsInfo");
const Generator = require("../Generator");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const { cssExportConvention } = require("../util/conventions");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */
/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorLocalIdentName} CssGeneratorLocalIdentName */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../DependencyTemplate").CssExportsData} CssExportsData */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/Hash")} Hash */

/**
 * @template T
 * @typedef {import("../InitFragment")<T>} InitFragment
 */

const TYPES = new Set(["javascript"]);

class CssExportsGenerator extends Generator {
	/**
	 * @param {CssGeneratorExportsConvention | undefined} convention the convention of the exports name
	 * @param {CssGeneratorLocalIdentName | undefined} localIdentName css export local ident name
	 * @param {boolean} esModule whether to use ES modules syntax
	 */
	constructor(convention, localIdentName, esModule) {
		super();
		/** @type {CssGeneratorExportsConvention | undefined} */
		this.convention = convention;
		/** @type {CssGeneratorLocalIdentName | undefined} */
		this.localIdentName = localIdentName;
		/** @type {boolean} */
		this.esModule = esModule;
	}

	/**
	 * @param {NormalModule} module module for which the bailout reason should be determined
	 * @param {ConcatenationBailoutReasonContext} context context
	 * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
	 */
	getConcatenationBailoutReason(module, context) {
		if (!this.esModule) {
			return "Module is not an ECMAScript module";
		}
		// TODO webpack 6: remove /\[moduleid\]/.test
		if (
			/\[id\]/.test(this.localIdentName) ||
			/\[moduleid\]/.test(this.localIdentName)
		) {
			return "The localIdentName includes moduleId ([id] or [moduleid])";
		}
		return undefined;
	}

	/**
	 * @param {NormalModule} module module for which the code should be generated
	 * @param {GenerateContext} generateContext context for generate
	 * @returns {Source} generated code
	 */
	generate(module, generateContext) {
		const source = new ReplaceSource(new RawSource(""));
		/** @type {InitFragment<TODO>[]} */
		const initFragments = [];
		/** @type {CssExportsData} */
		const cssExportsData = {
			esModule: this.esModule,
			exports: new Map()
		};

		generateContext.runtimeRequirements.add(RuntimeGlobals.module);

		let chunkInitFragments;
		const runtimeRequirements = new Set();

		/** @type {DependencyTemplateContext} */
		const templateContext = {
			runtimeTemplate: generateContext.runtimeTemplate,
			dependencyTemplates: generateContext.dependencyTemplates,
			moduleGraph: generateContext.moduleGraph,
			chunkGraph: generateContext.chunkGraph,
			module,
			runtime: generateContext.runtime,
			runtimeRequirements: runtimeRequirements,
			concatenationScope: generateContext.concatenationScope,
			codeGenerationResults: generateContext.codeGenerationResults,
			initFragments,
			cssExportsData,
			get chunkInitFragments() {
				if (!chunkInitFragments) {
					const data = generateContext.getData();
					chunkInitFragments = data.get("chunkInitFragments");
					if (!chunkInitFragments) {
						chunkInitFragments = [];
						data.set("chunkInitFragments", chunkInitFragments);
					}
				}

				return chunkInitFragments;
			}
		};

		/**
		 * @param {Dependency} dependency the dependency
		 */
		const handleDependency = dependency => {
			const constructor = /** @type {new (...args: any[]) => Dependency} */ (
				dependency.constructor
			);
			const template = generateContext.dependencyTemplates.get(constructor);
			if (!template) {
				throw new Error(
					"No template for dependency: " + dependency.constructor.name
				);
			}

			template.apply(dependency, source, templateContext);
		};
		module.dependencies.forEach(handleDependency);

		if (generateContext.concatenationScope) {
			const source = new ConcatSource();
			const usedIdentifiers = new Set();
			for (const [name, v] of cssExportsData.exports) {
				for (let k of cssExportConvention(name, this.convention)) {
					let identifier = Template.toIdentifier(k);
					let i = 0;
					while (usedIdentifiers.has(identifier)) {
						identifier = Template.toIdentifier(k + i);
					}
					usedIdentifiers.add(identifier);
					generateContext.concatenationScope.registerExport(k, identifier);
					source.add(
						`${
							generateContext.runtimeTemplate.supportsConst() ? "const" : "var"
						} ${identifier} = ${JSON.stringify(v)};\n`
					);
				}
			}
			return source;
		} else {
			const needNsObj =
				this.esModule &&
				generateContext.moduleGraph
					.getExportsInfo(module)
					.otherExportsInfo.getUsed(generateContext.runtime) !==
					UsageState.Unused;
			if (needNsObj) {
				generateContext.runtimeRequirements.add(
					RuntimeGlobals.makeNamespaceObject
				);
			}
			const newExports = [];
			for (let [k, v] of cssExportsData.exports) {
				for (let name of cssExportConvention(k, this.convention)) {
					newExports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
				}
			}
			return new RawSource(
				`${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
					module.moduleArgument
				}.exports = {\n${newExports.join(",\n")}\n}${needNsObj ? ")" : ""};`
			);
		}
	}

	/**
	 * @param {NormalModule} module fresh module
	 * @returns {Set<string>} available types (do not mutate)
	 */
	getTypes(module) {
		return TYPES;
	}

	/**
	 * @param {NormalModule} module the module
	 * @param {string=} type source type
	 * @returns {number} estimate size of the module
	 */
	getSize(module, type) {
		return 42;
	}

	/**
	 * @param {Hash} hash hash that will be modified
	 * @param {UpdateHashContext} updateHashContext context for updating hash
	 */
	updateHash(hash, { module }) {}
}

module.exports = CssExportsGenerator;


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

"use strict";

const { ReplaceSource } = require("webpack-sources");
const Generator = require("../Generator");
const InitFragment = require("../InitFragment");
const RuntimeGlobals = require("../RuntimeGlobals");
const { cssExportConvention } = require("../util/conventions");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */
/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorLocalIdentName} CssGeneratorLocalIdentName */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../DependencyTemplate").CssExportsData} CssExportsData */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/Hash")} Hash */

const TYPES = new Set(["css"]);

class CssGenerator extends Generator {
	/**
	 * @param {CssGeneratorExportsConvention | undefined} convention the convention of the exports name
	 * @param {CssGeneratorLocalIdentName | undefined} localIdentName css export local ident name
	 * @param {boolean} esModule whether to use ES modules syntax
	 */
	constructor(convention, localIdentName, esModule) {
		super();
		/** @type {CssGeneratorExportsConvention | undefined} */
		this.convention = convention;
		/** @type {CssGeneratorLocalIdentName | undefined} */
		this.localIdentName = localIdentName;
		/** @type {boolean} */
		this.esModule = esModule;
	}

	/**
	 * @param {NormalModule} module module for which the code should be generated
	 * @param {GenerateContext} generateContext context for generate
	 * @returns {Source} generated code
	 */
	generate(module, generateContext) {
		const originalSource = /** @type {Source} */ (module.originalSource());
		const source = new ReplaceSource(originalSource);
		/** @type {InitFragment[]} */
		const initFragments = [];
		/** @type {CssExportsData} */
		const cssExportsData = {
			esModule: this.esModule,
			exports: new Map()
		};

		generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);

		let chunkInitFragments;
		/** @type {DependencyTemplateContext} */
		const templateContext = {
			runtimeTemplate: generateContext.runtimeTemplate,
			dependencyTemplates: generateContext.dependencyTemplates,
			moduleGraph: generateContext.moduleGraph,
			chunkGraph: generateContext.chunkGraph,
			module,
			runtime: generateContext.runtime,
			runtimeRequirements: generateContext.runtimeRequirements,
			concatenationScope: generateContext.concatenationScope,
			codeGenerationResults: generateContext.codeGenerationResults,
			initFragments,
			cssExportsData,
			get chunkInitFragments() {
				if (!chunkInitFragments) {
					const data = generateContext.getData();
					chunkInitFragments = data.get("chunkInitFragments");
					if (!chunkInitFragments) {
						chunkInitFragments = [];
						data.set("chunkInitFragments", chunkInitFragments);
					}
				}

				return chunkInitFragments;
			}
		};

		/**
		 * @param {Dependency} dependency dependency
		 */
		const handleDependency = dependency => {
			const constructor = /** @type {new (...args: any[]) => Dependency} */ (
				dependency.constructor
			);
			const template = generateContext.dependencyTemplates.get(constructor);
			if (!template) {
				throw new Error(
					"No template for dependency: " + dependency.constructor.name
				);
			}

			template.apply(dependency, source, templateContext);
		};
		module.dependencies.forEach(handleDependency);
		if (module.presentationalDependencies !== undefined)
			module.presentationalDependencies.forEach(handleDependency);

		if (cssExportsData.exports.size > 0) {
			const newExports = new Map();
			for (let [name, v] of cssExportsData.exports) {
				for (let newName of cssExportConvention(name, this.convention)) {
					newExports.set(newName, v);
				}
			}
			cssExportsData.exports = newExports;
		}
		const data = generateContext.getData();
		data.set("css-exports", cssExportsData);

		return InitFragment.addToSource(source, initFragments, generateContext);
	}

	/**
	 * @param {NormalModule} module fresh module
	 * @returns {Set<string>} available types (do not mutate)
	 */
	getTypes(module) {
		return TYPES;
	}

	/**
	 * @param {NormalModule} module the module
	 * @param {string=} type source type
	 * @returns {number} estimate size of the module
	 */
	getSize(module, type) {
		const originalSource = module.originalSource();

		if (!originalSource) {
			return 0;
		}

		return originalSource.size();
	}

	/**
	 * @param {Hash} hash hash that will be modified
	 * @param {UpdateHashContext} updateHashContext context for updating hash
	 */
	updateHash(hash, { module }) {}
}

module.exports = CssGenerator;