ContextModule.js 34.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { OriginalSource, RawSource } = require("webpack-sources");
const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
const { makeWebpackError } = require("./HookWebpackError");
const Module = require("./Module");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
const WebpackError = require("./WebpackError");
const {
	compareLocations,
	concatComparators,
	compareSelect,
	keepOriginalOrder,
	compareModulesById
} = require("./util/comparators");
const {
	contextify,
	parseResource,
	makePathsRelative
} = require("./util/identifier");
const makeSerializable = require("./util/makeSerializable");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */
/** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */

/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */

/**
 * @typedef {Object} ContextOptions
 * @property {ContextMode} mode
 * @property {boolean} recursive
 * @property {RegExp} regExp
 * @property {"strict"|boolean=} namespaceObject
 * @property {string=} addon
 * @property {string=} chunkName
 * @property {RegExp=} include
 * @property {RegExp=} exclude
 * @property {RawChunkGroupOptions=} groupOptions
 * @property {string=} typePrefix
 * @property {string=} category
 * @property {string[][]=} referencedExports exports referenced from modules (won't be mangled)
 */

/**
 * @typedef {Object} ContextModuleOptionsExtras
 * @property {false|string|string[]} resource
 * @property {string=} resourceQuery
 * @property {string=} resourceFragment
 * @property {TODO} resolveOptions
 */

/** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */

/**
 * @callback ResolveDependenciesCallback
 * @param {(Error | null)=} err
 * @param {ContextElementDependency[]=} dependencies
 */

/**
 * @callback ResolveDependencies
 * @param {InputFileSystem} fs
 * @param {ContextModuleOptions} options
 * @param {ResolveDependenciesCallback} callback
 */

const SNAPSHOT_OPTIONS = { timestamp: true };

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

class ContextModule extends Module {
	/**
	 * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
	 * @param {ContextModuleOptions} options options object
	 */
	constructor(resolveDependencies, options) {
		if (!options || typeof options.resource === "string") {
			const parsed = parseResource(
				options ? /** @type {string} */ (options.resource) : ""
			);
			const resource = parsed.path;
			const resourceQuery = (options && options.resourceQuery) || parsed.query;
			const resourceFragment =
				(options && options.resourceFragment) || parsed.fragment;

			super("javascript/dynamic", resource);
			/** @type {ContextModuleOptions} */
			this.options = {
				...options,
				resource,
				resourceQuery,
				resourceFragment
			};
		} else {
			super("javascript/dynamic");
			/** @type {ContextModuleOptions} */
			this.options = {
				...options,
				resource: options.resource,
				resourceQuery: options.resourceQuery || "",
				resourceFragment: options.resourceFragment || ""
			};
		}

		// Info from Factory
		this.resolveDependencies = resolveDependencies;
		if (options && options.resolveOptions !== undefined) {
			this.resolveOptions = options.resolveOptions;
		}

		if (options && typeof options.mode !== "string") {
			throw new Error("options.mode is a required option");
		}

		this._identifier = this._createIdentifier();
		this._forceBuild = true;
	}

	/**
	 * @returns {Set<string>} types available (do not mutate)
	 */
	getSourceTypes() {
		return TYPES;
	}

	/**
	 * Assuming this module is in the cache. Update the (cached) module with
	 * the fresh module from the factory. Usually updates internal references
	 * and properties.
	 * @param {Module} module fresh module
	 * @returns {void}
	 */
	updateCacheModule(module) {
		const m = /** @type {ContextModule} */ (module);
		this.resolveDependencies = m.resolveDependencies;
		this.options = m.options;
	}

	/**
	 * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
	 */
	cleanupForCache() {
		super.cleanupForCache();
		this.resolveDependencies = undefined;
	}

	_prettyRegExp(regexString, stripSlash = true) {
		const str = (regexString + "").replace(/!/g, "%21").replace(/\|/g, "%7C");
		return stripSlash ? str.substring(1, str.length - 1) : str;
	}

