ContextModule.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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 AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
  8. const { makeWebpackError } = require("./HookWebpackError");
  9. const Module = require("./Module");
  10. const { JS_TYPES } = require("./ModuleSourceTypesConstants");
  11. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
  12. const RuntimeGlobals = require("./RuntimeGlobals");
  13. const Template = require("./Template");
  14. const WebpackError = require("./WebpackError");
  15. const {
  16. compareLocations,
  17. compareModulesById,
  18. compareSelect,
  19. concatComparators,
  20. keepOriginalOrder
  21. } = require("./util/comparators");
  22. const {
  23. contextify,
  24. makePathsRelative,
  25. parseResource
  26. } = require("./util/identifier");
  27. const makeSerializable = require("./util/makeSerializable");
  28. /** @typedef {import("webpack-sources").Source} Source */
  29. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  30. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  31. /** @typedef {import("./Chunk")} Chunk */
  32. /** @typedef {import("./Chunk").ChunkId} ChunkId */
  33. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  34. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  35. /** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
  36. /** @typedef {import("./Compilation")} Compilation */
  37. /** @typedef {import("./Dependency")} Dependency */
  38. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  39. /** @typedef {import("./Generator").SourceTypes} SourceTypes */
  40. /** @typedef {import("./Module").BuildCallback} BuildCallback */
  41. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  42. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  43. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  44. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  45. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  46. /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
  47. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  48. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  49. /** @typedef {import("./RequestShortener")} RequestShortener */
  50. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  51. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  52. /** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */
  53. /** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */
  54. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  55. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  56. /** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */
  57. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  58. /** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */
  59. /**
  60. * @typedef {object} ContextOptions
  61. * @property {ContextMode} mode
  62. * @property {boolean} recursive
  63. * @property {RegExp} regExp
  64. * @property {("strict" | boolean)=} namespaceObject
  65. * @property {string=} addon
  66. * @property {(string | null)=} chunkName
  67. * @property {(RegExp | null)=} include
  68. * @property {(RegExp | null)=} exclude
  69. * @property {RawChunkGroupOptions=} groupOptions
  70. * @property {string=} typePrefix
  71. * @property {string=} category
  72. * @property {(string[][] | null)=} referencedExports exports referenced from modules (won't be mangled)
  73. * @property {string=} layer
  74. * @property {ImportAttributes=} attributes
  75. */
  76. /**
  77. * @typedef {object} ContextModuleOptionsExtras
  78. * @property {false | string | string[]} resource
  79. * @property {string=} resourceQuery
  80. * @property {string=} resourceFragment
  81. * @property {ResolveOptions=} resolveOptions
  82. */
  83. /** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */
  84. /**
  85. * @callback ResolveDependenciesCallback
  86. * @param {Error | null} err
  87. * @param {ContextElementDependency[]=} dependencies
  88. */
  89. /**
  90. * @callback ResolveDependencies
  91. * @param {InputFileSystem} fs
  92. * @param {ContextModuleOptions} options
  93. * @param {ResolveDependenciesCallback} callback
  94. */
  95. /** @typedef {1 | 3 | 7 | 9} FakeMapType */
  96. /** @typedef {Record<ModuleId, FakeMapType>} FakeMap */
  97. const SNAPSHOT_OPTIONS = { timestamp: true };
  98. class ContextModule extends Module {
  99. /**
  100. * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
  101. * @param {ContextModuleOptions} options options object
  102. */
  103. constructor(resolveDependencies, options) {
  104. if (!options || typeof options.resource === "string") {
  105. const parsed = parseResource(
  106. options ? /** @type {string} */ (options.resource) : ""
  107. );
  108. const resource = parsed.path;
  109. const resourceQuery = (options && options.resourceQuery) || parsed.query;
  110. const resourceFragment =
  111. (options && options.resourceFragment) || parsed.fragment;
  112. const layer = options && options.layer;
  113. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, resource, layer);
  114. /** @type {ContextModuleOptions} */
  115. this.options = {
  116. ...options,
  117. resource,
  118. resourceQuery,
  119. resourceFragment
  120. };
  121. } else {
  122. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, undefined, options.layer);
  123. /** @type {ContextModuleOptions} */
  124. this.options = {
  125. ...options,
  126. resource: options.resource,
  127. resourceQuery: options.resourceQuery || "",
  128. resourceFragment: options.resourceFragment || ""
  129. };
  130. }
  131. // Info from Factory
  132. /** @type {ResolveDependencies | undefined} */
  133. this.resolveDependencies = resolveDependencies;
  134. if (options && options.resolveOptions !== undefined) {
  135. this.resolveOptions = options.resolveOptions;
  136. }
  137. if (options && typeof options.mode !== "string") {
  138. throw new Error("options.mode is a required option");
  139. }
  140. this._identifier = this._createIdentifier();
  141. this._forceBuild = true;
  142. }
  143. /**
  144. * @returns {SourceTypes} types available (do not mutate)
  145. */
  146. getSourceTypes() {
  147. return JS_TYPES;
  148. }
  149. /**
  150. * Assuming this module is in the cache. Update the (cached) module with
  151. * the fresh module from the factory. Usually updates internal references
  152. * and properties.
  153. * @param {Module} module fresh module
  154. * @returns {void}
  155. */
  156. updateCacheModule(module) {
  157. const m = /** @type {ContextModule} */ (module);
  158. this.resolveDependencies = m.resolveDependencies;
  159. this.options = m.options;
  160. }
  161. /**
  162. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  163. */
  164. cleanupForCache() {
  165. super.cleanupForCache();
  166. this.resolveDependencies = undefined;
  167. }
  168. /**
  169. * @private
  170. * @param {RegExp} regexString RegExp as a string
  171. * @param {boolean=} stripSlash do we need to strip a slsh
  172. * @returns {string} pretty RegExp
  173. */
  174. _prettyRegExp(regexString, stripSlash = true) {
  175. const str = stripSlash
  176. ? regexString.source + regexString.flags
  177. : `${regexString}`;
  178. return str.replace(/!/g, "%21").replace(/\|/g, "%7C");
  179. }
  180. _createIdentifier() {
  181. let identifier =
  182. this.context ||
  183. (typeof this.options.resource === "string" ||
  184. this.options.resource === false
  185. ? `${this.options.resource}`
  186. : this.options.resource.join("|"));
  187. if (this.options.resourceQuery) {
  188. identifier += `|${this.options.resourceQuery}`;
  189. }
  190. if (this.options.resourceFragment) {
  191. identifier += `|${this.options.resourceFragment}`;
  192. }
  193. if (this.options.mode) {
  194. identifier += `|${this.options.mode}`;
  195. }
  196. if (!this.options.recursive) {
  197. identifier += "|nonrecursive";
  198. }
  199. if (this.options.addon) {
  200. identifier += `|${this.options.addon}`;
  201. }
  202. if (this.options.regExp) {
  203. identifier += `|${this._prettyRegExp(this.options.regExp, false)}`;
  204. }
  205. if (this.options.include) {
  206. identifier += `|include: ${this._prettyRegExp(
  207. this.options.include,
  208. false
  209. )}`;
  210. }
  211. if (this.options.exclude) {
  212. identifier += `|exclude: ${this._prettyRegExp(
  213. this.options.exclude,
  214. false
  215. )}`;
  216. }
  217. if (this.options.referencedExports) {
  218. identifier += `|referencedExports: ${JSON.stringify(
  219. this.options.referencedExports
  220. )}`;
  221. }
  222. if (this.options.chunkName) {
  223. identifier += `|chunkName: ${this.options.chunkName}`;
  224. }
  225. if (this.options.groupOptions) {
  226. identifier += `|groupOptions: ${JSON.stringify(
  227. this.options.groupOptions
  228. )}`;
  229. }
  230. if (this.options.namespaceObject === "strict") {
  231. identifier += "|strict namespace object";
  232. } else if (this.options.namespaceObject) {
  233. identifier += "|namespace object";
  234. }
  235. if (this.layer) {
  236. identifier += `|layer: ${this.layer}`;
  237. }
  238. return identifier;
  239. }
  240. /**
  241. * @returns {string} a unique identifier of the module
  242. */
  243. identifier() {
  244. return this._identifier;
  245. }
  246. /**
  247. * @param {RequestShortener} requestShortener the request shortener
  248. * @returns {string} a user readable identifier of the module
  249. */
  250. readableIdentifier(requestShortener) {
  251. let identifier;
  252. if (this.context) {
  253. identifier = `${requestShortener.shorten(this.context)}/`;
  254. } else if (
  255. typeof this.options.resource === "string" ||
  256. this.options.resource === false
  257. ) {
  258. identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`;
  259. } else {
  260. identifier = this.options.resource
  261. .map((r) => `${requestShortener.shorten(r)}/`)
  262. .join(" ");
  263. }
  264. if (this.options.resourceQuery) {
  265. identifier += ` ${this.options.resourceQuery}`;
  266. }
  267. if (this.options.mode) {
  268. identifier += ` ${this.options.mode}`;
  269. }
  270. if (!this.options.recursive) {
  271. identifier += " nonrecursive";
  272. }
  273. if (this.options.addon) {
  274. identifier += ` ${requestShortener.shorten(this.options.addon)}`;
  275. }
  276. if (this.options.regExp) {
  277. identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
  278. }
  279. if (this.options.include) {
  280. identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
  281. }
  282. if (this.options.exclude) {
  283. identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
  284. }
  285. if (this.options.referencedExports) {
  286. identifier += ` referencedExports: ${this.options.referencedExports
  287. .map((e) => e.join("."))
  288. .join(", ")}`;
  289. }
  290. if (this.options.chunkName) {
  291. identifier += ` chunkName: ${this.options.chunkName}`;
  292. }
  293. if (this.options.groupOptions) {
  294. const groupOptions = this.options.groupOptions;
  295. for (const key of Object.keys(groupOptions)) {
  296. identifier += ` ${key}: ${
  297. groupOptions[/** @type {keyof RawChunkGroupOptions} */ (key)]
  298. }`;
  299. }
  300. }
  301. if (this.options.namespaceObject === "strict") {
  302. identifier += " strict namespace object";
  303. } else if (this.options.namespaceObject) {
  304. identifier += " namespace object";
  305. }
  306. return identifier;
  307. }
  308. /**
  309. * @param {LibIdentOptions} options options
  310. * @returns {string | null} an identifier for library inclusion
  311. */
  312. libIdent(options) {
  313. let identifier;
  314. if (this.context) {
  315. identifier = contextify(
  316. options.context,
  317. this.context,
  318. options.associatedObjectForCache
  319. );
  320. } else if (typeof this.options.resource === "string") {
  321. identifier = contextify(
  322. options.context,
  323. this.options.resource,
  324. options.associatedObjectForCache
  325. );
  326. } else if (this.options.resource === false) {
  327. identifier = "false";
  328. } else {
  329. identifier = this.options.resource
  330. .map((res) =>
  331. contextify(options.context, res, options.associatedObjectForCache)
  332. )
  333. .join(" ");
  334. }
  335. if (this.layer) identifier = `(${this.layer})/${identifier}`;
  336. if (this.options.mode) {
  337. identifier += ` ${this.options.mode}`;
  338. }
  339. if (this.options.recursive) {
  340. identifier += " recursive";
  341. }
  342. if (this.options.addon) {
  343. identifier += ` ${contextify(
  344. options.context,
  345. this.options.addon,
  346. options.associatedObjectForCache
  347. )}`;
  348. }
  349. if (this.options.regExp) {
  350. identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
  351. }
  352. if (this.options.include) {
  353. identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
  354. }
  355. if (this.options.exclude) {
  356. identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
  357. }
  358. if (this.options.referencedExports) {
  359. identifier += ` referencedExports: ${this.options.referencedExports
  360. .map((e) => e.join("."))
  361. .join(", ")}`;
  362. }
  363. return identifier;
  364. }
  365. /**
  366. * @returns {void}
  367. */
  368. invalidateBuild() {
  369. this._forceBuild = true;
  370. }
  371. /**
  372. * @param {NeedBuildContext} context context info
  373. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  374. * @returns {void}
  375. */
  376. needBuild({ fileSystemInfo }, callback) {
  377. // build if enforced
  378. if (this._forceBuild) return callback(null, true);
  379. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  380. // always build when we have no snapshot and context
  381. if (!buildInfo.snapshot) {
  382. return callback(null, Boolean(this.context || this.options.resource));
  383. }
  384. fileSystemInfo.checkSnapshotValid(buildInfo.snapshot, (err, valid) => {
  385. callback(err, !valid);
  386. });
  387. }
  388. /**
  389. * @param {WebpackOptions} options webpack options
  390. * @param {Compilation} compilation the compilation
  391. * @param {ResolverWithOptions} resolver the resolver
  392. * @param {InputFileSystem} fs the file system
  393. * @param {BuildCallback} callback callback function
  394. * @returns {void}
  395. */
  396. build(options, compilation, resolver, fs, callback) {
  397. this._forceBuild = false;
  398. /** @type {BuildMeta} */
  399. this.buildMeta = {
  400. exportsType: "default",
  401. defaultObject: "redirect-warn"
  402. };
  403. this.buildInfo = {
  404. snapshot: undefined
  405. };
  406. this.dependencies.length = 0;
  407. this.blocks.length = 0;
  408. const startTime = Date.now();
  409. /** @type {ResolveDependencies} */
  410. (this.resolveDependencies)(fs, this.options, (err, dependencies) => {
  411. if (err) {
  412. return callback(
  413. makeWebpackError(err, "ContextModule.resolveDependencies")
  414. );
  415. }
  416. // abort if something failed
  417. // this will create an empty context
  418. if (!dependencies) {
  419. callback();
  420. return;
  421. }
  422. // enhance dependencies with meta info
  423. for (const dep of dependencies) {
  424. dep.loc = {
  425. name: dep.userRequest
  426. };
  427. dep.request = this.options.addon + dep.request;
  428. }
  429. dependencies.sort(
  430. concatComparators(
  431. compareSelect((a) => a.loc, compareLocations),
  432. keepOriginalOrder(this.dependencies)
  433. )
  434. );
  435. if (this.options.mode === "sync" || this.options.mode === "eager") {
  436. // if we have an sync or eager context
  437. // just add all dependencies and continue
  438. this.dependencies = dependencies;
  439. } else if (this.options.mode === "lazy-once") {
  440. // for the lazy-once mode create a new async dependency block
  441. // and add that block to this context
  442. if (dependencies.length > 0) {
  443. const block = new AsyncDependenciesBlock({
  444. ...this.options.groupOptions,
  445. name: this.options.chunkName
  446. });
  447. for (const dep of dependencies) {
  448. block.addDependency(dep);
  449. }
  450. this.addBlock(block);
  451. }
  452. } else if (
  453. this.options.mode === "weak" ||
  454. this.options.mode === "async-weak"
  455. ) {
  456. // we mark all dependencies as weak
  457. for (const dep of dependencies) {
  458. dep.weak = true;
  459. }
  460. this.dependencies = dependencies;
  461. } else if (this.options.mode === "lazy") {
  462. // if we are lazy create a new async dependency block per dependency
  463. // and add all blocks to this context
  464. let index = 0;
  465. for (const dep of dependencies) {
  466. let chunkName = this.options.chunkName;
  467. if (chunkName) {
  468. if (!/\[(index|request)\]/.test(chunkName)) {
  469. chunkName += "[index]";
  470. }
  471. chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
  472. chunkName = chunkName.replace(
  473. /\[request\]/g,
  474. Template.toPath(dep.userRequest)
  475. );
  476. }
  477. const block = new AsyncDependenciesBlock(
  478. {
  479. ...this.options.groupOptions,
  480. name: chunkName
  481. },
  482. dep.loc,
  483. dep.userRequest
  484. );
  485. block.addDependency(dep);
  486. this.addBlock(block);
  487. }
  488. } else {
  489. callback(
  490. new WebpackError(`Unsupported mode "${this.options.mode}" in context`)
  491. );
  492. return;
  493. }
  494. if (!this.context && !this.options.resource) return callback();
  495. compilation.fileSystemInfo.createSnapshot(
  496. startTime,
  497. null,
  498. this.context
  499. ? [this.context]
  500. : typeof this.options.resource === "string"
  501. ? [this.options.resource]
  502. : /** @type {string[]} */ (this.options.resource),
  503. null,
  504. SNAPSHOT_OPTIONS,
  505. (err, snapshot) => {
  506. if (err) return callback(err);
  507. /** @type {BuildInfo} */
  508. (this.buildInfo).snapshot = snapshot;
  509. callback();
  510. }
  511. );
  512. });
  513. }
  514. /**
  515. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  516. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  517. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  518. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  519. */
  520. addCacheDependencies(
  521. fileDependencies,
  522. contextDependencies,
  523. missingDependencies,
  524. buildDependencies
  525. ) {
  526. if (this.context) {
  527. contextDependencies.add(this.context);
  528. } else if (typeof this.options.resource === "string") {
  529. contextDependencies.add(this.options.resource);
  530. } else if (this.options.resource === false) {
  531. // Do nothing
  532. } else {
  533. for (const res of this.options.resource) contextDependencies.add(res);
  534. }
  535. }
  536. /**
  537. * @param {Dependency[]} dependencies all dependencies
  538. * @param {ChunkGraph} chunkGraph chunk graph
  539. * @returns {Map<string, string | number>} map with user requests
  540. */
  541. getUserRequestMap(dependencies, chunkGraph) {
  542. const moduleGraph = chunkGraph.moduleGraph;
  543. // if we filter first we get a new array
  544. // therefore we don't need to create a clone of dependencies explicitly
  545. // therefore the order of this is !important!
  546. const sortedDependencies =
  547. /** @type {ContextElementDependency[]} */
  548. (dependencies)
  549. .filter((dependency) => moduleGraph.getModule(dependency))
  550. .sort((a, b) => {
  551. if (a.userRequest === b.userRequest) {
  552. return 0;
  553. }
  554. return a.userRequest < b.userRequest ? -1 : 1;
  555. });
  556. const map = Object.create(null);
  557. for (const dep of sortedDependencies) {
  558. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  559. map[dep.userRequest] = chunkGraph.getModuleId(module);
  560. }
  561. return map;
  562. }
  563. /**
  564. * @param {Dependency[]} dependencies all dependencies
  565. * @param {ChunkGraph} chunkGraph chunk graph
  566. * @returns {FakeMap | FakeMapType} fake map
  567. */
  568. getFakeMap(dependencies, chunkGraph) {
  569. if (!this.options.namespaceObject) {
  570. return 9;
  571. }
  572. const moduleGraph = chunkGraph.moduleGraph;
  573. // bitfield
  574. let hasType = 0;
  575. const comparator = compareModulesById(chunkGraph);
  576. // if we filter first we get a new array
  577. // therefore we don't need to create a clone of dependencies explicitly
  578. // therefore the order of this is !important!
  579. const sortedModules = dependencies
  580. .map(
  581. (dependency) =>
  582. /** @type {Module} */ (moduleGraph.getModule(dependency))
  583. )
  584. .filter(Boolean)
  585. .sort(comparator);
  586. /** @type {FakeMap} */
  587. const fakeMap = Object.create(null);
  588. for (const module of sortedModules) {
  589. const exportsType = module.getExportsType(
  590. moduleGraph,
  591. this.options.namespaceObject === "strict"
  592. );
  593. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  594. switch (exportsType) {
  595. case "namespace":
  596. fakeMap[id] = 9;
  597. hasType |= 1;
  598. break;
  599. case "dynamic":
  600. fakeMap[id] = 7;
  601. hasType |= 2;
  602. break;
  603. case "default-only":
  604. fakeMap[id] = 1;
  605. hasType |= 4;
  606. break;
  607. case "default-with-named":
  608. fakeMap[id] = 3;
  609. hasType |= 8;
  610. break;
  611. default:
  612. throw new Error(`Unexpected exports type ${exportsType}`);
  613. }
  614. }
  615. if (hasType === 1) {
  616. return 9;
  617. }
  618. if (hasType === 2) {
  619. return 7;
  620. }
  621. if (hasType === 4) {
  622. return 1;
  623. }
  624. if (hasType === 8) {
  625. return 3;
  626. }
  627. if (hasType === 0) {
  628. return 9;
  629. }
  630. return fakeMap;
  631. }
  632. /**
  633. * @param {FakeMap | FakeMapType} fakeMap fake map
  634. * @returns {string} fake map init statement
  635. */
  636. getFakeMapInitStatement(fakeMap) {
  637. return typeof fakeMap === "object"
  638. ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
  639. : "";
  640. }
  641. /**
  642. * @param {FakeMapType} type type
  643. * @param {boolean=} asyncModule is async module
  644. * @returns {string} return result
  645. */
  646. getReturn(type, asyncModule) {
  647. if (type === 9) {
  648. return `${RuntimeGlobals.require}(id)`;
  649. }
  650. return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${
  651. asyncModule ? " | 16" : ""
  652. })`;
  653. }
  654. /**
  655. * @param {FakeMap | FakeMapType} fakeMap fake map
  656. * @param {boolean=} asyncModule us async module
  657. * @param {string=} fakeMapDataExpression fake map data expression
  658. * @returns {string} module object source
  659. */
  660. getReturnModuleObjectSource(
  661. fakeMap,
  662. asyncModule,
  663. fakeMapDataExpression = "fakeMap[id]"
  664. ) {
  665. if (typeof fakeMap === "number") {
  666. return `return ${this.getReturn(fakeMap, asyncModule)};`;
  667. }
  668. return `return ${
  669. RuntimeGlobals.createFakeNamespaceObject
  670. }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`;
  671. }
  672. /**
  673. * @param {Dependency[]} dependencies dependencies
  674. * @param {ModuleId} id module id
  675. * @param {ChunkGraph} chunkGraph the chunk graph
  676. * @returns {string} source code
  677. */
  678. getSyncSource(dependencies, id, chunkGraph) {
  679. const map = this.getUserRequestMap(dependencies, chunkGraph);
  680. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  681. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  682. return `var map = ${JSON.stringify(map, null, "\t")};
  683. ${this.getFakeMapInitStatement(fakeMap)}
  684. function webpackContext(req) {
  685. var id = webpackContextResolve(req);
  686. ${returnModuleObject}
  687. }
  688. function webpackContextResolve(req) {
  689. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  690. var e = new Error("Cannot find module '" + req + "'");
  691. e.code = 'MODULE_NOT_FOUND';
  692. throw e;
  693. }
  694. return map[req];
  695. }
  696. webpackContext.keys = function webpackContextKeys() {
  697. return Object.keys(map);
  698. };
  699. webpackContext.resolve = webpackContextResolve;
  700. module.exports = webpackContext;
  701. webpackContext.id = ${JSON.stringify(id)};`;
  702. }
  703. /**
  704. * @param {Dependency[]} dependencies dependencies
  705. * @param {ModuleId} id module id
  706. * @param {ChunkGraph} chunkGraph the chunk graph
  707. * @returns {string} source code
  708. */
  709. getWeakSyncSource(dependencies, id, chunkGraph) {
  710. const map = this.getUserRequestMap(dependencies, chunkGraph);
  711. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  712. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  713. return `var map = ${JSON.stringify(map, null, "\t")};
  714. ${this.getFakeMapInitStatement(fakeMap)}
  715. function webpackContext(req) {
  716. var id = webpackContextResolve(req);
  717. if(!${RuntimeGlobals.moduleFactories}[id]) {
  718. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  719. e.code = 'MODULE_NOT_FOUND';
  720. throw e;
  721. }
  722. ${returnModuleObject}
  723. }
  724. function webpackContextResolve(req) {
  725. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  726. var e = new Error("Cannot find module '" + req + "'");
  727. e.code = 'MODULE_NOT_FOUND';
  728. throw e;
  729. }
  730. return map[req];
  731. }
  732. webpackContext.keys = function webpackContextKeys() {
  733. return Object.keys(map);
  734. };
  735. webpackContext.resolve = webpackContextResolve;
  736. webpackContext.id = ${JSON.stringify(id)};
  737. module.exports = webpackContext;`;
  738. }
  739. /**
  740. * @param {Dependency[]} dependencies dependencies
  741. * @param {ModuleId} id module id
  742. * @param {object} context context
  743. * @param {ChunkGraph} context.chunkGraph the chunk graph
  744. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  745. * @returns {string} source code
  746. */
  747. getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  748. const arrow = runtimeTemplate.supportsArrowFunction();
  749. const map = this.getUserRequestMap(dependencies, chunkGraph);
  750. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  751. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true);
  752. return `var map = ${JSON.stringify(map, null, "\t")};
  753. ${this.getFakeMapInitStatement(fakeMap)}
  754. function webpackAsyncContext(req) {
  755. return webpackAsyncContextResolve(req).then(${
  756. arrow ? "id =>" : "function(id)"
  757. } {
  758. if(!${RuntimeGlobals.moduleFactories}[id]) {
  759. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  760. e.code = 'MODULE_NOT_FOUND';
  761. throw e;
  762. }
  763. ${returnModuleObject}
  764. });
  765. }
  766. function webpackAsyncContextResolve(req) {
  767. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  768. // uncaught exception popping up in devtools
  769. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  770. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  771. var e = new Error("Cannot find module '" + req + "'");
  772. e.code = 'MODULE_NOT_FOUND';
  773. throw e;
  774. }
  775. return map[req];
  776. });
  777. }
  778. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  779. "Object.keys(map)"
  780. )};
  781. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  782. webpackAsyncContext.id = ${JSON.stringify(id)};
  783. module.exports = webpackAsyncContext;`;
  784. }
  785. /**
  786. * @param {Dependency[]} dependencies dependencies
  787. * @param {ModuleId} id module id
  788. * @param {object} context context
  789. * @param {ChunkGraph} context.chunkGraph the chunk graph
  790. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  791. * @returns {string} source code
  792. */
  793. getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  794. const arrow = runtimeTemplate.supportsArrowFunction();
  795. const map = this.getUserRequestMap(dependencies, chunkGraph);
  796. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  797. const thenFunction =
  798. fakeMap !== 9
  799. ? `${arrow ? "id =>" : "function(id)"} {
  800. ${this.getReturnModuleObjectSource(fakeMap, true)}
  801. }`
  802. : RuntimeGlobals.require;
  803. return `var map = ${JSON.stringify(map, null, "\t")};
  804. ${this.getFakeMapInitStatement(fakeMap)}
  805. function webpackAsyncContext(req) {
  806. return webpackAsyncContextResolve(req).then(${thenFunction});
  807. }
  808. function webpackAsyncContextResolve(req) {
  809. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  810. // uncaught exception popping up in devtools
  811. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  812. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  813. var e = new Error("Cannot find module '" + req + "'");
  814. e.code = 'MODULE_NOT_FOUND';
  815. throw e;
  816. }
  817. return map[req];
  818. });
  819. }
  820. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  821. "Object.keys(map)"
  822. )};
  823. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  824. webpackAsyncContext.id = ${JSON.stringify(id)};
  825. module.exports = webpackAsyncContext;`;
  826. }
  827. /**
  828. * @param {AsyncDependenciesBlock} block block
  829. * @param {Dependency[]} dependencies dependencies
  830. * @param {ModuleId} id module id
  831. * @param {object} options options object
  832. * @param {RuntimeTemplate} options.runtimeTemplate the runtime template
  833. * @param {ChunkGraph} options.chunkGraph the chunk graph
  834. * @returns {string} source code
  835. */
  836. getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) {
  837. const promise = runtimeTemplate.blockPromise({
  838. chunkGraph,
  839. block,
  840. message: "lazy-once context",
  841. runtimeRequirements: new Set()
  842. });
  843. const arrow = runtimeTemplate.supportsArrowFunction();
  844. const map = this.getUserRequestMap(dependencies, chunkGraph);
  845. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  846. const thenFunction =
  847. fakeMap !== 9
  848. ? `${arrow ? "id =>" : "function(id)"} {
  849. ${this.getReturnModuleObjectSource(fakeMap, true)};
  850. }`
  851. : RuntimeGlobals.require;
  852. return `var map = ${JSON.stringify(map, null, "\t")};
  853. ${this.getFakeMapInitStatement(fakeMap)}
  854. function webpackAsyncContext(req) {
  855. return webpackAsyncContextResolve(req).then(${thenFunction});
  856. }
  857. function webpackAsyncContextResolve(req) {
  858. return ${promise}.then(${arrow ? "() =>" : "function()"} {
  859. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  860. var e = new Error("Cannot find module '" + req + "'");
  861. e.code = 'MODULE_NOT_FOUND';
  862. throw e;
  863. }
  864. return map[req];
  865. });
  866. }
  867. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  868. "Object.keys(map)"
  869. )};
  870. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  871. webpackAsyncContext.id = ${JSON.stringify(id)};
  872. module.exports = webpackAsyncContext;`;
  873. }
  874. /**
  875. * @param {AsyncDependenciesBlock[]} blocks blocks
  876. * @param {ModuleId} id module id
  877. * @param {object} context context
  878. * @param {ChunkGraph} context.chunkGraph the chunk graph
  879. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  880. * @returns {string} source code
  881. */
  882. getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) {
  883. const moduleGraph = chunkGraph.moduleGraph;
  884. const arrow = runtimeTemplate.supportsArrowFunction();
  885. let hasMultipleOrNoChunks = false;
  886. let hasNoChunk = true;
  887. const fakeMap = this.getFakeMap(
  888. blocks.map((b) => b.dependencies[0]),
  889. chunkGraph
  890. );
  891. const hasFakeMap = typeof fakeMap === "object";
  892. /** @typedef {{userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock}} Item */
  893. /**
  894. * @type {Item[]}
  895. */
  896. const items = blocks
  897. .map((block) => {
  898. const dependency =
  899. /** @type {ContextElementDependency} */
  900. (block.dependencies[0]);
  901. return {
  902. dependency,
  903. module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
  904. block,
  905. userRequest: dependency.userRequest,
  906. chunks: undefined
  907. };
  908. })
  909. .filter((item) => item.module);
  910. for (const item of items) {
  911. const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
  912. const chunks = (chunkGroup && chunkGroup.chunks) || [];
  913. item.chunks = chunks;
  914. if (chunks.length > 0) {
  915. hasNoChunk = false;
  916. }
  917. if (chunks.length !== 1) {
  918. hasMultipleOrNoChunks = true;
  919. }
  920. }
  921. const shortMode = hasNoChunk && !hasFakeMap;
  922. const sortedItems = items.sort((a, b) => {
  923. if (a.userRequest === b.userRequest) return 0;
  924. return a.userRequest < b.userRequest ? -1 : 1;
  925. });
  926. /** @type {Record<string, ModuleId | (ModuleId[] | ChunkId[])>} */
  927. const map = Object.create(null);
  928. for (const item of sortedItems) {
  929. const moduleId =
  930. /** @type {ModuleId} */
  931. (chunkGraph.getModuleId(item.module));
  932. if (shortMode) {
  933. map[item.userRequest] = moduleId;
  934. } else {
  935. /** @type {(ModuleId | ChunkId)[]} */
  936. const arrayStart = [moduleId];
  937. if (hasFakeMap) {
  938. arrayStart.push(fakeMap[moduleId]);
  939. }
  940. map[item.userRequest] = [
  941. ...arrayStart,
  942. .../** @type {Chunk[]} */
  943. (item.chunks).map((chunk) => /** @type {ChunkId} */ (chunk.id))
  944. ];
  945. }
  946. }
  947. const chunksStartPosition = hasFakeMap ? 2 : 1;
  948. const requestPrefix = hasNoChunk
  949. ? "Promise.resolve()"
  950. : hasMultipleOrNoChunks
  951. ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
  952. : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
  953. const returnModuleObject = this.getReturnModuleObjectSource(
  954. fakeMap,
  955. true,
  956. shortMode ? "invalid" : "ids[1]"
  957. );
  958. const webpackAsyncContext =
  959. requestPrefix === "Promise.resolve()"
  960. ? `
  961. function webpackAsyncContext(req) {
  962. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  963. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  964. var e = new Error("Cannot find module '" + req + "'");
  965. e.code = 'MODULE_NOT_FOUND';
  966. throw e;
  967. }
  968. ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"}
  969. ${returnModuleObject}
  970. });
  971. }`
  972. : `function webpackAsyncContext(req) {
  973. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  974. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  975. var e = new Error("Cannot find module '" + req + "'");
  976. e.code = 'MODULE_NOT_FOUND';
  977. throw e;
  978. });
  979. }
  980. var ids = map[req], id = ids[0];
  981. return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} {
  982. ${returnModuleObject}
  983. });
  984. }`;
  985. return `var map = ${JSON.stringify(map, null, "\t")};
  986. ${webpackAsyncContext}
  987. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  988. "Object.keys(map)"
  989. )};
  990. webpackAsyncContext.id = ${JSON.stringify(id)};
  991. module.exports = webpackAsyncContext;`;
  992. }
  993. /**
  994. * @param {ModuleId} id module id
  995. * @param {RuntimeTemplate} runtimeTemplate runtime template
  996. * @returns {string} source for empty async context
  997. */
  998. getSourceForEmptyContext(id, runtimeTemplate) {
  999. return `function webpackEmptyContext(req) {
  1000. var e = new Error("Cannot find module '" + req + "'");
  1001. e.code = 'MODULE_NOT_FOUND';
  1002. throw e;
  1003. }
  1004. webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1005. webpackEmptyContext.resolve = webpackEmptyContext;
  1006. webpackEmptyContext.id = ${JSON.stringify(id)};
  1007. module.exports = webpackEmptyContext;`;
  1008. }
  1009. /**
  1010. * @param {ModuleId} id module id
  1011. * @param {RuntimeTemplate} runtimeTemplate runtime template
  1012. * @returns {string} source for empty async context
  1013. */
  1014. getSourceForEmptyAsyncContext(id, runtimeTemplate) {
  1015. const arrow = runtimeTemplate.supportsArrowFunction();
  1016. return `function webpackEmptyAsyncContext(req) {
  1017. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  1018. // uncaught exception popping up in devtools
  1019. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  1020. var e = new Error("Cannot find module '" + req + "'");
  1021. e.code = 'MODULE_NOT_FOUND';
  1022. throw e;
  1023. });
  1024. }
  1025. webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1026. webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
  1027. webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
  1028. module.exports = webpackEmptyAsyncContext;`;
  1029. }
  1030. /**
  1031. * @param {string} asyncMode module mode
  1032. * @param {CodeGenerationContext} context context info
  1033. * @returns {string} the source code
  1034. */
  1035. getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
  1036. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
  1037. if (asyncMode === "lazy") {
  1038. if (this.blocks && this.blocks.length > 0) {
  1039. return this.getLazySource(this.blocks, id, {
  1040. runtimeTemplate,
  1041. chunkGraph
  1042. });
  1043. }
  1044. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1045. }
  1046. if (asyncMode === "eager") {
  1047. if (this.dependencies && this.dependencies.length > 0) {
  1048. return this.getEagerSource(this.dependencies, id, {
  1049. chunkGraph,
  1050. runtimeTemplate
  1051. });
  1052. }
  1053. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1054. }
  1055. if (asyncMode === "lazy-once") {
  1056. const block = this.blocks[0];
  1057. if (block) {
  1058. return this.getLazyOnceSource(block, block.dependencies, id, {
  1059. runtimeTemplate,
  1060. chunkGraph
  1061. });
  1062. }
  1063. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1064. }
  1065. if (asyncMode === "async-weak") {
  1066. if (this.dependencies && this.dependencies.length > 0) {
  1067. return this.getAsyncWeakSource(this.dependencies, id, {
  1068. chunkGraph,
  1069. runtimeTemplate
  1070. });
  1071. }
  1072. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1073. }
  1074. if (
  1075. asyncMode === "weak" &&
  1076. this.dependencies &&
  1077. this.dependencies.length > 0
  1078. ) {
  1079. return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
  1080. }
  1081. if (this.dependencies && this.dependencies.length > 0) {
  1082. return this.getSyncSource(this.dependencies, id, chunkGraph);
  1083. }
  1084. return this.getSourceForEmptyContext(id, runtimeTemplate);
  1085. }
  1086. /**
  1087. * @param {string} sourceString source content
  1088. * @param {Compilation=} compilation the compilation
  1089. * @returns {Source} generated source
  1090. */
  1091. getSource(sourceString, compilation) {
  1092. if (this.useSourceMap || this.useSimpleSourceMap) {
  1093. return new OriginalSource(
  1094. sourceString,
  1095. `webpack://${makePathsRelative(
  1096. (compilation && compilation.compiler.context) || "",
  1097. this.identifier(),
  1098. compilation && compilation.compiler.root
  1099. )}`
  1100. );
  1101. }
  1102. return new RawSource(sourceString);
  1103. }
  1104. /**
  1105. * @param {CodeGenerationContext} context context for code generation
  1106. * @returns {CodeGenerationResult} result
  1107. */
  1108. codeGeneration(context) {
  1109. const { chunkGraph, compilation } = context;
  1110. const sources = new Map();
  1111. sources.set(
  1112. "javascript",
  1113. this.getSource(
  1114. this.getSourceString(this.options.mode, context),
  1115. compilation
  1116. )
  1117. );
  1118. const set = new Set();
  1119. const allDeps =
  1120. this.dependencies.length > 0
  1121. ? /** @type {ContextElementDependency[]} */ [...this.dependencies]
  1122. : [];
  1123. for (const block of this.blocks) {
  1124. for (const dep of block.dependencies) {
  1125. allDeps.push(/** @type {ContextElementDependency} */ (dep));
  1126. }
  1127. }
  1128. set.add(RuntimeGlobals.module);
  1129. set.add(RuntimeGlobals.hasOwnProperty);
  1130. if (allDeps.length > 0) {
  1131. const asyncMode = this.options.mode;
  1132. set.add(RuntimeGlobals.require);
  1133. if (asyncMode === "weak") {
  1134. set.add(RuntimeGlobals.moduleFactories);
  1135. } else if (asyncMode === "async-weak") {
  1136. set.add(RuntimeGlobals.moduleFactories);
  1137. set.add(RuntimeGlobals.ensureChunk);
  1138. } else if (asyncMode === "lazy" || asyncMode === "lazy-once") {
  1139. set.add(RuntimeGlobals.ensureChunk);
  1140. }
  1141. if (this.getFakeMap(allDeps, chunkGraph) !== 9) {
  1142. set.add(RuntimeGlobals.createFakeNamespaceObject);
  1143. }
  1144. }
  1145. return {
  1146. sources,
  1147. runtimeRequirements: set
  1148. };
  1149. }
  1150. /**
  1151. * @param {string=} type the source type for which the size should be estimated
  1152. * @returns {number} the estimated size of the module (must be non-zero)
  1153. */
  1154. size(type) {
  1155. // base penalty
  1156. let size = 160;
  1157. // if we don't have dependencies we stop here.
  1158. for (const dependency of this.dependencies) {
  1159. const element = /** @type {ContextElementDependency} */ (dependency);
  1160. size += 5 + element.userRequest.length;
  1161. }
  1162. return size;
  1163. }
  1164. /**
  1165. * @param {ObjectSerializerContext} context context
  1166. */
  1167. serialize(context) {
  1168. const { write } = context;
  1169. write(this._identifier);
  1170. write(this._forceBuild);
  1171. super.serialize(context);
  1172. }
  1173. /**
  1174. * @param {ObjectDeserializerContext} context context
  1175. */
  1176. deserialize(context) {
  1177. const { read } = context;
  1178. this._identifier = read();
  1179. this._forceBuild = read();
  1180. super.deserialize(context);
  1181. }
  1182. }
  1183. makeSerializable(ContextModule, "webpack/lib/ContextModule");
  1184. module.exports = ContextModule;