ConsumeSharedModule.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const Module = require("../Module");
  9. const {
  10. CONSUME_SHARED_TYPES,
  11. JAVASCRIPT_TYPES
  12. } = require("../ModuleSourceTypeConstants");
  13. const {
  14. WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE
  15. } = require("../ModuleTypeConstants");
  16. const RuntimeGlobals = require("../RuntimeGlobals");
  17. const makeSerializable = require("../util/makeSerializable");
  18. const { rangeToString, stringifyHoley } = require("../util/semver");
  19. const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependency");
  20. /** @type {WeakMap<ModuleGraph, WeakMap<ConsumeSharedModule, Module | null>>} */
  21. const fallbackModuleCache = new WeakMap();
  22. /** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
  23. /** @typedef {import("../Compilation")} Compilation */
  24. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  25. /** @typedef {import("../Module").BuildCallback} BuildCallback */
  26. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  27. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  28. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  29. /** @typedef {import("../Module").LibIdent} LibIdent */
  30. /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
  31. /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
  32. /** @typedef {import("../Module").Sources} Sources */
  33. /** @typedef {import("../Module").SourceTypes} SourceTypes */
  34. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  35. /** @typedef {import("../Module").ExportsType} ExportsType */
  36. /** @typedef {import("../RequestShortener")} RequestShortener */
  37. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  38. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  39. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  40. /** @typedef {import("../util/Hash")} Hash */
  41. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  42. /** @typedef {import("../util/semver").SemVerRange} SemVerRange */
  43. /** @typedef {import("../Module").BasicSourceTypes} BasicSourceTypes */
  44. /**
  45. * @typedef {object} ConsumeOptions
  46. * @property {string=} import fallback request
  47. * @property {string=} importResolved resolved fallback request
  48. * @property {string} shareKey global share key
  49. * @property {string} shareScope share scope
  50. * @property {SemVerRange | false | undefined} requiredVersion version requirement
  51. * @property {string=} packageName package name to determine required version automatically
  52. * @property {boolean} strictVersion don't use shared version even if version isn't valid
  53. * @property {boolean} singleton use single global version
  54. * @property {boolean} eager include the fallback module in a sync way
  55. */
  56. class ConsumeSharedModule extends Module {
  57. /**
  58. * @param {string} context context
  59. * @param {ConsumeOptions} options consume options
  60. */
  61. constructor(context, options) {
  62. super(WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE, context);
  63. this.options = options;
  64. }
  65. /**
  66. * @returns {string} a unique identifier of the module
  67. */
  68. identifier() {
  69. const {
  70. shareKey,
  71. shareScope,
  72. importResolved,
  73. requiredVersion,
  74. strictVersion,
  75. singleton,
  76. eager
  77. } = this.options;
  78. return `${WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE}|${shareScope}|${shareKey}|${
  79. requiredVersion && rangeToString(requiredVersion)
  80. }|${strictVersion}|${importResolved}|${singleton}|${eager}`;
  81. }
  82. /**
  83. * @param {RequestShortener} requestShortener the request shortener
  84. * @returns {string} a user readable identifier of the module
  85. */
  86. readableIdentifier(requestShortener) {
  87. const {
  88. shareKey,
  89. shareScope,
  90. importResolved,
  91. requiredVersion,
  92. strictVersion,
  93. singleton,
  94. eager
  95. } = this.options;
  96. return `consume shared module (${shareScope}) ${shareKey}@${
  97. requiredVersion ? rangeToString(requiredVersion) : "*"
  98. }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${
  99. importResolved
  100. ? ` (fallback: ${requestShortener.shorten(importResolved)})`
  101. : ""
  102. }${eager ? " (eager)" : ""}`;
  103. }
  104. /**
  105. * @param {LibIdentOptions} options options
  106. * @returns {LibIdent | null} an identifier for library inclusion
  107. */
  108. libIdent(options) {
  109. const { shareKey, shareScope, import: request } = this.options;
  110. return `${
  111. this.layer ? `(${this.layer})/` : ""
  112. }webpack/sharing/consume/${shareScope}/${shareKey}${
  113. request ? `/${request}` : ""
  114. }`;
  115. }
  116. /**
  117. * @param {NeedBuildContext} context context info
  118. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  119. * @returns {void}
  120. */
  121. needBuild(context, callback) {
  122. callback(null, !this.buildInfo);
  123. }
  124. /**
  125. * @param {WebpackOptions} options webpack options
  126. * @param {Compilation} compilation the compilation
  127. * @param {ResolverWithOptions} resolver the resolver
  128. * @param {InputFileSystem} fs the file system
  129. * @param {BuildCallback} callback callback function
  130. * @returns {void}
  131. */
  132. build(options, compilation, resolver, fs, callback) {
  133. this.buildMeta = {};
  134. this.buildInfo = {};
  135. if (this.options.import) {
  136. const dep = new ConsumeSharedFallbackDependency(this.options.import);
  137. if (this.options.eager) {
  138. this.addDependency(dep);
  139. } else {
  140. const block = new AsyncDependenciesBlock({});
  141. block.addDependency(dep);
  142. this.addBlock(block);
  143. }
  144. }
  145. callback();
  146. }
  147. /**
  148. * @returns {SourceTypes} types available (do not mutate)
  149. */
  150. getSourceTypes() {
  151. return CONSUME_SHARED_TYPES;
  152. }
  153. /**
  154. * Basic source types are high-level categories like javascript, css, webassembly, etc.
  155. * We only have built-in knowledge about the javascript basic type here; other basic types may be
  156. * added or changed over time by generators and do not need to be handled or detected here.
  157. *
  158. * Some modules, e.g. RemoteModule, may return non-basic source types like "remote" and "share-init"
  159. * from getSourceTypes(), but their generated output is still JavaScript, i.e. their basic type is JS.
  160. * @returns {BasicSourceTypes} types available (do not mutate)
  161. */
  162. getSourceBasicTypes() {
  163. return JAVASCRIPT_TYPES;
  164. }
  165. /**
  166. * @param {ModuleGraph} moduleGraph the module graph
  167. * @returns {Module | null} fallback module
  168. */
  169. _getFallbackModule(moduleGraph) {
  170. let moduleCache = fallbackModuleCache.get(moduleGraph);
  171. if (!moduleCache) {
  172. moduleCache = new WeakMap();
  173. fallbackModuleCache.set(moduleGraph, moduleCache);
  174. }
  175. const cached = moduleCache.get(this);
  176. if (cached !== undefined) {
  177. return cached;
  178. }
  179. /** @type {undefined | null | Module} */
  180. let fallbackModule = null;
  181. if (this.options.import) {
  182. if (this.options.eager) {
  183. const dep = this.dependencies[0];
  184. if (dep) {
  185. fallbackModule = moduleGraph.getModule(dep);
  186. }
  187. } else {
  188. const block = this.blocks[0];
  189. if (block && block.dependencies.length > 0) {
  190. fallbackModule = moduleGraph.getModule(block.dependencies[0]);
  191. }
  192. }
  193. }
  194. moduleCache.set(this, fallbackModule);
  195. return fallbackModule;
  196. }
  197. /**
  198. * @param {ModuleGraph} moduleGraph the module graph
  199. * @param {boolean | undefined} strict the importing module is strict
  200. * @returns {ExportsType} export type
  201. * "namespace": Exports is already a namespace object. namespace = exports.
  202. * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }.
  203. * "default-only": Provide a namespace object with only default export. namespace = { default: exports }
  204. * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports }
  205. */
  206. getExportsType(moduleGraph, strict) {
  207. const fallbackModule = this._getFallbackModule(moduleGraph);
  208. if (!fallbackModule) return "dynamic";
  209. return fallbackModule.getExportsType(moduleGraph, strict);
  210. }
  211. /**
  212. * @param {string=} type the source type for which the size should be estimated
  213. * @returns {number} the estimated size of the module (must be non-zero)
  214. */
  215. size(type) {
  216. return 42;
  217. }
  218. /**
  219. * @param {Hash} hash the hash used to track dependencies
  220. * @param {UpdateHashContext} context context
  221. * @returns {void}
  222. */
  223. updateHash(hash, context) {
  224. hash.update(JSON.stringify(this.options));
  225. super.updateHash(hash, context);
  226. }
  227. /**
  228. * @param {CodeGenerationContext} context context for code generation
  229. * @returns {CodeGenerationResult} result
  230. */
  231. codeGeneration({ chunkGraph, runtimeTemplate }) {
  232. const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]);
  233. const {
  234. shareScope,
  235. shareKey,
  236. strictVersion,
  237. requiredVersion,
  238. import: request,
  239. singleton,
  240. eager
  241. } = this.options;
  242. /** @type {undefined | string} */
  243. let fallbackCode;
  244. if (request) {
  245. if (eager) {
  246. const dep = this.dependencies[0];
  247. fallbackCode = runtimeTemplate.syncModuleFactory({
  248. dependency: dep,
  249. chunkGraph,
  250. runtimeRequirements,
  251. request: this.options.import
  252. });
  253. } else {
  254. const block = this.blocks[0];
  255. fallbackCode = runtimeTemplate.asyncModuleFactory({
  256. block,
  257. chunkGraph,
  258. runtimeRequirements,
  259. request: this.options.import
  260. });
  261. }
  262. }
  263. const args = [
  264. JSON.stringify(shareScope),
  265. JSON.stringify(shareKey),
  266. JSON.stringify(eager)
  267. ];
  268. if (requiredVersion) {
  269. args.push(stringifyHoley(requiredVersion));
  270. }
  271. if (fallbackCode) {
  272. args.push(fallbackCode);
  273. }
  274. /** @type {string} */
  275. let fn;
  276. if (requiredVersion) {
  277. if (strictVersion) {
  278. fn = singleton ? "loadStrictSingletonVersion" : "loadStrictVersion";
  279. } else {
  280. fn = singleton ? "loadSingletonVersion" : "loadVersion";
  281. }
  282. } else {
  283. fn = singleton ? "loadSingleton" : "load";
  284. }
  285. const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`);
  286. /** @type {Sources} */
  287. const sources = new Map();
  288. sources.set("consume-shared", new RawSource(code));
  289. return {
  290. runtimeRequirements,
  291. sources
  292. };
  293. }
  294. /**
  295. * @param {ObjectSerializerContext} context context
  296. */
  297. serialize(context) {
  298. const { write } = context;
  299. write(this.options);
  300. super.serialize(context);
  301. }
  302. /**
  303. * @param {ObjectDeserializerContext} context context
  304. */
  305. deserialize(context) {
  306. const { read } = context;
  307. this.options = read();
  308. super.deserialize(context);
  309. }
  310. }
  311. makeSerializable(
  312. ConsumeSharedModule,
  313. "webpack/lib/sharing/ConsumeSharedModule"
  314. );
  315. module.exports = ConsumeSharedModule;