	_createIdentifier() {
		let identifier =
			this.context ||
			(typeof this.options.resource === "string" ||
			this.options.resource === false
				? `${this.options.resource}`
				: this.options.resource.join("|"));
		if (this.options.resourceQuery) {
			identifier += `|${this.options.resourceQuery}`;
		}
		if (this.options.resourceFragment) {
			identifier += `|${this.options.resourceFragment}`;
		}
		if (this.options.mode) {
			identifier += `|${this.options.mode}`;
		}
		if (!this.options.recursive) {
			identifier += "|nonrecursive";
		}
		if (this.options.addon) {
			identifier += `|${this.options.addon}`;
		}
		if (this.options.regExp) {
			identifier += `|${this._prettyRegExp(this.options.regExp, false)}`;
		}
		if (this.options.include) {
			identifier += `|include: ${this._prettyRegExp(
				this.options.include,
				false
			)}`;
		}
		if (this.options.exclude) {
			identifier += `|exclude: ${this._prettyRegExp(
				this.options.exclude,
				false
			)}`;
		}
		if (this.options.referencedExports) {
			identifier += `|referencedExports: ${JSON.stringify(
				this.options.referencedExports
			)}`;
		}
		if (this.options.chunkName) {
			identifier += `|chunkName: ${this.options.chunkName}`;
		}
		if (this.options.groupOptions) {
			identifier += `|groupOptions: ${JSON.stringify(
				this.options.groupOptions
			)}`;
		}
		if (this.options.namespaceObject === "strict") {
			identifier += "|strict namespace object";
		} else if (this.options.namespaceObject) {
			identifier += "|namespace object";
		}

		return identifier;
	}

	/**
	 * @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) {
		let identifier;
		if (this.context) {
			identifier = requestShortener.shorten(this.context) + "/";
		} else if (
			typeof this.options.resource === "string" ||
			this.options.resource === false
		) {
			identifier = requestShortener.shorten(`${this.options.resource}`) + "/";
		} else {
			identifier = this.options.resource
				.map(r => requestShortener.shorten(r) + "/")
				.join(" ");
		}
		if (this.options.resourceQuery) {
			identifier += ` ${this.options.resourceQuery}`;
		}
		if (this.options.mode) {
			identifier += ` ${this.options.mode}`;
		}
		if (!this.options.recursive) {
			identifier += " nonrecursive";
		}
		if (this.options.addon) {
			identifier += ` ${requestShortener.shorten(this.options.addon)}`;
		}
		if (this.options.regExp) {
			identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
		}
		if (this.options.include) {
			identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
		}
		if (this.options.exclude) {
			identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
		}
		if (this.options.referencedExports) {
			identifier += ` referencedExports: ${this.options.referencedExports
				.map(e => e.join("."))
				.join(", ")}`;
		}
		if (this.options.chunkName) {
			identifier += ` chunkName: ${this.options.chunkName}`;
		}
		if (this.options.groupOptions) {
			const groupOptions = this.options.groupOptions;
			for (const key of Object.keys(groupOptions)) {
				identifier += ` ${key}: ${groupOptions[key]}`;
			}
		}
		if (this.options.namespaceObject === "strict") {
			identifier += " strict namespace object";
		} else if (this.options.namespaceObject) {
			identifier += " namespace object";
		}

		return identifier;
	}

	/**
	 * @param {LibIdentOptions} options options
	 * @returns {string | null} an identifier for library inclusion
	 */
	libIdent(options) {
		let identifier;

		if (this.context) {
			identifier = contextify(
				options.context,
				this.context,
				options.associatedObjectForCache
			);
		} else if (typeof this.options.resource === "string") {
			identifier = contextify(
				options.context,
				this.options.resource,
				options.associatedObjectForCache
			);
		} else if (this.options.resource === false) {
			identifier = "false";
		} else {
			identifier = this.options.resource
				.map(res =>
					contextify(options.context, res, options.associatedObjectForCache)
				)
				.join(" ");
		}

		if (this.layer) identifier = `(${this.layer})/${identifier}`;
		if (this.options.mode) {
			identifier += ` ${this.options.mode}`;
		}
		if (this.options.recursive) {
			identifier += " recursive";
		}
		if (this.options.addon) {
			identifier += ` ${contextify(
				options.context,
				this.options.addon,
				options.associatedObjectForCache
			)}`;
		}
		if (this.options.regExp) {
			identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
		}
		if (this.options.include) {
			identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
		}
		if (this.options.exclude) {
			identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
		}
		if (this.options.referencedExports) {
			identifier += ` referencedExports: ${this.options.referencedExports
				.map(e => e.join("."))
				.join(", ")}`;
		}

		return identifier;
	}

