ContainerEntryModule.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
  4. */
  5. "use strict";
  6. const { OriginalSource, RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const Module = require("../Module");
  9. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants");
  10. const RuntimeGlobals = require("../RuntimeGlobals");
  11. const Template = require("../Template");
  12. const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
  13. const makeSerializable = require("../util/makeSerializable");
  14. const ContainerExposedDependency = require("./ContainerExposedDependency");
  15. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  16. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  17. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  18. /** @typedef {import("../Compilation")} Compilation */
  19. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  20. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  21. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  22. /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
  23. /** @typedef {import("../RequestShortener")} RequestShortener */
  24. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  25. /** @typedef {import("../WebpackError")} WebpackError */
  26. /** @typedef {import("../util/Hash")} Hash */
  27. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  28. /** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */
  29. /**
  30. * @typedef {Object} ExposeOptions
  31. * @property {string[]} import requests to exposed modules (last one is exported)
  32. * @property {string} name custom chunk name for the exposed module
  33. */
  34. const SOURCE_TYPES = new Set(["javascript"]);
  35. class ContainerEntryModule extends Module {
  36. /**
  37. * @param {string} name container entry name
  38. * @param {[string, ExposeOptions][]} exposes list of exposed modules
  39. * @param {string} shareScope name of the share scope
  40. */
  41. constructor(name, exposes, shareScope) {
  42. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
  43. this._name = name;
  44. this._exposes = exposes;
  45. this._shareScope = shareScope;
  46. }
  47. /**
  48. * @returns {Set<string>} types available (do not mutate)
  49. */
  50. getSourceTypes() {
  51. return SOURCE_TYPES;
  52. }
  53. /**
  54. * @returns {string} a unique identifier of the module
  55. */
  56. identifier() {
  57. return `container entry (${this._shareScope}) ${JSON.stringify(
  58. this._exposes
  59. )}`;
  60. }
  61. /**
  62. * @param {RequestShortener} requestShortener the request shortener
  63. * @returns {string} a user readable identifier of the module
  64. */
  65. readableIdentifier(requestShortener) {
  66. return `container entry`;
  67. }
  68. /**
  69. * @param {LibIdentOptions} options options
  70. * @returns {string | null} an identifier for library inclusion
  71. */
  72. libIdent(options) {
  73. return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${
  74. this._name
  75. }`;
  76. }
  77. /**
  78. * @param {NeedBuildContext} context context info
  79. * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
  80. * @returns {void}
  81. */
  82. needBuild(context, callback) {
  83. return callback(null, !this.buildMeta);
  84. }
  85. /**
  86. * @param {WebpackOptions} options webpack options
  87. * @param {Compilation} compilation the compilation
  88. * @param {ResolverWithOptions} resolver the resolver
  89. * @param {InputFileSystem} fs the file system
  90. * @param {function(WebpackError=): void} callback callback function
  91. * @returns {void}
  92. */
  93. build(options, compilation, resolver, fs, callback) {
  94. this.buildMeta = {};
  95. this.buildInfo = {
  96. strict: true,
  97. topLevelDeclarations: new Set(["moduleMap", "get", "init"])
  98. };
  99. this.buildMeta.exportsType = "namespace";
  100. this.clearDependenciesAndBlocks();
  101. for (const [name, options] of this._exposes) {
  102. const block = new AsyncDependenciesBlock(
  103. {
  104. name: options.name
  105. },
  106. { name },
  107. options.import[options.import.length - 1]
  108. );
  109. let idx = 0;
  110. for (const request of options.import) {
  111. const dep = new ContainerExposedDependency(name, request);
  112. dep.loc = {
  113. name,
  114. index: idx++
  115. };
  116. block.addDependency(dep);
  117. }
  118. this.addBlock(block);
  119. }
  120. this.addDependency(new StaticExportsDependency(["get", "init"], false));
  121. callback();
  122. }
  123. /**
  124. * @param {CodeGenerationContext} context context for code generation
  125. * @returns {CodeGenerationResult} result
  126. */
  127. codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) {
  128. const sources = new Map();
  129. const runtimeRequirements = new Set([
  130. RuntimeGlobals.definePropertyGetters,
  131. RuntimeGlobals.hasOwnProperty,
  132. RuntimeGlobals.exports
  133. ]);
  134. const getters = [];
  135. for (const block of this.blocks) {
  136. const { dependencies } = block;
  137. const modules = dependencies.map(dependency => {
  138. const dep = /** @type {ContainerExposedDependency} */ (dependency);
  139. return {
  140. name: dep.exposedName,
  141. module: moduleGraph.getModule(dep),
  142. request: dep.userRequest
  143. };
  144. });
  145. let str;
  146. if (modules.some(m => !m.module)) {
  147. str = runtimeTemplate.throwMissingModuleErrorBlock({
  148. request: modules.map(m => m.request).join(", ")
  149. });
  150. } else {
  151. str = `return ${runtimeTemplate.blockPromise({
  152. block,
  153. message: "",
  154. chunkGraph,
  155. runtimeRequirements
  156. })}.then(${runtimeTemplate.returningFunction(
  157. runtimeTemplate.returningFunction(
  158. `(${modules
  159. .map(({ module, request }) =>
  160. runtimeTemplate.moduleRaw({
  161. module,
  162. chunkGraph,
  163. request,
  164. weak: false,
  165. runtimeRequirements
  166. })
  167. )
  168. .join(", ")})`
  169. )
  170. )});`;
  171. }
  172. getters.push(
  173. `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction(
  174. "",
  175. str
  176. )}`
  177. );
  178. }
  179. const source = Template.asString([
  180. `var moduleMap = {`,
  181. Template.indent(getters.join(",\n")),
  182. "};",
  183. `var get = ${runtimeTemplate.basicFunction("module, getScope", [
  184. `${RuntimeGlobals.currentRemoteGetScope} = getScope;`,
  185. // reusing the getScope variable to avoid creating a new var (and module is also used later)
  186. "getScope = (",
  187. Template.indent([
  188. `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`,
  189. Template.indent([
  190. "? moduleMap[module]()",
  191. `: Promise.resolve().then(${runtimeTemplate.basicFunction(
  192. "",
  193. "throw new Error('Module \"' + module + '\" does not exist in container.');"
  194. )})`
  195. ])
  196. ]),
  197. ");",
  198. `${RuntimeGlobals.currentRemoteGetScope} = undefined;`,
  199. "return getScope;"
  200. ])};`,
  201. `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [
  202. `if (!${RuntimeGlobals.shareScopeMap}) return;`,
  203. `var name = ${JSON.stringify(this._shareScope)}`,
  204. `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`,
  205. `if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`,
  206. `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`,
  207. `return ${RuntimeGlobals.initializeSharing}(name, initScope);`
  208. ])};`,
  209. "",
  210. "// This exports getters to disallow modifications",
  211. `${RuntimeGlobals.definePropertyGetters}(exports, {`,
  212. Template.indent([
  213. `get: ${runtimeTemplate.returningFunction("get")},`,
  214. `init: ${runtimeTemplate.returningFunction("init")}`
  215. ]),
  216. "});"
  217. ]);
  218. sources.set(
  219. "javascript",
  220. this.useSourceMap || this.useSimpleSourceMap
  221. ? new OriginalSource(source, "webpack/container-entry")
  222. : new RawSource(source)
  223. );
  224. return {
  225. sources,
  226. runtimeRequirements
  227. };
  228. }
  229. /**
  230. * @param {string=} type the source type for which the size should be estimated
  231. * @returns {number} the estimated size of the module (must be non-zero)
  232. */
  233. size(type) {
  234. return 42;
  235. }
  236. serialize(context) {
  237. const { write } = context;
  238. write(this._name);
  239. write(this._exposes);
  240. write(this._shareScope);
  241. super.serialize(context);
  242. }
  243. static deserialize(context) {
  244. const { read } = context;
  245. const obj = new ContainerEntryModule(read(), read(), read());
  246. obj.deserialize(context);
  247. return obj;
  248. }
  249. }
  250. makeSerializable(
  251. ContainerEntryModule,
  252. "webpack/lib/container/ContainerEntryModule"
  253. );
  254. module.exports = ContainerEntryModule;