ContainerEntryModule.js 9.6 KB

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