	/**
	 * @returns {void}
	 */
	invalidateBuild() {
		this._forceBuild = true;
	}

	/**
	 * @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({ fileSystemInfo }, callback) {
		// build if enforced
		if (this._forceBuild) return callback(null, true);

		// always build when we have no snapshot and context
		if (!this.buildInfo.snapshot)
			return callback(null, Boolean(this.context || this.options.resource));

		fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => {
			callback(err, !valid);
		});
	}

	/**
	 * @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._forceBuild = false;
		/** @type {BuildMeta} */
		this.buildMeta = {
			exportsType: "default",
			defaultObject: "redirect-warn"
		};
		this.buildInfo = {
			snapshot: undefined
		};
		this.dependencies.length = 0;
		this.blocks.length = 0;
		const startTime = Date.now();
		this.resolveDependencies(fs, this.options, (err, dependencies) => {
			if (err) {
				return callback(
					makeWebpackError(err, "ContextModule.resolveDependencies")
				);
			}

			// abort if something failed
			// this will create an empty context
			if (!dependencies) {
				callback();
				return;
			}

			// enhance dependencies with meta info
			for (const dep of dependencies) {
				dep.loc = {
					name: dep.userRequest
				};
				dep.request = this.options.addon + dep.request;
			}
			dependencies.sort(
				concatComparators(
					compareSelect(a => a.loc, compareLocations),
					keepOriginalOrder(this.dependencies)
				)
			);

			if (this.options.mode === "sync" || this.options.mode === "eager") {
				// if we have an sync or eager context
				// just add all dependencies and continue
				this.dependencies = dependencies;
			} else if (this.options.mode === "lazy-once") {
				// for the lazy-once mode create a new async dependency block
				// and add that block to this context
				if (dependencies.length > 0) {
					const block = new AsyncDependenciesBlock({
						...this.options.groupOptions,
						name: this.options.chunkName
					});
					for (const dep of dependencies) {
						block.addDependency(dep);
					}
					this.addBlock(block);
				}
			} else if (
				this.options.mode === "weak" ||
				this.options.mode === "async-weak"
			) {
				// we mark all dependencies as weak
				for (const dep of dependencies) {
					dep.weak = true;
				}
				this.dependencies = dependencies;
			} else if (this.options.mode === "lazy") {
				// if we are lazy create a new async dependency block per dependency
				// and add all blocks to this context
				let index = 0;
				for (const dep of dependencies) {
					let chunkName = this.options.chunkName;
					if (chunkName) {
						if (!/\[(index|request)\]/.test(chunkName)) {
							chunkName += "[index]";
						}
						chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
						chunkName = chunkName.replace(
							/\[request\]/g,
							Template.toPath(dep.userRequest)
						);
					}
					const block = new AsyncDependenciesBlock(
						{
							...this.options.groupOptions,
							name: chunkName
						},
						dep.loc,
						dep.userRequest
					);
					block.addDependency(dep);
					this.addBlock(block);
				}
			} else {
				callback(
					new WebpackError(`Unsupported mode "${this.options.mode}" in context`)
				);
				return;
			}
			if (!this.context && !this.options.resource) return callback();

			compilation.fileSystemInfo.createSnapshot(
				startTime,
				null,
				this.context
					? [this.context]
					: typeof this.options.resource === "string"
					? [this.options.resource]
					: /** @type {string[]} */ (this.options.resource),
				null,
				SNAPSHOT_OPTIONS,
				(err, snapshot) => {
					if (err) return callback(err);
					this.buildInfo.snapshot = snapshot;
					callback();
				}
			);
		});
	}

	/**
	 * @param {LazySet<string>} fileDependencies set where file dependencies are added to
	 * @param {LazySet<string>} contextDependencies set where context dependencies are added to
	 * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
	 * @param {LazySet<string>} buildDependencies set where build dependencies are added to
	 */
	addCacheDependencies(
		fileDependencies,
		contextDependencies,
		missingDependencies,
		buildDependencies
	) {
		if (this.context) {
			contextDependencies.add(this.context);
		} else if (typeof this.options.resource === "string") {
			contextDependencies.add(this.options.resource);
		} else if (this.options.resource === false) {
			return;
		} else {
			for (const res of this.options.resource) contextDependencies.add(res);
		}
	}

	/**
	 * @param {ContextElementDependency[]} dependencies all dependencies
	 * @param {ChunkGraph} chunkGraph chunk graph
	 * @returns {TODO} TODO
	 */
	getUserRequestMap(dependencies, chunkGraph) {
		const moduleGraph = chunkGraph.moduleGraph;
		// if we filter first we get a new array
		// therefore we don't need to create a clone of dependencies explicitly
		// therefore the order of this is !important!
		const sortedDependencies = dependencies
			.filter(dependency => moduleGraph.getModule(dependency))
			.sort((a, b) => {
				if (a.userRequest === b.userRequest) {
					return 0;
				}
				return a.userRequest < b.userRequest ? -1 : 1;
			});
		const map = Object.create(null);
		for (const dep of sortedDependencies) {
			const module = moduleGraph.getModule(dep);
			map[dep.userRequest] = chunkGraph.getModuleId(module);
		}
		return map;
	}

	/**
	 * @param {ContextElementDependency[]} dependencies all dependencies
	 * @param {ChunkGraph} chunkGraph chunk graph
	 * @returns {TODO} TODO
	 */
	getFakeMap(dependencies, chunkGraph) {
		if (!this.options.namespaceObject) {
			return 9;
		}
		const moduleGraph = chunkGraph.moduleGraph;
		// bitfield
		let hasType = 0;
		const comparator = compareModulesById(chunkGraph);
		// if we filter first we get a new array
		// therefore we don't need to create a clone of dependencies explicitly
		// therefore the order of this is !important!
		const sortedModules = dependencies
			.map(dependency => moduleGraph.getModule(dependency))
			.filter(Boolean)
			.sort(comparator);
		const fakeMap = Object.create(null);
		for (const module of sortedModules) {
			const exportsType = module.getExportsType(
				moduleGraph,
				this.options.namespaceObject === "strict"
			);
			const id = chunkGraph.getModuleId(module);
			switch (exportsType) {
				case "namespace":
					fakeMap[id] = 9;
					hasType |= 1;
					break;
				case "dynamic":
					fakeMap[id] = 7;
					hasType |= 2;
					break;
				case "default-only":
					fakeMap[id] = 1;
					hasType |= 4;
					break;
				case "default-with-named":
					fakeMap[id] = 3;
					hasType |= 8;
					break;
				default:
					throw new Error(`Unexpected exports type ${exportsType}`);
			}
		}
		if (hasType === 1) {
			return 9;
		}
		if (hasType === 2) {
			return 7;
		}
		if (hasType === 4) {
			return 1;
		}
		if (hasType === 8) {
			return 3;
		}
		if (hasType === 0) {
			return 9;
		}
		return fakeMap;
	}

	getFakeMapInitStatement(fakeMap) {
		return typeof fakeMap === "object"
			? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
			: "";
	}

	getReturn(type, asyncModule) {
		if (type === 9) {
			return "__webpack_require__(id)";
		}
		return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${
			asyncModule ? " | 16" : ""
		})`;
	}

	getReturnModuleObjectSource(
		fakeMap,
		asyncModule,
		fakeMapDataExpression = "fakeMap[id]"
	) {
		if (typeof fakeMap === "number") {
			return `return ${this.getReturn(fakeMap, asyncModule)};`;
		}
		return `return ${
			RuntimeGlobals.createFakeNamespaceObject
		}(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`;
	}

	/**
	 * @param {TODO} dependencies TODO
	 * @param {TODO} id TODO
	 * @param {ChunkGraph} chunkGraph the chunk graph
	 * @returns {string} source code
	 */
	getSyncSource(dependencies, id, chunkGraph) {
		const map = this.getUserRequestMap(dependencies, chunkGraph);
		const fakeMap = this.getFakeMap(dependencies, chunkGraph);
		const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);

		return `var map = ${JSON.stringify(map, null, "\t")};
${this.getFakeMapInitStatement(fakeMap)}

function webpackContext(req) {
	var id = webpackContextResolve(req);
	${returnModuleObject}
}
function webpackContextResolve(req) {
	if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
		var e = new Error("Cannot find module '" + req + "'");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	}
	return map[req];
}
webpackContext.keys = function webpackContextKeys() {
	return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = ${JSON.stringify(id)};`;
	}

	/**
	 * @param {TODO} dependencies TODO
	 * @param {TODO} id TODO
	 * @param {ChunkGraph} chunkGraph the chunk graph
	 * @returns {string} source code
	 */
	getWeakSyncSource(dependencies, id, chunkGraph) {
		const map = this.getUserRequestMap(dependencies, chunkGraph);
		const fakeMap = this.getFakeMap(dependencies, chunkGraph);
		const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);

		return `var map = ${JSON.stringify(map, null, "\t")};
${this.getFakeMapInitStatement(fakeMap)}

function webpackContext(req) {
	var id = webpackContextResolve(req);
	if(!${RuntimeGlobals.moduleFactories}[id]) {
		var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	}
	${returnModuleObject}
}
function webpackContextResolve(req) {
	if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
		var e = new Error("Cannot find module '" + req + "'");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	}
	return map[req];
}
webpackContext.keys = function webpackContextKeys() {
	return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
webpackContext.id = ${JSON.stringify(id)};
module.exports = webpackContext;`;
	}

	/**
	 * @param {TODO} dependencies TODO
	 * @param {TODO} id TODO
	 * @param {Object} context context
	 * @param {ChunkGraph} context.chunkGraph the chunk graph
	 * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
	 * @returns {string} source code
	 */
	getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
		const arrow = runtimeTemplate.supportsArrowFunction();
		const map = this.getUserRequestMap(dependencies, chunkGraph);
		const fakeMap = this.getFakeMap(dependencies, chunkGraph);
		const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true);

		return `var map = ${JSON.stringify(map, null, "\t")};
${this.getFakeMapInitStatement(fakeMap)}

function webpackAsyncContext(req) {
	return webpackAsyncContextResolve(req).then(${
		arrow ? "id =>" : "function(id)"
	} {
		if(!${RuntimeGlobals.moduleFactories}[id]) {
			var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		}
		${returnModuleObject}
	});
}
function webpackAsyncContextResolve(req) {
	// Here Promise.resolve().then() is used instead of new Promise() to prevent
	// uncaught exception popping up in devtools
	return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
		if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		}
		return map[req];
	});
}
webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
			"Object.keys(map)"
		)};
