ContainerEntryModule.js 8.9 KB

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