ModuleGraph.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const ExportsInfo = require("./ExportsInfo");
  8. const ModuleGraphConnection = require("./ModuleGraphConnection");
  9. const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency");
  10. const { ImportPhaseUtils } = require("./dependencies/ImportPhase");
  11. const SortableSet = require("./util/SortableSet");
  12. const WeakTupleMap = require("./util/WeakTupleMap");
  13. const { sortWithSourceOrder } = require("./util/comparators");
  14. /** @import { ModuleMemCaches } from "./Compilation" */
  15. /** @import DependenciesBlock from "./DependenciesBlock" */
  16. /** @import Dependency, { ExportInfoName } from "./Dependency" */
  17. /** @import { ExportInfo } from "./ExportsInfo" */
  18. /** @import Module from "./Module" */
  19. /** @import ModuleProfile from "./ModuleProfile" */
  20. /** @import RequestShortener from "./RequestShortener" */
  21. /** @import { RuntimeSpec } from "./util/runtime" */
  22. /** @import HarmonyImportSideEffectDependency from "./dependencies/HarmonyImportSideEffectDependency" */
  23. /**
  24. * @import HarmonyImportSpecifierDependency, {
  25. * idsSymbol as HarmonyImportSpecifierDependencyIDsSymbol
  26. * } from "./dependencies/HarmonyImportSpecifierDependency"
  27. */
  28. /** @import { DependencySourceOrder } from "./util/comparators" */
  29. /**
  30. * Defines the optimization bailout function callback.
  31. * @callback OptimizationBailoutFunction
  32. * @param {RequestShortener} requestShortener
  33. * @returns {string}
  34. */
  35. /** @type {Iterable<ModuleGraphConnection>} */
  36. const EMPTY_SET = new Set();
  37. /**
  38. * Gets connections by key.
  39. * @template {Module | null | undefined} T
  40. * @param {SortableSet<ModuleGraphConnection>} set input
  41. * @param {(connection: ModuleGraphConnection) => T} getKey function to extract key from connection
  42. * @returns {ReadonlyMap<T, ReadonlyArray<ModuleGraphConnection>>} mapped by key
  43. */
  44. const getConnectionsByKey = (set, getKey) => {
  45. /** @type {Map<T, ModuleGraphConnection[]>} */
  46. const map = new Map();
  47. /** @type {T | 0} */
  48. let lastKey = 0;
  49. /** @type {ModuleGraphConnection[] | undefined} */
  50. let lastList;
  51. for (const connection of set) {
  52. const key = getKey(connection);
  53. if (lastKey === key) {
  54. /** @type {ModuleGraphConnection[]} */
  55. (lastList).push(connection);
  56. } else {
  57. lastKey = key;
  58. const list = map.get(key);
  59. if (list !== undefined) {
  60. lastList = list;
  61. list.push(connection);
  62. } else {
  63. const list = [connection];
  64. lastList = list;
  65. map.set(key, list);
  66. }
  67. }
  68. }
  69. return map;
  70. };
  71. /**
  72. * Gets connections by origin module.
  73. * @param {SortableSet<ModuleGraphConnection>} set input
  74. * @returns {ReadonlyMap<Module | undefined | null, ReadonlyArray<ModuleGraphConnection>>} mapped by origin module
  75. */
  76. const getConnectionsByOriginModule = (set) =>
  77. getConnectionsByKey(set, (connection) => connection.originModule);
  78. /**
  79. * Gets connections by module.
  80. * @param {SortableSet<ModuleGraphConnection>} set input
  81. * @returns {ReadonlyMap<Module | undefined, ReadonlyArray<ModuleGraphConnection>>} mapped by module
  82. */
  83. const getConnectionsByModule = (set) =>
  84. getConnectionsByKey(set, (connection) => connection.module);
  85. /** @typedef {SortableSet<ModuleGraphConnection>} IncomingConnections */
  86. /** @typedef {SortableSet<ModuleGraphConnection>} OutgoingConnections */
  87. /** @typedef {Module | null | undefined} Issuer */
  88. /** @typedef {(string | OptimizationBailoutFunction)[]} OptimizationBailouts */
  89. class ModuleGraphModule {
  90. constructor() {
  91. /** @type {IncomingConnections} */
  92. this.incomingConnections = new SortableSet();
  93. /** @type {OutgoingConnections | undefined} */
  94. this.outgoingConnections = undefined;
  95. /** @type {Issuer} */
  96. this.issuer = undefined;
  97. /** @type {OptimizationBailouts} */
  98. this.optimizationBailout = [];
  99. /** @type {ExportsInfo} */
  100. this.exports = new ExportsInfo();
  101. /** @type {number | null} */
  102. this.preOrderIndex = null;
  103. /** @type {number | null} */
  104. this.postOrderIndex = null;
  105. /** @type {number | null} */
  106. this.depth = null;
  107. /** @type {ModuleProfile | undefined} */
  108. this.profile = undefined;
  109. /** @type {boolean} */
  110. this.async = false;
  111. /** @type {ModuleGraphConnection[] | undefined} */
  112. this._unassignedConnections = undefined;
  113. }
  114. }
  115. /** @typedef {(moduleGraphConnection: ModuleGraphConnection) => boolean} FilterConnection */
  116. /** @typedef {EXPECTED_OBJECT} MetaKey */
  117. /**
  118. * @import {
  119. * idsSymbol as CommonJsExportRequireDependencyIDsSymbol
  120. * } from "./dependencies/CommonJsExportRequireDependency"
  121. */
  122. /**
  123. * @import {
  124. * idsSymbol as HarmonyExportImportedSpecifierDependencyIDsSymbol
  125. * } from "./dependencies/HarmonyExportImportedSpecifierDependency"
  126. */
  127. /**
  128. * Defines the known meta type used by this module.
  129. * @typedef {object} KnownMeta
  130. * @property {Map<Module, string>=} importVarMap
  131. * @property {Map<Module, string>=} deferredImportVarMap
  132. */
  133. /** @typedef {KnownMeta & Record<CommonJsExportRequireDependencyIDsSymbol | HarmonyImportSpecifierDependencyIDsSymbol | HarmonyExportImportedSpecifierDependencyIDsSymbol, string[]> & Record<string, EXPECTED_ANY>} Meta */
  134. class ModuleGraph {
  135. constructor() {
  136. /**
  137. * @type {WeakMap<Dependency, ModuleGraphConnection | null>}
  138. * @private
  139. */
  140. this._dependencyMap = new WeakMap();
  141. /**
  142. * @type {Map<Module, ModuleGraphModule>}
  143. * @private
  144. */
  145. this._moduleMap = new Map();
  146. /**
  147. * @type {WeakMap<MetaKey, Meta>}
  148. * @private
  149. */
  150. this._metaMap = new WeakMap();
  151. /**
  152. * @type {WeakTupleMap<EXPECTED_ANY[], EXPECTED_ANY> | undefined}
  153. * @private
  154. */
  155. this._cache = undefined;
  156. /**
  157. * @type {ModuleMemCaches | undefined}
  158. * @private
  159. */
  160. this._moduleMemCaches = undefined;
  161. /**
  162. * @type {string | undefined}
  163. * @private
  164. */
  165. this._cacheStage = undefined;
  166. // incremental rebuilds: when set, move/copyOutgoingModuleConnections record
  167. // their seal-time graph mutations (concatenation) here so they can be reversed,
  168. // keeping this durable graph reusable across rebuilds
  169. /**
  170. * @type {{ oldModule?: Module, newModule: Module, movedOut?: ModuleGraphConnection[] | undefined, movedIn?: ModuleGraphConnection[] | undefined, copied?: ModuleGraphConnection[] }[] | undefined}
  171. * @private
  172. */
  173. this._mutationJournal = undefined;
  174. /**
  175. * @type {WeakMap<Dependency, DependencySourceOrder>}
  176. * @private
  177. */
  178. this._dependencySourceOrderMap = new WeakMap();
  179. /**
  180. * @type {Set<Module>}
  181. * @private
  182. */
  183. this._modulesNeedingSort = new Set();
  184. }
  185. /**
  186. * Get module graph module.
  187. * @param {Module} module the module
  188. * @returns {ModuleGraphModule} the internal module
  189. */
  190. _getModuleGraphModule(module) {
  191. let mgm = this._moduleMap.get(module);
  192. if (mgm === undefined) {
  193. mgm = new ModuleGraphModule();
  194. this._moduleMap.set(module, mgm);
  195. }
  196. return mgm;
  197. }
  198. /**
  199. * Updates parents using the provided dependency.
  200. * @param {Dependency} dependency the dependency
  201. * @param {DependenciesBlock} block parent block
  202. * @param {Module} module parent module
  203. * @param {number=} indexInBlock position in block
  204. * @returns {void}
  205. */
  206. setParents(dependency, block, module, indexInBlock = -1) {
  207. dependency._parentDependenciesBlockIndex = indexInBlock;
  208. dependency._parentDependenciesBlock = block;
  209. dependency._parentModule = module;
  210. }
  211. /**
  212. * Sets parent dependencies block index.
  213. * @param {Dependency} dependency the dependency
  214. * @param {number} index the index
  215. * @returns {void}
  216. */
  217. setParentDependenciesBlockIndex(dependency, index) {
  218. dependency._parentDependenciesBlockIndex = index;
  219. }
  220. /**
  221. * Gets parent module.
  222. * @param {Dependency} dependency the dependency
  223. * @returns {Module | undefined} parent module
  224. */
  225. getParentModule(dependency) {
  226. return dependency._parentModule;
  227. }
  228. /**
  229. * Returns parent block.
  230. * @param {Dependency} dependency the dependency
  231. * @returns {DependenciesBlock | undefined} parent block
  232. */
  233. getParentBlock(dependency) {
  234. return dependency._parentDependenciesBlock;
  235. }
  236. /**
  237. * Gets parent block index.
  238. * @param {Dependency} dependency the dependency
  239. * @returns {number} index
  240. */
  241. getParentBlockIndex(dependency) {
  242. return dependency._parentDependenciesBlockIndex;
  243. }
  244. /**
  245. * Sets resolved module.
  246. * @param {Module | null} originModule the referencing module
  247. * @param {Dependency} dependency the referencing dependency
  248. * @param {Module} module the referenced module
  249. * @returns {void}
  250. */
  251. setResolvedModule(originModule, dependency, module) {
  252. const connection = new ModuleGraphConnection(
  253. originModule,
  254. dependency,
  255. module,
  256. undefined,
  257. // weak is defined on ModuleDependency; undefined for other dependency kinds
  258. /** @type {{ weak?: boolean }} */ (dependency).weak,
  259. dependency.getCondition(this)
  260. );
  261. const connections = this._getModuleGraphModule(module).incomingConnections;
  262. connections.add(connection);
  263. if (originModule) {
  264. const mgm = this._getModuleGraphModule(originModule);
  265. if (mgm._unassignedConnections === undefined) {
  266. mgm._unassignedConnections = [];
  267. }
  268. mgm._unassignedConnections.push(connection);
  269. if (mgm.outgoingConnections === undefined) {
  270. mgm.outgoingConnections = new SortableSet();
  271. }
  272. mgm.outgoingConnections.add(connection);
  273. } else {
  274. this._dependencyMap.set(dependency, connection);
  275. }
  276. }
  277. /**
  278. * Updates module using the provided dependency.
  279. * @param {Dependency} dependency the referencing dependency
  280. * @param {Module} module the referenced module
  281. * @returns {void}
  282. */
  283. updateModule(dependency, module) {
  284. const connection =
  285. /** @type {ModuleGraphConnection} */
  286. (this.getConnection(dependency));
  287. if (connection.module === module) return;
  288. const newConnection = connection.clone();
  289. newConnection.module = module;
  290. this._dependencyMap.set(dependency, newConnection);
  291. connection.setActive(false);
  292. const originMgm = this._getModuleGraphModule(
  293. /** @type {Module} */ (connection.originModule)
  294. );
  295. /** @type {OutgoingConnections} */
  296. (originMgm.outgoingConnections).add(newConnection);
  297. const targetMgm = this._getModuleGraphModule(module);
  298. targetMgm.incomingConnections.add(newConnection);
  299. }
  300. /**
  301. * Updates parent using the provided dependency.
  302. * @param {Dependency} dependency the need update dependency
  303. * @param {ModuleGraphConnection=} connection the target connection
  304. * @param {Module=} parentModule the parent module
  305. * @returns {void}
  306. */
  307. updateParent(dependency, connection, parentModule) {
  308. if (this._dependencySourceOrderMap.has(dependency)) {
  309. return;
  310. }
  311. if (!connection || !parentModule) {
  312. return;
  313. }
  314. const originDependency = connection.dependency;
  315. // src/index.js
  316. // import { c } from "lib/c" -> c = 0
  317. // import { a, b } from "lib" -> a and b have the same source order -> a = b = 1
  318. // import { d } from "lib/d" -> d = 2
  319. const currentSourceOrder =
  320. /** @type {HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */
  321. (dependency).sourceOrder;
  322. // lib/index.js (reexport)
  323. // import { a } from "lib/a" -> a = 0
  324. // import { b } from "lib/b" -> b = 1
  325. const originSourceOrder =
  326. /** @type {HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */
  327. (originDependency).sourceOrder;
  328. if (
  329. typeof currentSourceOrder === "number" &&
  330. typeof originSourceOrder === "number"
  331. ) {
  332. // src/index.js
  333. // import { c } from "lib/c" -> c = 0
  334. // import { a } from "lib/a" -> a = 1.0 = 1(main) + 0.0(sub)
  335. // import { b } from "lib/b" -> b = 1.1 = 1(main) + 0.1(sub)
  336. // import { d } from "lib/d" -> d = 2
  337. this._dependencySourceOrderMap.set(dependency, {
  338. main: currentSourceOrder,
  339. sub: originSourceOrder
  340. });
  341. // Save for later batch sorting
  342. this._modulesNeedingSort.add(parentModule);
  343. }
  344. }
  345. /**
  346. * Finish update parent.
  347. * @returns {void}
  348. */
  349. finishUpdateParent() {
  350. if (this._modulesNeedingSort.size === 0) {
  351. return;
  352. }
  353. for (const mod of this._modulesNeedingSort) {
  354. // If dependencies like HarmonyImportSideEffectDependency and HarmonyImportSpecifierDependency have a SourceOrder,
  355. // we sort based on it; otherwise, we preserve the original order.
  356. sortWithSourceOrder(
  357. mod.dependencies,
  358. this._dependencySourceOrderMap,
  359. (dep, index) => this.setParentDependenciesBlockIndex(dep, index)
  360. );
  361. }
  362. this._modulesNeedingSort.clear();
  363. }
  364. /**
  365. * Removes connection.
  366. * @param {Dependency} dependency the referencing dependency
  367. * @returns {void}
  368. */
  369. removeConnection(dependency) {
  370. const connection =
  371. /** @type {ModuleGraphConnection} */
  372. (this.getConnection(dependency));
  373. const targetMgm = this._getModuleGraphModule(connection.module);
  374. targetMgm.incomingConnections.delete(connection);
  375. const originMgm = this._getModuleGraphModule(
  376. /** @type {Module} */ (connection.originModule)
  377. );
  378. /** @type {OutgoingConnections} */
  379. (originMgm.outgoingConnections).delete(connection);
  380. this._dependencyMap.set(dependency, null);
  381. }
  382. /**
  383. * Removes every outgoing connection of `module` whose dependency is in
  384. * `staleDependencies`, including inactive ones left by `updateModule`
  385. * re-targeting (which the dependency-keyed `removeConnection` misses). Needed
  386. * when a module is rebuilt against a persisted graph so stale connections don't
  387. * linger in the old target's incoming set and crash seal-time plugins.
  388. * @param {Module} module the rebuilt origin module
  389. * @param {Set<Dependency>} staleDependencies dependencies replaced by the rebuild
  390. * @returns {void}
  391. */
  392. _removeStaleOutgoingConnections(module, staleDependencies) {
  393. const mgm = this._getModuleGraphModule(module);
  394. const outgoing = mgm.outgoingConnections;
  395. if (outgoing === undefined) return;
  396. for (const connection of outgoing) {
  397. if (
  398. !staleDependencies.has(
  399. /** @type {Dependency} */ (connection.dependency)
  400. )
  401. ) {
  402. continue;
  403. }
  404. outgoing.delete(connection);
  405. if (connection.module !== null) {
  406. this._getModuleGraphModule(
  407. connection.module
  408. ).incomingConnections.delete(connection);
  409. }
  410. }
  411. }
  412. /**
  413. * Assigns `module`'s pending outgoing connections into the dependency map by
  414. * origin. `getConnection` normally does this lazily keyed by a dependency's
  415. * PARENT module; an incremental barrel un-lazy wires a re-export target from
  416. * the importer's walk, so the export dep's parent differs from its origin
  417. * barrel and the lazy flush never reaches it. Flush by origin to fix that.
  418. * @param {Module} module the origin module
  419. * @returns {void}
  420. */
  421. _flushUnassignedConnections(module) {
  422. const mgm = this._getModuleGraphModule(module);
  423. const pending = mgm._unassignedConnections;
  424. if (pending === undefined || pending.length === 0) return;
  425. for (const connection of pending) {
  426. this._dependencyMap.set(
  427. /** @type {Dependency} */ (connection.dependency),
  428. connection
  429. );
  430. }
  431. pending.length = 0;
  432. }
  433. /**
  434. * Adds the provided dependency to the module graph.
  435. * @param {Dependency} dependency the referencing dependency
  436. * @param {string} explanation an explanation
  437. * @returns {void}
  438. */
  439. addExplanation(dependency, explanation) {
  440. const connection =
  441. /** @type {ModuleGraphConnection} */
  442. (this.getConnection(dependency));
  443. connection.addExplanation(explanation);
  444. }
  445. /**
  446. * Clones module attributes.
  447. * @param {Module} sourceModule the source module
  448. * @param {Module} targetModule the target module
  449. * @returns {void}
  450. */
  451. cloneModuleAttributes(sourceModule, targetModule) {
  452. const oldMgm = this._getModuleGraphModule(sourceModule);
  453. const newMgm = this._getModuleGraphModule(targetModule);
  454. newMgm.postOrderIndex = oldMgm.postOrderIndex;
  455. newMgm.preOrderIndex = oldMgm.preOrderIndex;
  456. newMgm.depth = oldMgm.depth;
  457. newMgm.exports = oldMgm.exports;
  458. newMgm.async = oldMgm.async;
  459. }
  460. /**
  461. * Removes module attributes.
  462. * @param {Module} module the module
  463. * @returns {void}
  464. */
  465. removeModuleAttributes(module) {
  466. const mgm = this._getModuleGraphModule(module);
  467. mgm.postOrderIndex = null;
  468. mgm.preOrderIndex = null;
  469. mgm.depth = null;
  470. mgm.async = false;
  471. }
  472. /**
  473. * Removes a module from the graph entirely, detaching its connections. Used to
  474. * drop stale runtime modules on an incremental rebuild so the persisted graph
  475. * doesn't accumulate them.
  476. * @param {Module} module the module to remove
  477. * @returns {void}
  478. */
  479. _removeModule(module) {
  480. const mgm = this._moduleMap.get(module);
  481. if (mgm === undefined) return;
  482. if (mgm.outgoingConnections !== undefined) {
  483. for (const connection of mgm.outgoingConnections) {
  484. if (connection.module && connection.module !== module) {
  485. const other = this._moduleMap.get(connection.module);
  486. if (other !== undefined) other.incomingConnections.delete(connection);
  487. }
  488. }
  489. }
  490. for (const connection of mgm.incomingConnections) {
  491. if (connection.originModule && connection.originModule !== module) {
  492. const other = this._moduleMap.get(connection.originModule);
  493. if (other !== undefined && other.outgoingConnections !== undefined) {
  494. other.outgoingConnections.delete(connection);
  495. }
  496. }
  497. }
  498. this._moduleMap.delete(module);
  499. }
  500. /**
  501. * Removes all module attributes.
  502. * @returns {void}
  503. */
  504. removeAllModuleAttributes() {
  505. for (const mgm of this._moduleMap.values()) {
  506. mgm.postOrderIndex = null;
  507. mgm.preOrderIndex = null;
  508. mgm.depth = null;
  509. mgm.async = false;
  510. }
  511. }
  512. /**
  513. * Move module connections.
  514. * @param {Module} oldModule the old referencing module
  515. * @param {Module} newModule the new referencing module
  516. * @param {FilterConnection} filterConnection filter predicate for replacement
  517. * @returns {void}
  518. */
  519. moveModuleConnections(oldModule, newModule, filterConnection) {
  520. if (oldModule === newModule) return;
  521. const oldMgm = this._getModuleGraphModule(oldModule);
  522. const newMgm = this._getModuleGraphModule(newModule);
  523. const journal = this._mutationJournal;
  524. /** @type {ModuleGraphConnection[] | undefined} */
  525. const movedOut = journal ? [] : undefined;
  526. /** @type {ModuleGraphConnection[] | undefined} */
  527. const movedIn = journal ? [] : undefined;
  528. // Outgoing connections
  529. const oldConnections = oldMgm.outgoingConnections;
  530. if (oldConnections !== undefined) {
  531. if (newMgm.outgoingConnections === undefined) {
  532. newMgm.outgoingConnections = new SortableSet();
  533. }
  534. const newConnections = newMgm.outgoingConnections;
  535. for (const connection of oldConnections) {
  536. if (filterConnection(connection)) {
  537. connection.originModule = newModule;
  538. newConnections.add(connection);
  539. oldConnections.delete(connection);
  540. if (movedOut) movedOut.push(connection);
  541. }
  542. }
  543. }
  544. // Incoming connections
  545. const oldConnections2 = oldMgm.incomingConnections;
  546. const newConnections2 = newMgm.incomingConnections;
  547. for (const connection of oldConnections2) {
  548. if (filterConnection(connection)) {
  549. connection.module = newModule;
  550. newConnections2.add(connection);
  551. oldConnections2.delete(connection);
  552. if (movedIn) movedIn.push(connection);
  553. }
  554. }
  555. if (journal) journal.push({ oldModule, newModule, movedOut, movedIn });
  556. }
  557. /**
  558. * Start recording connection moves so they can later be reversed for incremental rebuilds.
  559. * @returns {void}
  560. */
  561. _startMutationJournal() {
  562. this._mutationJournal = [];
  563. }
  564. /**
  565. * Reverse all recorded connection moves, restoring the graph to its pre-seal
  566. * (end-of-make) state, then stop recording (incremental rebuilds).
  567. * @returns {void}
  568. */
  569. _restoreFromMutationJournal() {
  570. const journal = this._mutationJournal;
  571. if (journal === undefined) return;
  572. for (let i = journal.length - 1; i >= 0; i--) {
  573. const { oldModule, newModule, movedOut, movedIn, copied } = journal[i];
  574. const newMgm = this._getModuleGraphModule(newModule);
  575. // copyOutgoingModuleConnections clones connections onto newModule and the
  576. // external targets; undo by deleting the clones (there is no oldModule)
  577. if (copied !== undefined) {
  578. for (const connection of copied) {
  579. if (newMgm.outgoingConnections !== undefined) {
  580. newMgm.outgoingConnections.delete(connection);
  581. }
  582. if (connection.module !== null && connection.module !== undefined) {
  583. this._getModuleGraphModule(
  584. connection.module
  585. ).incomingConnections.delete(connection);
  586. }
  587. }
  588. continue;
  589. }
  590. const oldModuleT = /** @type {Module} */ (oldModule);
  591. const oldMgm = this._getModuleGraphModule(oldModuleT);
  592. if (movedOut !== undefined) {
  593. if (oldMgm.outgoingConnections === undefined) {
  594. oldMgm.outgoingConnections = new SortableSet();
  595. }
  596. for (const connection of movedOut) {
  597. connection.originModule = oldModuleT;
  598. oldMgm.outgoingConnections.add(connection);
  599. if (newMgm.outgoingConnections !== undefined) {
  600. newMgm.outgoingConnections.delete(connection);
  601. }
  602. }
  603. }
  604. if (movedIn !== undefined) {
  605. for (const connection of movedIn) {
  606. connection.module = oldModuleT;
  607. oldMgm.incomingConnections.add(connection);
  608. newMgm.incomingConnections.delete(connection);
  609. }
  610. }
  611. }
  612. this._mutationJournal = undefined;
  613. }
  614. /**
  615. * Copies outgoing module connections.
  616. * @param {Module} oldModule the old referencing module
  617. * @param {Module} newModule the new referencing module
  618. * @param {FilterConnection} filterConnection filter predicate for replacement
  619. * @returns {void}
  620. */
  621. copyOutgoingModuleConnections(oldModule, newModule, filterConnection) {
  622. if (oldModule === newModule) return;
  623. const oldMgm = this._getModuleGraphModule(oldModule);
  624. const newMgm = this._getModuleGraphModule(newModule);
  625. const journal = this._mutationJournal;
  626. /** @type {ModuleGraphConnection[] | undefined} */
  627. const copied = journal ? [] : undefined;
  628. // Outgoing connections
  629. const oldConnections = oldMgm.outgoingConnections;
  630. if (oldConnections !== undefined) {
  631. if (newMgm.outgoingConnections === undefined) {
  632. newMgm.outgoingConnections = new SortableSet();
  633. }
  634. const newConnections = newMgm.outgoingConnections;
  635. for (const connection of oldConnections) {
  636. if (filterConnection(connection)) {
  637. const newConnection = connection.clone();
  638. newConnection.originModule = newModule;
  639. newConnections.add(newConnection);
  640. if (newConnection.module !== undefined) {
  641. const otherMgm = this._getModuleGraphModule(newConnection.module);
  642. otherMgm.incomingConnections.add(newConnection);
  643. }
  644. if (copied) copied.push(newConnection);
  645. }
  646. }
  647. }
  648. if (journal && copied !== undefined && copied.length > 0) {
  649. journal.push({ newModule, copied });
  650. }
  651. }
  652. /**
  653. * Adds the provided module to the module graph.
  654. * @param {Module} module the referenced module
  655. * @param {string} explanation an explanation why it's referenced
  656. * @returns {void}
  657. */
  658. addExtraReason(module, explanation) {
  659. const connections = this._getModuleGraphModule(module).incomingConnections;
  660. connections.add(new ModuleGraphConnection(null, null, module, explanation));
  661. }
  662. /**
  663. * Gets resolved module.
  664. * @param {Dependency} dependency the dependency to look for a referenced module
  665. * @returns {Module | null} the referenced module
  666. */
  667. getResolvedModule(dependency) {
  668. const connection = this.getConnection(dependency);
  669. return connection !== undefined ? connection.resolvedModule : null;
  670. }
  671. /**
  672. * Returns the connection.
  673. * @param {Dependency} dependency the dependency to look for a referenced module
  674. * @returns {ModuleGraphConnection | undefined} the connection
  675. */
  676. getConnection(dependency) {
  677. const connection = this._dependencyMap.get(dependency);
  678. if (connection === undefined) {
  679. const module = this.getParentModule(dependency);
  680. if (module !== undefined) {
  681. const mgm = this._getModuleGraphModule(module);
  682. if (
  683. mgm._unassignedConnections &&
  684. mgm._unassignedConnections.length !== 0
  685. ) {
  686. /** @type {undefined | ModuleGraphConnection} */
  687. let foundConnection;
  688. for (const connection of mgm._unassignedConnections) {
  689. this._dependencyMap.set(
  690. /** @type {Dependency} */ (connection.dependency),
  691. connection
  692. );
  693. if (connection.dependency === dependency) {
  694. foundConnection = connection;
  695. }
  696. }
  697. mgm._unassignedConnections.length = 0;
  698. if (foundConnection !== undefined) {
  699. return foundConnection;
  700. }
  701. }
  702. }
  703. this._dependencyMap.set(dependency, null);
  704. return;
  705. }
  706. return connection === null ? undefined : connection;
  707. }
  708. /**
  709. * Returns the referenced module.
  710. * @param {Dependency} dependency the dependency to look for a referenced module
  711. * @returns {Module | null} the referenced module
  712. */
  713. getModule(dependency) {
  714. const connection = this.getConnection(dependency);
  715. return connection !== undefined ? connection.module : null;
  716. }
  717. /**
  718. * Returns the referencing module.
  719. * @param {Dependency} dependency the dependency to look for a referencing module
  720. * @returns {Module | null} the referencing module
  721. */
  722. getOrigin(dependency) {
  723. const connection = this.getConnection(dependency);
  724. return connection !== undefined ? connection.originModule : null;
  725. }
  726. /**
  727. * Gets resolved origin.
  728. * @param {Dependency} dependency the dependency to look for a referencing module
  729. * @returns {Module | null} the original referencing module
  730. */
  731. getResolvedOrigin(dependency) {
  732. const connection = this.getConnection(dependency);
  733. return connection !== undefined ? connection.resolvedOriginModule : null;
  734. }
  735. /**
  736. * Gets incoming connections.
  737. * @param {Module} module the module
  738. * @returns {Iterable<ModuleGraphConnection>} reasons why a module is included
  739. */
  740. getIncomingConnections(module) {
  741. const connections = this._getModuleGraphModule(module).incomingConnections;
  742. return connections;
  743. }
  744. /**
  745. * Gets outgoing connections.
  746. * @param {Module} module the module
  747. * @returns {Iterable<ModuleGraphConnection>} list of outgoing connections
  748. */
  749. getOutgoingConnections(module) {
  750. const connections = this._getModuleGraphModule(module).outgoingConnections;
  751. return connections === undefined ? EMPTY_SET : connections;
  752. }
  753. /**
  754. * Gets incoming connections by origin module.
  755. * @param {Module} module the module
  756. * @returns {ReadonlyMap<Module | undefined | null, ReadonlyArray<ModuleGraphConnection>>} reasons why a module is included, in a map by source module
  757. */
  758. getIncomingConnectionsByOriginModule(module) {
  759. const connections = this._getModuleGraphModule(module).incomingConnections;
  760. return connections.getFromUnorderedCache(getConnectionsByOriginModule);
  761. }
  762. /**
  763. * Gets outgoing connections by module.
  764. * @param {Module} module the module
  765. * @returns {ReadonlyMap<Module | undefined, ReadonlyArray<ModuleGraphConnection>> | undefined} connections to modules, in a map by module
  766. */
  767. getOutgoingConnectionsByModule(module) {
  768. const connections = this._getModuleGraphModule(module).outgoingConnections;
  769. return connections === undefined
  770. ? undefined
  771. : connections.getFromUnorderedCache(getConnectionsByModule);
  772. }
  773. /**
  774. * Returns the module profile.
  775. * @param {Module} module the module
  776. * @returns {ModuleProfile | undefined} the module profile
  777. */
  778. getProfile(module) {
  779. const mgm = this._getModuleGraphModule(module);
  780. return mgm.profile;
  781. }
  782. /**
  783. * Updates profile using the provided module.
  784. * @param {Module} module the module
  785. * @param {ModuleProfile | undefined} profile the module profile
  786. * @returns {void}
  787. */
  788. setProfile(module, profile) {
  789. const mgm = this._getModuleGraphModule(module);
  790. mgm.profile = profile;
  791. }
  792. /**
  793. * Returns the issuer module.
  794. * @param {Module} module the module
  795. * @returns {Issuer} the issuer module
  796. */
  797. getIssuer(module) {
  798. const mgm = this._getModuleGraphModule(module);
  799. return mgm.issuer;
  800. }
  801. /**
  802. * Updates issuer using the provided module.
  803. * @param {Module} module the module
  804. * @param {Module | null} issuer the issuer module
  805. * @returns {void}
  806. */
  807. setIssuer(module, issuer) {
  808. const mgm = this._getModuleGraphModule(module);
  809. mgm.issuer = issuer;
  810. }
  811. /**
  812. * Sets issuer if unset.
  813. * @param {Module} module the module
  814. * @param {Module | null} issuer the issuer module
  815. * @returns {void}
  816. */
  817. setIssuerIfUnset(module, issuer) {
  818. const mgm = this._getModuleGraphModule(module);
  819. if (mgm.issuer === undefined) mgm.issuer = issuer;
  820. }
  821. /**
  822. * Gets optimization bailout.
  823. * @param {Module} module the module
  824. * @returns {OptimizationBailouts} optimization bailouts
  825. */
  826. getOptimizationBailout(module) {
  827. const mgm = this._getModuleGraphModule(module);
  828. return mgm.optimizationBailout;
  829. }
  830. /**
  831. * Gets provided exports.
  832. * @param {Module} module the module
  833. * @returns {null | true | ExportInfoName[]} the provided exports
  834. */
  835. getProvidedExports(module) {
  836. const mgm = this._getModuleGraphModule(module);
  837. return mgm.exports.getProvidedExports();
  838. }
  839. /**
  840. * Checks whether this module graph is export provided.
  841. * @param {Module} module the module
  842. * @param {ExportInfoName | ExportInfoName[]} exportName a name of an export
  843. * @returns {boolean | null} true, if the export is provided by the module.
  844. * null, if it's unknown.
  845. * false, if it's not provided.
  846. */
  847. isExportProvided(module, exportName) {
  848. const mgm = this._getModuleGraphModule(module);
  849. const result = mgm.exports.isExportProvided(exportName);
  850. return result === undefined ? null : result;
  851. }
  852. /**
  853. * Returns info about the exports.
  854. * @param {Module} module the module
  855. * @returns {ExportsInfo} info about the exports
  856. */
  857. getExportsInfo(module) {
  858. const mgm = this._getModuleGraphModule(module);
  859. return mgm.exports;
  860. }
  861. /**
  862. * Returns info about the export.
  863. * @param {Module} module the module
  864. * @param {string} exportName the export
  865. * @returns {InstanceType<ExportInfo>} info about the export
  866. */
  867. getExportInfo(module, exportName) {
  868. const mgm = this._getModuleGraphModule(module);
  869. return mgm.exports.getExportInfo(exportName);
  870. }
  871. /**
  872. * Gets read only export info.
  873. * @param {Module} module the module
  874. * @param {string} exportName the export
  875. * @returns {InstanceType<ExportInfo>} info about the export (do not modify)
  876. */
  877. getReadOnlyExportInfo(module, exportName) {
  878. const mgm = this._getModuleGraphModule(module);
  879. return mgm.exports.getReadOnlyExportInfo(exportName);
  880. }
  881. /**
  882. * Returns the used exports.
  883. * @param {Module} module the module
  884. * @param {RuntimeSpec} runtime the runtime
  885. * @returns {false | true | SortableSet<string> | null} the used exports
  886. * false: module is not used at all.
  887. * true: the module namespace/object export is used.
  888. * SortableSet<string>: these export names are used.
  889. * empty SortableSet<string>: module is used but no export.
  890. * null: unknown, worst case should be assumed.
  891. */
  892. getUsedExports(module, runtime) {
  893. const mgm = this._getModuleGraphModule(module);
  894. return mgm.exports.getUsedExports(runtime);
  895. }
  896. /**
  897. * Gets pre order index.
  898. * @param {Module} module the module
  899. * @returns {number | null} the index of the module
  900. */
  901. getPreOrderIndex(module) {
  902. const mgm = this._getModuleGraphModule(module);
  903. return mgm.preOrderIndex;
  904. }
  905. /**
  906. * Gets post order index.
  907. * @param {Module} module the module
  908. * @returns {number | null} the index of the module
  909. */
  910. getPostOrderIndex(module) {
  911. const mgm = this._getModuleGraphModule(module);
  912. return mgm.postOrderIndex;
  913. }
  914. /**
  915. * Sets pre order index.
  916. * @param {Module} module the module
  917. * @param {number} index the index of the module
  918. * @returns {void}
  919. */
  920. setPreOrderIndex(module, index) {
  921. const mgm = this._getModuleGraphModule(module);
  922. mgm.preOrderIndex = index;
  923. }
  924. /**
  925. * Sets pre order index if unset.
  926. * @param {Module} module the module
  927. * @param {number} index the index of the module
  928. * @returns {boolean} true, if the index was set
  929. */
  930. setPreOrderIndexIfUnset(module, index) {
  931. const mgm = this._getModuleGraphModule(module);
  932. if (mgm.preOrderIndex === null) {
  933. mgm.preOrderIndex = index;
  934. return true;
  935. }
  936. return false;
  937. }
  938. /**
  939. * Sets post order index.
  940. * @param {Module} module the module
  941. * @param {number} index the index of the module
  942. * @returns {void}
  943. */
  944. setPostOrderIndex(module, index) {
  945. const mgm = this._getModuleGraphModule(module);
  946. mgm.postOrderIndex = index;
  947. }
  948. /**
  949. * Sets post order index if unset.
  950. * @param {Module} module the module
  951. * @param {number} index the index of the module
  952. * @returns {boolean} true, if the index was set
  953. */
  954. setPostOrderIndexIfUnset(module, index) {
  955. const mgm = this._getModuleGraphModule(module);
  956. if (mgm.postOrderIndex === null) {
  957. mgm.postOrderIndex = index;
  958. return true;
  959. }
  960. return false;
  961. }
  962. /**
  963. * Returns the depth of the module.
  964. * @param {Module} module the module
  965. * @returns {number | null} the depth of the module
  966. */
  967. getDepth(module) {
  968. const mgm = this._getModuleGraphModule(module);
  969. return mgm.depth;
  970. }
  971. /**
  972. * Updates depth using the provided module.
  973. * @param {Module} module the module
  974. * @param {number} depth the depth of the module
  975. * @returns {void}
  976. */
  977. setDepth(module, depth) {
  978. const mgm = this._getModuleGraphModule(module);
  979. mgm.depth = depth;
  980. }
  981. /**
  982. * Sets depth if lower.
  983. * @param {Module} module the module
  984. * @param {number} depth the depth of the module
  985. * @returns {boolean} true, if the depth was set
  986. */
  987. setDepthIfLower(module, depth) {
  988. const mgm = this._getModuleGraphModule(module);
  989. if (mgm.depth === null || mgm.depth > depth) {
  990. mgm.depth = depth;
  991. return true;
  992. }
  993. return false;
  994. }
  995. /**
  996. * Checks whether this module graph is async.
  997. * @param {Module} module the module
  998. * @returns {boolean} true, if the module is async
  999. */
  1000. isAsync(module) {
  1001. const mgm = this._getModuleGraphModule(module);
  1002. return mgm.async;
  1003. }
  1004. /**
  1005. * Checks whether this module graph is deferred.
  1006. * @param {Module} module the module
  1007. * @returns {boolean} true, if the module is used as a deferred module at least once
  1008. */
  1009. isDeferred(module) {
  1010. if (this.isAsync(module)) return false;
  1011. const connections = this.getIncomingConnections(module);
  1012. for (const connection of connections) {
  1013. if (
  1014. !connection.dependency ||
  1015. !(connection.dependency instanceof HarmonyImportDependency)
  1016. ) {
  1017. continue;
  1018. }
  1019. if (ImportPhaseUtils.isDefer(connection.dependency.phase)) return true;
  1020. }
  1021. return false;
  1022. }
  1023. /**
  1024. * Updates async using the provided module.
  1025. * @param {Module} module the module
  1026. * @returns {void}
  1027. */
  1028. setAsync(module) {
  1029. const mgm = this._getModuleGraphModule(module);
  1030. mgm.async = true;
  1031. }
  1032. /**
  1033. * Returns metadata.
  1034. * @param {MetaKey} thing any thing
  1035. * @returns {Meta} metadata
  1036. */
  1037. getMeta(thing) {
  1038. let meta = this._metaMap.get(thing);
  1039. if (meta === undefined) {
  1040. meta = /** @type {Meta} */ (Object.create(null));
  1041. this._metaMap.set(thing, meta);
  1042. }
  1043. return meta;
  1044. }
  1045. /**
  1046. * Gets meta if existing.
  1047. * @param {MetaKey} thing any thing
  1048. * @returns {Meta | undefined} metadata
  1049. */
  1050. getMetaIfExisting(thing) {
  1051. return this._metaMap.get(thing);
  1052. }
  1053. /**
  1054. * Processes the provided cache stage.
  1055. * @param {string=} cacheStage a persistent stage name for caching
  1056. */
  1057. freeze(cacheStage) {
  1058. this._cache = new WeakTupleMap();
  1059. this._cacheStage = cacheStage;
  1060. }
  1061. unfreeze() {
  1062. this._cache = undefined;
  1063. this._cacheStage = undefined;
  1064. }
  1065. /**
  1066. * Returns computed value or cached.
  1067. * @template {EXPECTED_ANY[]} T
  1068. * @template R
  1069. * @param {(moduleGraph: ModuleGraph, ...args: T) => R} fn computer
  1070. * @param {T} args arguments
  1071. * @returns {R} computed value or cached
  1072. */
  1073. cached(fn, ...args) {
  1074. if (this._cache === undefined) return fn(this, ...args);
  1075. return this._cache.cachedProvide(fn, this, args);
  1076. }
  1077. /**
  1078. * Sets module mem caches.
  1079. * @param {ModuleMemCaches} moduleMemCaches mem caches for modules for better caching
  1080. */
  1081. setModuleMemCaches(moduleMemCaches) {
  1082. this._moduleMemCaches = moduleMemCaches;
  1083. }
  1084. /**
  1085. * Dependency cache provide.
  1086. * @template {Dependency} D
  1087. * @template {EXPECTED_ANY[]} ARGS
  1088. * @template R
  1089. * @param {D} dependency dependency
  1090. * @param {[...ARGS, (moduleGraph: ModuleGraph, dependency: D, ...args: ARGS) => R]} args arguments, last argument is a function called with moduleGraph, dependency, ...args
  1091. * @returns {R} computed value or cached
  1092. */
  1093. dependencyCacheProvide(dependency, ...args) {
  1094. const fn =
  1095. /** @type {(moduleGraph: ModuleGraph, dependency: D, ...args: EXPECTED_ANY[]) => R} */
  1096. (args.pop());
  1097. if (this._moduleMemCaches && this._cacheStage) {
  1098. const memCache = this._moduleMemCaches.get(
  1099. /** @type {Module} */
  1100. (this.getParentModule(dependency))
  1101. );
  1102. if (memCache !== undefined) {
  1103. return memCache.provide(dependency, this._cacheStage, ...args, () =>
  1104. fn(this, dependency, ...args)
  1105. );
  1106. }
  1107. }
  1108. if (this._cache === undefined) return fn(this, dependency, ...args);
  1109. return this._cache.provide(dependency, ...args, () =>
  1110. fn(this, dependency, ...args)
  1111. );
  1112. }
  1113. // TODO remove in webpack 6
  1114. /**
  1115. * Gets module graph for module.
  1116. * @deprecated
  1117. * @param {Module} module the module
  1118. * @param {string} deprecateMessage message for the deprecation message
  1119. * @param {string} deprecationCode code for the deprecation
  1120. * @returns {ModuleGraph} the module graph
  1121. */
  1122. static getModuleGraphForModule(module, deprecateMessage, deprecationCode) {
  1123. const fn = deprecateMap.get(deprecateMessage);
  1124. if (fn) return fn(module);
  1125. const newFn = util.deprecate(
  1126. /**
  1127. * Handles the callback logic for this hook.
  1128. * @param {Module} module the module
  1129. * @returns {ModuleGraph} the module graph
  1130. */
  1131. (module) => {
  1132. const moduleGraph = moduleGraphForModuleMap.get(module);
  1133. if (!moduleGraph) {
  1134. throw new Error(
  1135. `${deprecateMessage}There was no ModuleGraph assigned to the Module for backward-compat (Use the new API)`
  1136. );
  1137. }
  1138. return moduleGraph;
  1139. },
  1140. `${deprecateMessage}: Use new ModuleGraph API`,
  1141. deprecationCode
  1142. );
  1143. deprecateMap.set(deprecateMessage, newFn);
  1144. return newFn(module);
  1145. }
  1146. // TODO remove in webpack 6
  1147. /**
  1148. * Sets module graph for module.
  1149. * @deprecated
  1150. * @param {Module} module the module
  1151. * @param {ModuleGraph} moduleGraph the module graph
  1152. * @returns {void}
  1153. */
  1154. static setModuleGraphForModule(module, moduleGraph) {
  1155. moduleGraphForModuleMap.set(module, moduleGraph);
  1156. }
  1157. // TODO remove in webpack 6
  1158. /**
  1159. * Clear module graph for module.
  1160. * @deprecated
  1161. * @param {Module} module the module
  1162. * @returns {void}
  1163. */
  1164. static clearModuleGraphForModule(module) {
  1165. moduleGraphForModuleMap.delete(module);
  1166. }
  1167. }
  1168. // TODO remove in webpack 6
  1169. /** @type {WeakMap<Module, ModuleGraph>} */
  1170. const moduleGraphForModuleMap = new WeakMap();
  1171. // TODO remove in webpack 6
  1172. /** @type {Map<string, (module: Module) => ModuleGraph>} */
  1173. const deprecateMap = new Map();
  1174. ModuleGraph.ModuleGraphConnection = ModuleGraphConnection;
  1175. module.exports = ModuleGraph;