webpackAsyncContext.resolve = webpackAsyncContextResolve;
webpackAsyncContext.id = ${JSON.stringify(id)};
module.exports = webpackAsyncContext;`;
	}

	/**
	 * @param {TODO} dependencies TODO
	 * @param {TODO} id TODO
	 * @param {Object} context context
	 * @param {ChunkGraph} context.chunkGraph the chunk graph
	 * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
	 * @returns {string} source code
	 */
	getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
		const arrow = runtimeTemplate.supportsArrowFunction();
		const map = this.getUserRequestMap(dependencies, chunkGraph);
		const fakeMap = this.getFakeMap(dependencies, chunkGraph);
		const thenFunction =
			fakeMap !== 9
				? `${arrow ? "id =>" : "function(id)"} {
		${this.getReturnModuleObjectSource(fakeMap)}
	}`
				: "__webpack_require__";
		return `var map = ${JSON.stringify(map, null, "\t")};
${this.getFakeMapInitStatement(fakeMap)}

function webpackAsyncContext(req) {
	return webpackAsyncContextResolve(req).then(${thenFunction});
}
function webpackAsyncContextResolve(req) {
	// Here Promise.resolve().then() is used instead of new Promise() to prevent
	// uncaught exception popping up in devtools
	return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
		if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		}
		return map[req];
	});
}
webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
			"Object.keys(map)"
		)};
