ModuleConcatenationPlugin.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("neo-async");
  7. const ChunkGraph = require("../ChunkGraph");
  8. const ModuleGraph = require("../ModuleGraph");
  9. const { JS_TYPE } = require("../ModuleSourceTypesConstants");
  10. const { STAGE_DEFAULT } = require("../OptimizationStages");
  11. const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
  12. const { compareModulesByIdentifier } = require("../util/comparators");
  13. const {
  14. filterRuntime,
  15. intersectRuntime,
  16. mergeRuntime,
  17. mergeRuntimeOwned,
  18. runtimeToString
  19. } = require("../util/runtime");
  20. const ConcatenatedModule = require("./ConcatenatedModule");
  21. /** @typedef {import("../Compilation")} Compilation */
  22. /** @typedef {import("../Compiler")} Compiler */
  23. /** @typedef {import("../Module")} Module */
  24. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  25. /** @typedef {import("../RequestShortener")} RequestShortener */
  26. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  27. /**
  28. * @typedef {object} Statistics
  29. * @property {number} cached
  30. * @property {number} alreadyInConfig
  31. * @property {number} invalidModule
  32. * @property {number} incorrectChunks
  33. * @property {number} incorrectDependency
  34. * @property {number} incorrectModuleDependency
  35. * @property {number} incorrectChunksOfImporter
  36. * @property {number} incorrectRuntimeCondition
  37. * @property {number} importerFailed
  38. * @property {number} added
  39. */
  40. /**
  41. * @param {string} msg message
  42. * @returns {string} formatted message
  43. */
  44. const formatBailoutReason = msg => `ModuleConcatenation bailout: ${msg}`;
  45. const PLUGIN_NAME = "ModuleConcatenationPlugin";
  46. class ModuleConcatenationPlugin {
  47. /**
  48. * Apply the plugin
  49. * @param {Compiler} compiler the compiler instance
  50. * @returns {void}
  51. */
  52. apply(compiler) {
  53. const { _backCompat: backCompat } = compiler;
  54. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
  55. if (compilation.moduleMemCaches) {
  56. throw new Error(
  57. "optimization.concatenateModules can't be used with cacheUnaffected as module concatenation is a global effect"
  58. );
  59. }
  60. const moduleGraph = compilation.moduleGraph;
  61. /** @type {Map<Module, string | ((requestShortener: RequestShortener) => string)>} */
  62. const bailoutReasonMap = new Map();
  63. /**
  64. * @param {Module} module the module
  65. * @param {string | ((requestShortener: RequestShortener) => string)} reason the reason
  66. */
  67. const setBailoutReason = (module, reason) => {
  68. setInnerBailoutReason(module, reason);
  69. moduleGraph
  70. .getOptimizationBailout(module)
  71. .push(
  72. typeof reason === "function"
  73. ? rs => formatBailoutReason(reason(rs))
  74. : formatBailoutReason(reason)
  75. );
  76. };
  77. /**
  78. * @param {Module} module the module
  79. * @param {string | ((requestShortener: RequestShortener) => string)} reason the reason
  80. */
  81. const setInnerBailoutReason = (module, reason) => {
  82. bailoutReasonMap.set(module, reason);
  83. };
  84. /**
  85. * @param {Module} module the module
  86. * @param {RequestShortener} requestShortener the request shortener
  87. * @returns {string | ((requestShortener: RequestShortener) => string) | undefined} the reason
  88. */
  89. const getInnerBailoutReason = (module, requestShortener) => {
  90. const reason = bailoutReasonMap.get(module);
  91. if (typeof reason === "function") return reason(requestShortener);
  92. return reason;
  93. };
  94. /**
  95. * @param {Module} module the module
  96. * @param {Module | ((requestShortener: RequestShortener) => string)} problem the problem
  97. * @returns {(requestShortener: RequestShortener) => string} the reason
  98. */
  99. const formatBailoutWarning = (module, problem) => requestShortener => {
  100. if (typeof problem === "function") {
  101. return formatBailoutReason(
  102. `Cannot concat with ${module.readableIdentifier(
  103. requestShortener
  104. )}: ${problem(requestShortener)}`
  105. );
  106. }
  107. const reason = getInnerBailoutReason(module, requestShortener);
  108. const reasonWithPrefix = reason ? `: ${reason}` : "";
  109. if (module === problem) {
  110. return formatBailoutReason(
  111. `Cannot concat with ${module.readableIdentifier(
  112. requestShortener
  113. )}${reasonWithPrefix}`
  114. );
  115. }
  116. return formatBailoutReason(
  117. `Cannot concat with ${module.readableIdentifier(
  118. requestShortener
  119. )} because of ${problem.readableIdentifier(
  120. requestShortener
  121. )}${reasonWithPrefix}`
  122. );
  123. };
  124. compilation.hooks.optimizeChunkModules.tapAsync(
  125. {
  126. name: PLUGIN_NAME,
  127. stage: STAGE_DEFAULT
  128. },
  129. (allChunks, modules, callback) => {
  130. const logger = compilation.getLogger(
  131. "webpack.ModuleConcatenationPlugin"
  132. );
  133. const { chunkGraph, moduleGraph } = compilation;
  134. const relevantModules = [];
  135. const possibleInners = new Set();
  136. const context = {
  137. chunkGraph,
  138. moduleGraph
  139. };
  140. logger.time("select relevant modules");
  141. for (const module of modules) {
  142. let canBeRoot = true;
  143. let canBeInner = true;
  144. const bailoutReason = module.getConcatenationBailoutReason(context);
  145. if (bailoutReason) {
  146. setBailoutReason(module, bailoutReason);
  147. continue;
  148. }
  149. // Must not be an async module
  150. if (moduleGraph.isAsync(module)) {
  151. setBailoutReason(module, "Module is async");
  152. continue;
  153. }
  154. // Must be in strict mode
  155. if (!(/** @type {BuildInfo} */ (module.buildInfo).strict)) {
  156. setBailoutReason(module, "Module is not in strict mode");
  157. continue;
  158. }
  159. // Module must be in any chunk (we don't want to do useless work)
  160. if (chunkGraph.getNumberOfModuleChunks(module) === 0) {
  161. setBailoutReason(module, "Module is not in any chunk");
  162. continue;
  163. }
  164. // Exports must be known (and not dynamic)
  165. const exportsInfo = moduleGraph.getExportsInfo(module);
  166. const relevantExports = exportsInfo.getRelevantExports(undefined);
  167. const unknownReexports = relevantExports.filter(
  168. exportInfo =>
  169. exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph)
  170. );
  171. if (unknownReexports.length > 0) {
  172. setBailoutReason(
  173. module,
  174. `Reexports in this module do not have a static target (${Array.from(
  175. unknownReexports,
  176. exportInfo =>
  177. `${
  178. exportInfo.name || "other exports"
  179. }: ${exportInfo.getUsedInfo()}`
  180. ).join(", ")})`
  181. );
  182. continue;
  183. }
  184. // Root modules must have a static list of exports
  185. const unknownProvidedExports = relevantExports.filter(
  186. exportInfo => exportInfo.provided !== true
  187. );
  188. if (unknownProvidedExports.length > 0) {
  189. setBailoutReason(
  190. module,
  191. `List of module exports is dynamic (${Array.from(
  192. unknownProvidedExports,
  193. exportInfo =>
  194. `${
  195. exportInfo.name || "other exports"
  196. }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}`
  197. ).join(", ")})`
  198. );
  199. canBeRoot = false;
  200. }
  201. // Module must not be an entry point
  202. if (chunkGraph.isEntryModule(module)) {
  203. setInnerBailoutReason(module, "Module is an entry point");
  204. canBeInner = false;
  205. }
  206. if (moduleGraph.isDeferred(module)) {
  207. setInnerBailoutReason(module, "Module is deferred");
  208. canBeInner = false;
  209. }
  210. if (canBeRoot) relevantModules.push(module);
  211. if (canBeInner) possibleInners.add(module);
  212. }
  213. logger.timeEnd("select relevant modules");
  214. logger.debug(
  215. `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules`
  216. );
  217. // sort by depth
  218. // modules with lower depth are more likely suited as roots
  219. // this improves performance, because modules already selected as inner are skipped
  220. logger.time("sort relevant modules");
  221. relevantModules.sort(
  222. (a, b) =>
  223. /** @type {number} */ (moduleGraph.getDepth(a)) -
  224. /** @type {number} */ (moduleGraph.getDepth(b))
  225. );
  226. logger.timeEnd("sort relevant modules");
  227. /** @type {Statistics} */
  228. const stats = {
  229. cached: 0,
  230. alreadyInConfig: 0,
  231. invalidModule: 0,
  232. incorrectChunks: 0,
  233. incorrectDependency: 0,
  234. incorrectModuleDependency: 0,
  235. incorrectChunksOfImporter: 0,
  236. incorrectRuntimeCondition: 0,
  237. importerFailed: 0,
  238. added: 0
  239. };
  240. let statsCandidates = 0;
  241. let statsSizeSum = 0;
  242. let statsEmptyConfigurations = 0;
  243. logger.time("find modules to concatenate");
  244. const concatConfigurations = [];
  245. const usedAsInner = new Set();
  246. for (const currentRoot of relevantModules) {
  247. // when used by another configuration as inner:
  248. // the other configuration is better and we can skip this one
  249. // TODO reconsider that when it's only used in a different runtime
  250. if (usedAsInner.has(currentRoot)) continue;
  251. let chunkRuntime;
  252. for (const r of chunkGraph.getModuleRuntimes(currentRoot)) {
  253. chunkRuntime = mergeRuntimeOwned(chunkRuntime, r);
  254. }
  255. const exportsInfo = moduleGraph.getExportsInfo(currentRoot);
  256. const filteredRuntime = filterRuntime(chunkRuntime, r =>
  257. exportsInfo.isModuleUsed(r)
  258. );
  259. const activeRuntime =
  260. filteredRuntime === true
  261. ? chunkRuntime
  262. : filteredRuntime === false
  263. ? undefined
  264. : filteredRuntime;
  265. // create a configuration with the root
  266. const currentConfiguration = new ConcatConfiguration(
  267. currentRoot,
  268. activeRuntime
  269. );
  270. // cache failures to add modules
  271. const failureCache = new Map();
  272. // potential optional import candidates
  273. /** @type {Set<Module>} */
  274. const candidates = new Set();
  275. // try to add all imports
  276. for (const imp of this._getImports(
  277. compilation,
  278. currentRoot,
  279. activeRuntime
  280. )) {
  281. candidates.add(imp);
  282. }
  283. for (const imp of candidates) {
  284. const impCandidates = new Set();
  285. const problem = this._tryToAdd(
  286. compilation,
  287. currentConfiguration,
  288. imp,
  289. chunkRuntime,
  290. activeRuntime,
  291. possibleInners,
  292. impCandidates,
  293. failureCache,
  294. chunkGraph,
  295. true,
  296. stats
  297. );
  298. if (problem) {
  299. failureCache.set(imp, problem);
  300. currentConfiguration.addWarning(imp, problem);
  301. } else {
  302. for (const c of impCandidates) {
  303. candidates.add(c);
  304. }
  305. }
  306. }
  307. statsCandidates += candidates.size;
  308. if (!currentConfiguration.isEmpty()) {
  309. const modules = currentConfiguration.getModules();
  310. statsSizeSum += modules.size;
  311. concatConfigurations.push(currentConfiguration);
  312. for (const module of modules) {
  313. if (module !== currentConfiguration.rootModule) {
  314. usedAsInner.add(module);
  315. }
  316. }
  317. } else {
  318. statsEmptyConfigurations++;
  319. const optimizationBailouts =
  320. moduleGraph.getOptimizationBailout(currentRoot);
  321. for (const warning of currentConfiguration.getWarningsSorted()) {
  322. optimizationBailouts.push(
  323. formatBailoutWarning(warning[0], warning[1])
  324. );
  325. }
  326. }
  327. }
  328. logger.timeEnd("find modules to concatenate");
  329. logger.debug(
  330. `${
  331. concatConfigurations.length
  332. } successful concat configurations (avg size: ${
  333. statsSizeSum / concatConfigurations.length
  334. }), ${statsEmptyConfigurations} bailed out completely`
  335. );
  336. logger.debug(
  337. `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)`
  338. );
  339. // HACK: Sort configurations by length and start with the longest one
  340. // to get the biggest groups possible. Used modules are marked with usedModules
  341. // TODO: Allow to reuse existing configuration while trying to add dependencies.
  342. // This would improve performance. O(n^2) -> O(n)
  343. logger.time("sort concat configurations");
  344. concatConfigurations.sort((a, b) => b.modules.size - a.modules.size);
  345. logger.timeEnd("sort concat configurations");
  346. const usedModules = new Set();
  347. logger.time("create concatenated modules");
  348. asyncLib.each(
  349. concatConfigurations,
  350. (concatConfiguration, callback) => {
  351. const rootModule = concatConfiguration.rootModule;
  352. // Avoid overlapping configurations
  353. // TODO: remove this when todo above is fixed
  354. if (usedModules.has(rootModule)) return callback();
  355. const modules = concatConfiguration.getModules();
  356. for (const m of modules) {
  357. usedModules.add(m);
  358. }
  359. // Create a new ConcatenatedModule
  360. ConcatenatedModule.getCompilationHooks(compilation);
  361. const newModule = ConcatenatedModule.create(
  362. rootModule,
  363. modules,
  364. concatConfiguration.runtime,
  365. compilation,
  366. compiler.root,
  367. compilation.outputOptions.hashFunction
  368. );
  369. const build = () => {
  370. newModule.build(
  371. compiler.options,
  372. compilation,
  373. /** @type {EXPECTED_ANY} */
  374. (null),
  375. /** @type {EXPECTED_ANY} */
  376. (null),
  377. err => {
  378. if (err) {
  379. if (!err.module) {
  380. err.module = newModule;
  381. }
  382. return callback(err);
  383. }
  384. integrate();
  385. }
  386. );
  387. };
  388. const integrate = () => {
  389. if (backCompat) {
  390. ChunkGraph.setChunkGraphForModule(newModule, chunkGraph);
  391. ModuleGraph.setModuleGraphForModule(newModule, moduleGraph);
  392. }
  393. for (const warning of concatConfiguration.getWarningsSorted()) {
  394. moduleGraph
  395. .getOptimizationBailout(newModule)
  396. .push(formatBailoutWarning(warning[0], warning[1]));
  397. }
  398. moduleGraph.cloneModuleAttributes(rootModule, newModule);
  399. for (const m of modules) {
  400. // add to builtModules when one of the included modules was built
  401. if (compilation.builtModules.has(m)) {
  402. compilation.builtModules.add(newModule);
  403. }
  404. if (m !== rootModule) {
  405. // attach external references to the concatenated module too
  406. moduleGraph.copyOutgoingModuleConnections(
  407. m,
  408. newModule,
  409. c =>
  410. c.originModule === m &&
  411. !(
  412. c.dependency instanceof HarmonyImportDependency &&
  413. modules.has(c.module)
  414. )
  415. );
  416. // remove module from chunk
  417. for (const chunk of chunkGraph.getModuleChunksIterable(
  418. rootModule
  419. )) {
  420. const sourceTypes = chunkGraph.getChunkModuleSourceTypes(
  421. chunk,
  422. m
  423. );
  424. if (sourceTypes.size === 1) {
  425. chunkGraph.disconnectChunkAndModule(chunk, m);
  426. } else {
  427. const newSourceTypes = new Set(sourceTypes);
  428. newSourceTypes.delete(JS_TYPE);
  429. chunkGraph.setChunkModuleSourceTypes(
  430. chunk,
  431. m,
  432. newSourceTypes
  433. );
  434. }
  435. }
  436. }
  437. }
  438. compilation.modules.delete(rootModule);
  439. ChunkGraph.clearChunkGraphForModule(rootModule);
  440. ModuleGraph.clearModuleGraphForModule(rootModule);
  441. // remove module from chunk
  442. chunkGraph.replaceModule(rootModule, newModule);
  443. // replace module references with the concatenated module
  444. moduleGraph.moveModuleConnections(rootModule, newModule, c => {
  445. const otherModule =
  446. c.module === rootModule ? c.originModule : c.module;
  447. const innerConnection =
  448. c.dependency instanceof HarmonyImportDependency &&
  449. modules.has(/** @type {Module} */ (otherModule));
  450. return !innerConnection;
  451. });
  452. // add concatenated module to the compilation
  453. compilation.modules.add(newModule);
  454. callback();
  455. };
  456. build();
  457. },
  458. err => {
  459. logger.timeEnd("create concatenated modules");
  460. process.nextTick(callback.bind(null, err));
  461. }
  462. );
  463. }
  464. );
  465. });
  466. }
  467. /**
  468. * @param {Compilation} compilation the compilation
  469. * @param {Module} module the module to be added
  470. * @param {RuntimeSpec} runtime the runtime scope
  471. * @returns {Set<Module>} the imported modules
  472. */
  473. _getImports(compilation, module, runtime) {
  474. const moduleGraph = compilation.moduleGraph;
  475. const set = new Set();
  476. for (const dep of module.dependencies) {
  477. // Get reference info only for harmony Dependencies
  478. if (!(dep instanceof HarmonyImportDependency)) continue;
  479. const connection = moduleGraph.getConnection(dep);
  480. // Reference is valid and has a module
  481. if (
  482. !connection ||
  483. !connection.module ||
  484. !connection.isTargetActive(runtime)
  485. ) {
  486. continue;
  487. }
  488. const importedNames = compilation.getDependencyReferencedExports(
  489. dep,
  490. undefined
  491. );
  492. if (
  493. importedNames.every(i =>
  494. Array.isArray(i) ? i.length > 0 : i.name.length > 0
  495. ) ||
  496. Array.isArray(moduleGraph.getProvidedExports(module))
  497. ) {
  498. set.add(connection.module);
  499. }
  500. }
  501. return set;
  502. }
  503. /**
  504. * @param {Compilation} compilation webpack compilation
  505. * @param {ConcatConfiguration} config concat configuration (will be modified when added)
  506. * @param {Module} module the module to be added
  507. * @param {RuntimeSpec} runtime the runtime scope of the generated code
  508. * @param {RuntimeSpec} activeRuntime the runtime scope of the root module
  509. * @param {Set<Module>} possibleModules modules that are candidates
  510. * @param {Set<Module>} candidates list of potential candidates (will be added to)
  511. * @param {Map<Module, Module | ((requestShortener: RequestShortener) => string)>} failureCache cache for problematic modules to be more performant
  512. * @param {ChunkGraph} chunkGraph the chunk graph
  513. * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails
  514. * @param {Statistics} statistics gathering metrics
  515. * @returns {null | Module | ((requestShortener: RequestShortener) => string)} the problematic module
  516. */
  517. _tryToAdd(
  518. compilation,
  519. config,
  520. module,
  521. runtime,
  522. activeRuntime,
  523. possibleModules,
  524. candidates,
  525. failureCache,
  526. chunkGraph,
  527. avoidMutateOnFailure,
  528. statistics
  529. ) {
  530. const cacheEntry = failureCache.get(module);
  531. if (cacheEntry) {
  532. statistics.cached++;
  533. return cacheEntry;
  534. }
  535. // Already added?
  536. if (config.has(module)) {
  537. statistics.alreadyInConfig++;
  538. return null;
  539. }
  540. // Not possible to add?
  541. if (!possibleModules.has(module)) {
  542. statistics.invalidModule++;
  543. failureCache.set(module, module); // cache failures for performance
  544. return module;
  545. }
  546. // Module must be in the correct chunks
  547. const missingChunks = [
  548. ...chunkGraph.getModuleChunksIterable(config.rootModule)
  549. ].filter(chunk => !chunkGraph.isModuleInChunk(module, chunk));
  550. if (missingChunks.length > 0) {
  551. /**
  552. * @param {RequestShortener} requestShortener request shortener
  553. * @returns {string} problem description
  554. */
  555. const problem = requestShortener => {
  556. const missingChunksList = [
  557. ...new Set(
  558. missingChunks.map(chunk => chunk.name || "unnamed chunk(s)")
  559. )
  560. ].sort();
  561. const chunks = [
  562. ...new Set(
  563. [...chunkGraph.getModuleChunksIterable(module)].map(
  564. chunk => chunk.name || "unnamed chunk(s)"
  565. )
  566. )
  567. ].sort();
  568. return `Module ${module.readableIdentifier(
  569. requestShortener
  570. )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join(
  571. ", "
  572. )}, module is in chunk(s) ${chunks.join(", ")})`;
  573. };
  574. statistics.incorrectChunks++;
  575. failureCache.set(module, problem); // cache failures for performance
  576. return problem;
  577. }
  578. const moduleGraph = compilation.moduleGraph;
  579. const incomingConnections =
  580. moduleGraph.getIncomingConnectionsByOriginModule(module);
  581. const incomingConnectionsFromNonModules =
  582. incomingConnections.get(null) || incomingConnections.get(undefined);
  583. if (incomingConnectionsFromNonModules) {
  584. const activeNonModulesConnections =
  585. incomingConnectionsFromNonModules.filter(connection =>
  586. // We are not interested in inactive connections
  587. // or connections without dependency
  588. connection.isActive(runtime)
  589. );
  590. if (activeNonModulesConnections.length > 0) {
  591. /**
  592. * @param {RequestShortener} requestShortener request shortener
  593. * @returns {string} problem description
  594. */
  595. const problem = requestShortener => {
  596. const importingExplanations = new Set(
  597. activeNonModulesConnections.map(c => c.explanation).filter(Boolean)
  598. );
  599. const explanations = [...importingExplanations].sort();
  600. return `Module ${module.readableIdentifier(
  601. requestShortener
  602. )} is referenced ${
  603. explanations.length > 0
  604. ? `by: ${explanations.join(", ")}`
  605. : "in an unsupported way"
  606. }`;
  607. };
  608. statistics.incorrectDependency++;
  609. failureCache.set(module, problem); // cache failures for performance
  610. return problem;
  611. }
  612. }
  613. /** @type {Map<Module, readonly ModuleGraph.ModuleGraphConnection[]>} */
  614. const incomingConnectionsFromModules = new Map();
  615. for (const [originModule, connections] of incomingConnections) {
  616. if (originModule) {
  617. // Ignore connection from orphan modules
  618. if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue;
  619. // We don't care for connections from other runtimes
  620. let originRuntime;
  621. for (const r of chunkGraph.getModuleRuntimes(originModule)) {
  622. originRuntime = mergeRuntimeOwned(originRuntime, r);
  623. }
  624. if (!intersectRuntime(runtime, originRuntime)) continue;
  625. // We are not interested in inactive connections
  626. const activeConnections = connections.filter(connection =>
  627. connection.isActive(runtime)
  628. );
  629. if (activeConnections.length > 0) {
  630. incomingConnectionsFromModules.set(originModule, activeConnections);
  631. }
  632. }
  633. }
  634. const incomingModules = [...incomingConnectionsFromModules.keys()];
  635. // Module must be in the same chunks like the referencing module
  636. const otherChunkModules = incomingModules.filter(originModule => {
  637. for (const chunk of chunkGraph.getModuleChunksIterable(
  638. config.rootModule
  639. )) {
  640. if (!chunkGraph.isModuleInChunk(originModule, chunk)) {
  641. return true;
  642. }
  643. }
  644. return false;
  645. });
  646. if (otherChunkModules.length > 0) {
  647. /**
  648. * @param {RequestShortener} requestShortener request shortener
  649. * @returns {string} problem description
  650. */
  651. const problem = requestShortener => {
  652. const names = otherChunkModules
  653. .map(m => m.readableIdentifier(requestShortener))
  654. .sort();
  655. return `Module ${module.readableIdentifier(
  656. requestShortener
  657. )} is referenced from different chunks by these modules: ${names.join(
  658. ", "
  659. )}`;
  660. };
  661. statistics.incorrectChunksOfImporter++;
  662. failureCache.set(module, problem); // cache failures for performance
  663. return problem;
  664. }
  665. /** @type {Map<Module, readonly ModuleGraph.ModuleGraphConnection[]>} */
  666. const nonHarmonyConnections = new Map();
  667. for (const [originModule, connections] of incomingConnectionsFromModules) {
  668. const selected = connections.filter(
  669. connection =>
  670. !connection.dependency ||
  671. !(connection.dependency instanceof HarmonyImportDependency)
  672. );
  673. if (selected.length > 0) {
  674. nonHarmonyConnections.set(originModule, connections);
  675. }
  676. }
  677. if (nonHarmonyConnections.size > 0) {
  678. /**
  679. * @param {RequestShortener} requestShortener request shortener
  680. * @returns {string} problem description
  681. */
  682. const problem = requestShortener => {
  683. const names = [...nonHarmonyConnections]
  684. .map(
  685. ([originModule, connections]) =>
  686. `${originModule.readableIdentifier(
  687. requestShortener
  688. )} (referenced with ${[
  689. ...new Set(
  690. connections
  691. .map(c => c.dependency && c.dependency.type)
  692. .filter(Boolean)
  693. )
  694. ]
  695. .sort()
  696. .join(", ")})`
  697. )
  698. .sort();
  699. return `Module ${module.readableIdentifier(
  700. requestShortener
  701. )} is referenced from these modules with unsupported syntax: ${names.join(
  702. ", "
  703. )}`;
  704. };
  705. statistics.incorrectModuleDependency++;
  706. failureCache.set(module, problem); // cache failures for performance
  707. return problem;
  708. }
  709. if (runtime !== undefined && typeof runtime !== "string") {
  710. // Module must be consistently referenced in the same runtimes
  711. /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */
  712. const otherRuntimeConnections = [];
  713. outer: for (const [
  714. originModule,
  715. connections
  716. ] of incomingConnectionsFromModules) {
  717. /** @type {false | RuntimeSpec} */
  718. let currentRuntimeCondition = false;
  719. for (const connection of connections) {
  720. const runtimeCondition = filterRuntime(runtime, runtime =>
  721. connection.isTargetActive(runtime)
  722. );
  723. if (runtimeCondition === false) continue;
  724. if (runtimeCondition === true) continue outer;
  725. currentRuntimeCondition =
  726. currentRuntimeCondition !== false
  727. ? mergeRuntime(currentRuntimeCondition, runtimeCondition)
  728. : runtimeCondition;
  729. }
  730. if (currentRuntimeCondition !== false) {
  731. otherRuntimeConnections.push({
  732. originModule,
  733. runtimeCondition: currentRuntimeCondition
  734. });
  735. }
  736. }
  737. if (otherRuntimeConnections.length > 0) {
  738. /**
  739. * @param {RequestShortener} requestShortener request shortener
  740. * @returns {string} problem description
  741. */
  742. const problem = requestShortener =>
  743. `Module ${module.readableIdentifier(
  744. requestShortener
  745. )} is runtime-dependent referenced by these modules: ${Array.from(
  746. otherRuntimeConnections,
  747. ({ originModule, runtimeCondition }) =>
  748. `${originModule.readableIdentifier(
  749. requestShortener
  750. )} (expected runtime ${runtimeToString(
  751. runtime
  752. )}, module is only referenced in ${runtimeToString(
  753. /** @type {RuntimeSpec} */ (runtimeCondition)
  754. )})`
  755. ).join(", ")}`;
  756. statistics.incorrectRuntimeCondition++;
  757. failureCache.set(module, problem); // cache failures for performance
  758. return problem;
  759. }
  760. }
  761. let backup;
  762. if (avoidMutateOnFailure) {
  763. backup = config.snapshot();
  764. }
  765. // Add the module
  766. config.add(module);
  767. incomingModules.sort(compareModulesByIdentifier);
  768. // Every module which depends on the added module must be in the configuration too.
  769. for (const originModule of incomingModules) {
  770. const problem = this._tryToAdd(
  771. compilation,
  772. config,
  773. originModule,
  774. runtime,
  775. activeRuntime,
  776. possibleModules,
  777. candidates,
  778. failureCache,
  779. chunkGraph,
  780. false,
  781. statistics
  782. );
  783. if (problem) {
  784. if (backup !== undefined) config.rollback(backup);
  785. statistics.importerFailed++;
  786. failureCache.set(module, problem); // cache failures for performance
  787. return problem;
  788. }
  789. }
  790. // Add imports to possible candidates list
  791. for (const imp of this._getImports(compilation, module, runtime)) {
  792. candidates.add(imp);
  793. }
  794. statistics.added++;
  795. return null;
  796. }
  797. }
  798. /** @typedef {Module | ((requestShortener: RequestShortener) => string)} Problem */
  799. class ConcatConfiguration {
  800. /**
  801. * @param {Module} rootModule the root module
  802. * @param {RuntimeSpec} runtime the runtime
  803. */
  804. constructor(rootModule, runtime) {
  805. this.rootModule = rootModule;
  806. this.runtime = runtime;
  807. /** @type {Set<Module>} */
  808. this.modules = new Set();
  809. this.modules.add(rootModule);
  810. /** @type {Map<Module, Problem>} */
  811. this.warnings = new Map();
  812. }
  813. /**
  814. * @param {Module} module the module
  815. */
  816. add(module) {
  817. this.modules.add(module);
  818. }
  819. /**
  820. * @param {Module} module the module
  821. * @returns {boolean} true, when the module is in the module set
  822. */
  823. has(module) {
  824. return this.modules.has(module);
  825. }
  826. isEmpty() {
  827. return this.modules.size === 1;
  828. }
  829. /**
  830. * @param {Module} module the module
  831. * @param {Problem} problem the problem
  832. */
  833. addWarning(module, problem) {
  834. this.warnings.set(module, problem);
  835. }
  836. /**
  837. * @returns {Map<Module, Problem>} warnings
  838. */
  839. getWarningsSorted() {
  840. return new Map(
  841. [...this.warnings].sort((a, b) => {
  842. const ai = a[0].identifier();
  843. const bi = b[0].identifier();
  844. if (ai < bi) return -1;
  845. if (ai > bi) return 1;
  846. return 0;
  847. })
  848. );
  849. }
  850. /**
  851. * @returns {Set<Module>} modules as set
  852. */
  853. getModules() {
  854. return this.modules;
  855. }
  856. snapshot() {
  857. return this.modules.size;
  858. }
  859. /**
  860. * @param {number} snapshot snapshot
  861. */
  862. rollback(snapshot) {
  863. const modules = this.modules;
  864. for (const m of modules) {
  865. if (snapshot === 0) {
  866. modules.delete(m);
  867. } else {
  868. snapshot--;
  869. }
  870. }
  871. }
  872. }
  873. module.exports = ModuleConcatenationPlugin;