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