webpackAsyncContext.resolve = webpackAsyncContextResolve;
webpackAsyncContext.id = ${JSON.stringify(id)};
module.exports = webpackAsyncContext;`;
	}

	/**
	 * @param {TODO} block TODO
	 * @param {TODO} dependencies TODO
	 * @param {TODO} id TODO
	 * @param {Object} options options object
	 * @param {RuntimeTemplate} options.runtimeTemplate the runtime template
	 * @param {ChunkGraph} options.chunkGraph the chunk graph
	 * @returns {string} source code
	 */
	getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) {
		const promise = runtimeTemplate.blockPromise({
			chunkGraph,
			block,
			message: "lazy-once context",
			runtimeRequirements: new Set()
		});
		const arrow = runtimeTemplate.supportsArrowFunction();
		const map = this.getUserRequestMap(dependencies, chunkGraph);
		const fakeMap = this.getFakeMap(dependencies, chunkGraph);
		const thenFunction =
			fakeMap !== 9
				? `${arrow ? "id =>" : "function(id)"} {
		${this.getReturnModuleObjectSource(fakeMap, true)};
	}`
				: "__webpack_require__";

		return `var map = ${JSON.stringify(map, null, "\t")};
${this.getFakeMapInitStatement(fakeMap)}

function webpackAsyncContext(req) {
	return webpackAsyncContextResolve(req).then(${thenFunction});
}
function webpackAsyncContextResolve(req) {
	return ${promise}.then(${arrow ? "() =>" : "function()"} {
		if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		}
		return map[req];
	});
}
webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
			"Object.keys(map)"
		)};
