DelegatedModule.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { OriginalSource, RawSource } = require("webpack-sources");
  7. const Module = require("../Module");
  8. const {
  9. JAVASCRIPT_TYPE,
  10. JAVASCRIPT_TYPES
  11. } = require("../ModuleSourceTypeConstants");
  12. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants");
  13. const RuntimeGlobals = require("../RuntimeGlobals");
  14. const DelegatedSourceDependency = require("../dependencies/DelegatedSourceDependency");
  15. const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
  16. const makeSerializable = require("../util/makeSerializable");
  17. /**
  18. * @import {
  19. * DllReferencePluginOptions
  20. * } from "../../declarations/plugins/dll/DllReferencePlugin"
  21. */
  22. /** @import { ModuleId } from "../ChunkGraph" */
  23. /**
  24. * @import {
  25. * WebpackOptionsNormalizedWithDefaults as WebpackOptions
  26. * } from "../config/defaults"
  27. */
  28. /** @import Compilation from "../Compilation" */
  29. /** @import { UpdateHashContext } from "../Dependency" */
  30. /** @import { ManifestModuleData } from "./LibManifestPlugin" */
  31. /**
  32. * @import {
  33. * BuildCallback,
  34. * BuildMeta,
  35. * CodeGenerationContext,
  36. * CodeGenerationResult,
  37. * LibIdentOptions,
  38. * LibIdent,
  39. * NeedBuildCallback,
  40. * NeedBuildContext,
  41. * Sources,
  42. * RuntimeRequirements,
  43. * SourceTypes
  44. * } from "../Module"
  45. */
  46. /** @import RequestShortener from "../RequestShortener" */
  47. /** @import { ResolverWithOptions } from "../ResolverFactory" */
  48. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<[DelegatedModuleSourceRequest, DelegatedModuleData, DelegatedModuleType, string, string | Module]>} ObjectDeserializerContext */
  49. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<[DelegatedModuleSourceRequest, DelegatedModuleData, DelegatedModuleType, string, string | Module]>} ObjectSerializerContext */
  50. /** @import { Exports } from "../dependencies/StaticExportsDependency" */
  51. /** @import Hash from "../util/Hash" */
  52. /** @import { InputFileSystem } from "../util/fs" */
  53. /** @typedef {string} DelegatedModuleSourceRequest */
  54. /** @typedef {NonNullable<DllReferencePluginOptions["type"]>} DelegatedModuleType */
  55. /**
  56. * Defines the delegated module data type used by this module.
  57. * @typedef {object} DelegatedModuleData
  58. * @property {BuildMeta=} buildMeta build meta
  59. * @property {Exports=} exports exports
  60. * @property {ModuleId} id module id
  61. */
  62. const RUNTIME_REQUIREMENTS = new Set([
  63. RuntimeGlobals.module,
  64. RuntimeGlobals.require
  65. ]);
  66. class DelegatedModule extends Module {
  67. /**
  68. * Creates an instance of DelegatedModule.
  69. * @param {DelegatedModuleSourceRequest} sourceRequest source request
  70. * @param {DelegatedModuleData} data data
  71. * @param {DelegatedModuleType} type type
  72. * @param {string} userRequest user request
  73. * @param {string | Module} originalRequest original request
  74. */
  75. constructor(sourceRequest, data, type, userRequest, originalRequest) {
  76. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
  77. // Info from Factory
  78. /** @type {string} */
  79. this.sourceRequest = sourceRequest;
  80. /** @type {ModuleId} */
  81. this.request = data.id;
  82. /** @type {DelegatedModuleType} */
  83. this.delegationType = type;
  84. /** @type {string} */
  85. this.userRequest = userRequest;
  86. /** @type {string | Module} */
  87. this.originalRequest = originalRequest;
  88. /** @type {DelegatedModuleData} */
  89. this.delegateData = data;
  90. // Build info
  91. /** @type {undefined | DelegatedSourceDependency} */
  92. this.delegatedSourceDependency = undefined;
  93. }
  94. /**
  95. * Returns the source types this module can generate.
  96. * @returns {SourceTypes} types available (do not mutate)
  97. */
  98. getSourceTypes() {
  99. return JAVASCRIPT_TYPES;
  100. }
  101. /**
  102. * Gets the library identifier.
  103. * @param {LibIdentOptions} options options
  104. * @returns {LibIdent | null} an identifier for library inclusion
  105. */
  106. libIdent(options) {
  107. return typeof this.originalRequest === "string"
  108. ? this.originalRequest
  109. : this.originalRequest.libIdent(options);
  110. }
  111. /**
  112. * Returns the unique identifier used to reference this module.
  113. * @returns {string} a unique identifier of the module
  114. */
  115. identifier() {
  116. return `delegated ${JSON.stringify(this.request)} from ${
  117. this.sourceRequest
  118. }`;
  119. }
  120. /**
  121. * Returns a human-readable identifier for this module.
  122. * @param {RequestShortener} requestShortener the request shortener
  123. * @returns {string} a user readable identifier of the module
  124. */
  125. readableIdentifier(requestShortener) {
  126. return `delegated ${this.userRequest} from ${this.sourceRequest}`;
  127. }
  128. /**
  129. * Checks whether the module needs to be rebuilt for the current build state.
  130. * @param {NeedBuildContext} context context info
  131. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  132. * @returns {void}
  133. */
  134. needBuild(context, callback) {
  135. return callback(null, !this.buildMeta);
  136. }
  137. /**
  138. * Builds the module using the provided compilation context.
  139. * @param {WebpackOptions} options webpack options
  140. * @param {Compilation} compilation the compilation
  141. * @param {ResolverWithOptions} resolver the resolver
  142. * @param {InputFileSystem} fs the file system
  143. * @param {BuildCallback} callback callback function
  144. * @returns {void}
  145. */
  146. build(options, compilation, resolver, fs, callback) {
  147. const delegateData = /** @type {ManifestModuleData} */ (this.delegateData);
  148. this.buildMeta = { ...delegateData.buildMeta };
  149. this.buildInfo = {};
  150. this.dependencies.length = 0;
  151. this.delegatedSourceDependency = new DelegatedSourceDependency(
  152. this.sourceRequest
  153. );
  154. this.addDependency(this.delegatedSourceDependency);
  155. this.addDependency(
  156. new StaticExportsDependency(delegateData.exports || true, false)
  157. );
  158. callback();
  159. }
  160. /**
  161. * Generates code and runtime requirements for this module.
  162. * @param {CodeGenerationContext} context context for code generation
  163. * @returns {CodeGenerationResult} result
  164. */
  165. codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
  166. const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]);
  167. const sourceModule = moduleGraph.getModule(dep);
  168. /** @type {string} */
  169. let str;
  170. if (!sourceModule) {
  171. str = runtimeTemplate.throwMissingModuleErrorBlock({
  172. request: this.sourceRequest
  173. });
  174. } else {
  175. str = `module.exports = (${runtimeTemplate.moduleExports({
  176. module: sourceModule,
  177. chunkGraph,
  178. request: dep.request,
  179. /** @type {RuntimeRequirements} */
  180. runtimeRequirements: new Set()
  181. })})`;
  182. switch (this.delegationType) {
  183. case "require":
  184. str += `(${JSON.stringify(this.request)})`;
  185. break;
  186. case "object":
  187. str += `[${JSON.stringify(this.request)}]`;
  188. break;
  189. }
  190. str += ";";
  191. }
  192. /** @type {Sources} */
  193. const sources = new Map();
  194. if (this.useSourceMap || this.useSimpleSourceMap) {
  195. sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier()));
  196. } else {
  197. sources.set(JAVASCRIPT_TYPE, new RawSource(str));
  198. }
  199. return {
  200. sources,
  201. runtimeRequirements: RUNTIME_REQUIREMENTS
  202. };
  203. }
  204. /**
  205. * Returns the estimated size for the requested source type.
  206. * @param {string=} type the source type for which the size should be estimated
  207. * @returns {number} the estimated size of the module (must be non-zero)
  208. */
  209. size(type) {
  210. return 42;
  211. }
  212. /**
  213. * Updates the hash with the data contributed by this instance.
  214. * @param {Hash} hash the hash used to track dependencies
  215. * @param {UpdateHashContext} context context
  216. * @returns {void}
  217. */
  218. updateHash(hash, context) {
  219. hash.update(this.delegationType);
  220. hash.update(JSON.stringify(this.request));
  221. super.updateHash(hash, context);
  222. }
  223. /**
  224. * Serializes this instance into the provided serializer context.
  225. * @param {ObjectSerializerContext} context context
  226. */
  227. serialize(context) {
  228. // constructor
  229. context
  230. .write(this.sourceRequest)
  231. .write(this.delegateData)
  232. .write(this.delegationType)
  233. .write(this.userRequest)
  234. .write(this.originalRequest);
  235. super.serialize(context);
  236. }
  237. /**
  238. * Restores this instance from the provided deserializer context.
  239. * @param {ObjectDeserializerContext} context context\
  240. * @returns {DelegatedModule} DelegatedModule
  241. */
  242. static deserialize(context) {
  243. const sourceRequest = context.read();
  244. const c1 = context.rest;
  245. const delegateData = c1.read();
  246. const c2 = c1.rest;
  247. const delegationType = c2.read();
  248. const c3 = c2.rest;
  249. const userRequest = c3.read();
  250. const c4 = c3.rest;
  251. const originalRequest = c4.read();
  252. const obj = new DelegatedModule(
  253. sourceRequest,
  254. delegateData,
  255. delegationType,
  256. userRequest,
  257. originalRequest
  258. );
  259. obj.deserialize(c4.rest);
  260. return obj;
  261. }
  262. /**
  263. * Assuming this module is in the cache. Update the (cached) module with
  264. * the fresh module from the factory. Usually updates internal references
  265. * and properties.
  266. * @param {Module} module fresh module
  267. * @returns {void}
  268. */
  269. updateCacheModule(module) {
  270. super.updateCacheModule(module);
  271. const m = /** @type {DelegatedModule} */ (module);
  272. this.delegationType = m.delegationType;
  273. this.userRequest = m.userRequest;
  274. this.originalRequest = m.originalRequest;
  275. this.delegateData = m.delegateData;
  276. }
  277. /**
  278. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  279. */
  280. cleanupForCache() {
  281. super.cleanupForCache();
  282. this.delegateData =
  283. /** @type {EXPECTED_ANY} */
  284. (undefined);
  285. }
  286. }
  287. makeSerializable(DelegatedModule, "webpack/lib/dll/DelegatedModule");
  288. module.exports = DelegatedModule;