ContainerEntryModule.js 8.8 KB

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