webpackAsyncContext.resolve = webpackAsyncContextResolve;
webpackAsyncContext.id = ${JSON.stringify(id)};
module.exports = webpackAsyncContext;`;
	}

	/**
	 * @param {TODO} blocks TODO
	 * @param {TODO} id TODO
	 * @param {Object} context context
	 * @param {ChunkGraph} context.chunkGraph the chunk graph
	 * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
	 * @returns {string} source code
	 */
	getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) {
		const moduleGraph = chunkGraph.moduleGraph;
		const arrow = runtimeTemplate.supportsArrowFunction();
		let hasMultipleOrNoChunks = false;
		let hasNoChunk = true;
		const fakeMap = this.getFakeMap(
			blocks.map(b => b.dependencies[0]),
			chunkGraph
		);
		const hasFakeMap = typeof fakeMap === "object";
		const items = blocks
			.map(block => {
				const dependency = block.dependencies[0];
				return {
					dependency: dependency,
					module: moduleGraph.getModule(dependency),
					block: block,
					userRequest: dependency.userRequest,
					chunks: undefined
				};
			})
			.filter(item => item.module);
		for (const item of items) {
			const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
			const chunks = (chunkGroup && chunkGroup.chunks) || [];
			item.chunks = chunks;
			if (chunks.length > 0) {
				hasNoChunk = false;
			}
			if (chunks.length !== 1) {
				hasMultipleOrNoChunks = true;
			}
		}
		const shortMode = hasNoChunk && !hasFakeMap;
		const sortedItems = items.sort((a, b) => {
			if (a.userRequest === b.userRequest) return 0;
			return a.userRequest < b.userRequest ? -1 : 1;
		});
		const map = Object.create(null);
		for (const item of sortedItems) {
			const moduleId = chunkGraph.getModuleId(item.module);
			if (shortMode) {
				map[item.userRequest] = moduleId;
			} else {
				const arrayStart = [moduleId];
				if (hasFakeMap) {
					arrayStart.push(fakeMap[moduleId]);
				}
				map[item.userRequest] = arrayStart.concat(
					item.chunks.map(chunk => chunk.id)
				);
			}
		}

		const chunksStartPosition = hasFakeMap ? 2 : 1;
		const requestPrefix = hasNoChunk
			? "Promise.resolve()"
			: hasMultipleOrNoChunks
			? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
			: `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
		const returnModuleObject = this.getReturnModuleObjectSource(
			fakeMap,
			true,
			shortMode ? "invalid" : "ids[1]"
		);

		const webpackAsyncContext =
			requestPrefix === "Promise.resolve()"
				? `
function webpackAsyncContext(req) {
	return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
		if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		}

		${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"}
		${returnModuleObject}
	});
}`
				: `function webpackAsyncContext(req) {
	if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
		return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		});
	}

	var ids = map[req], id = ids[0];
	return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} {
		${returnModuleObject}
	});
}`;

		return `var map = ${JSON.stringify(map, null, "\t")};
${webpackAsyncContext}
webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
			"Object.keys(map)"
		)};
webpackAsyncContext.id = ${JSON.stringify(id)};
module.exports = webpackAsyncContext;`;
	}

	getSourceForEmptyContext(id, runtimeTemplate) {
		return `function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")};
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = ${JSON.stringify(id)};
module.exports = webpackEmptyContext;`;
	}

	getSourceForEmptyAsyncContext(id, runtimeTemplate) {
		const arrow = runtimeTemplate.supportsArrowFunction();
		return `function webpackEmptyAsyncContext(req) {
	// Here Promise.resolve().then() is used instead of new Promise() to prevent
	// uncaught exception popping up in devtools
	return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
		var e = new Error("Cannot find module '" + req + "'");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	});
}
webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")};
webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
module.exports = webpackEmptyAsyncContext;`;
	}

	/**
	 * @param {string} asyncMode module mode
	 * @param {CodeGenerationContext} context context info
	 * @returns {string} the source code
	 */
	getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
		const id = chunkGraph.getModuleId(this);
		if (asyncMode === "lazy") {
			if (this.blocks && this.blocks.length > 0) {
				return this.getLazySource(this.blocks, id, {
					runtimeTemplate,
					chunkGraph
				});
			}
			return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
		}
		if (asyncMode === "eager") {
			if (this.dependencies && this.dependencies.length > 0) {
				return this.getEagerSource(this.dependencies, id, {
					chunkGraph,
					runtimeTemplate
				});
			}
			return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
		}
		if (asyncMode === "lazy-once") {
			const block = this.blocks[0];
			if (block) {
				return this.getLazyOnceSource(block, block.dependencies, id, {
					runtimeTemplate,
					chunkGraph
				});
			}
			return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
		}
		if (asyncMode === "async-weak") {
			if (this.dependencies && this.dependencies.length > 0) {
				return this.getAsyncWeakSource(this.dependencies, id, {
					chunkGraph,
					runtimeTemplate
				});
			}
			return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
		}
		if (asyncMode === "weak") {
			if (this.dependencies && this.dependencies.length > 0) {
				return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
			}
		}
		if (this.dependencies && this.dependencies.length > 0) {
			return this.getSyncSource(this.dependencies, id, chunkGraph);
		}
		return this.getSourceForEmptyContext(id, runtimeTemplate);
	}

	/**
	 * @param {string} sourceString source content
	 * @param {Compilation=} compilation the compilation
	 * @returns {Source} generated source
	 */
	getSource(sourceString, compilation) {
		if (this.useSourceMap || this.useSimpleSourceMap) {
			return new OriginalSource(
				sourceString,
				`webpack://${makePathsRelative(
					(compilation && compilation.compiler.context) || "",
					this.identifier(),
					compilation && compilation.compiler.root
				)}`
			);
		}
		return new RawSource(sourceString);
	}

	/**
	 * @param {CodeGenerationContext} context context for code generation
	 * @returns {CodeGenerationResult} result
	 */
	codeGeneration(context) {
		const { chunkGraph, compilation } = context;
		const sources = new Map();
		sources.set(
			"javascript",
			this.getSource(
				this.getSourceString(this.options.mode, context),
				compilation
			)
		);
		const set = new Set();
		const allDeps =
			this.dependencies.length > 0
				? /** @type {ContextElementDependency[]} */ (this.dependencies).slice()
				: [];
		for (const block of this.blocks)
			for (const dep of block.dependencies)
				allDeps.push(/** @type {ContextElementDependency} */ (dep));
		set.add(RuntimeGlobals.module);
		set.add(RuntimeGlobals.hasOwnProperty);
		if (allDeps.length > 0) {
			const asyncMode = this.options.mode;
			set.add(RuntimeGlobals.require);
			if (asyncMode === "weak") {
				set.add(RuntimeGlobals.moduleFactories);
			} else if (asyncMode === "async-weak") {
				set.add(RuntimeGlobals.moduleFactories);
				set.add(RuntimeGlobals.ensureChunk);
			} else if (asyncMode === "lazy" || asyncMode === "lazy-once") {
				set.add(RuntimeGlobals.ensureChunk);
			}
			if (this.getFakeMap(allDeps, chunkGraph) !== 9) {
				set.add(RuntimeGlobals.createFakeNamespaceObject);
			}
		}
		return {
			sources,
			runtimeRequirements: set
		};
	}

	/**
	 * @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) {
		// base penalty
		let size = 160;

		// if we don't have dependencies we stop here.
		for (const dependency of this.dependencies) {
			const element = /** @type {ContextElementDependency} */ (dependency);
			size += 5 + element.userRequest.length;
		}
		return size;
	}

	serialize(context) {
		const { write } = context;
		write(this._identifier);
		write(this._forceBuild);
		super.serialize(context);
	}

	deserialize(context) {
		const { read } = context;
		this._identifier = read();
		this._forceBuild = read();
		super.deserialize(context);
	}
}

makeSerializable(ContextModule, "webpack/lib/ContextModule");

module.exports = ContextModule;