ConcatenatedModule.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const eslintScope = require("eslint-scope");
  7. const Referencer = require("eslint-scope/lib/referencer");
  8. const { SyncBailHook } = require("tapable");
  9. const {
  10. CachedSource,
  11. ConcatSource,
  12. ReplaceSource
  13. } = require("webpack-sources");
  14. const ConcatenationScope = require("../ConcatenationScope");
  15. const { UsageState } = require("../ExportsInfo");
  16. const Module = require("../Module");
  17. const { JS_TYPES } = require("../ModuleSourceTypesConstants");
  18. const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants");
  19. const RuntimeGlobals = require("../RuntimeGlobals");
  20. const Template = require("../Template");
  21. const { DEFAULTS } = require("../config/defaults");
  22. const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
  23. const JavascriptParser = require("../javascript/JavascriptParser");
  24. const { equals } = require("../util/ArrayHelpers");
  25. const LazySet = require("../util/LazySet");
  26. const { concatComparators } = require("../util/comparators");
  27. const {
  28. RESERVED_NAMES,
  29. findNewName,
  30. addScopeSymbols,
  31. getAllReferences,
  32. getPathInAst,
  33. getUsedNamesInScopeInfo
  34. } = require("../util/concatenate");
  35. const createHash = require("../util/createHash");
  36. const { makePathsRelative } = require("../util/identifier");
  37. const makeSerializable = require("../util/makeSerializable");
  38. const propertyAccess = require("../util/propertyAccess");
  39. const { propertyName } = require("../util/propertyName");
  40. const {
  41. filterRuntime,
  42. intersectRuntime,
  43. mergeRuntimeCondition,
  44. mergeRuntimeConditionNonFalse,
  45. runtimeConditionToString,
  46. subtractRuntimeCondition
  47. } = require("../util/runtime");
  48. /** @typedef {import("eslint-scope").Reference} Reference */
  49. /** @typedef {import("eslint-scope").Scope} Scope */
  50. /** @typedef {import("eslint-scope").Variable} Variable */
  51. /** @typedef {import("webpack-sources").Source} Source */
  52. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  53. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  54. /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
  55. /** @typedef {import("../Compilation")} Compilation */
  56. /** @typedef {import("../Dependency")} Dependency */
  57. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  58. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  59. /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
  60. /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
  61. /** @typedef {import("../Module").BuildCallback} BuildCallback */
  62. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  63. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  64. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  65. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  66. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  67. /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
  68. /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
  69. /** @typedef {import("../Module").SourceTypes} SourceTypes */
  70. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  71. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  72. /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
  73. /** @typedef {import("../ModuleParseError")} ModuleParseError */
  74. /** @typedef {import("../RequestShortener")} RequestShortener */
  75. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  76. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  77. /** @typedef {import("../WebpackError")} WebpackError */
  78. /** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
  79. /** @typedef {import("../javascript/JavascriptParser").Program} Program */
  80. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  81. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  82. /** @typedef {import("../util/Hash")} Hash */
  83. /** @typedef {typeof import("../util/Hash")} HashConstructor */
  84. /** @typedef {import("../util/concatenate").ScopeInfo} ScopeInfo */
  85. /** @typedef {import("../util/concatenate").UsedNames} UsedNames */
  86. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  87. /** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
  88. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  89. /**
  90. * @template T
  91. * @typedef {import("../InitFragment")<T>} InitFragment
  92. */
  93. /**
  94. * @template T
  95. * @typedef {import("../util/comparators").Comparator<T>} Comparator
  96. */
  97. // fix eslint-scope to support class properties correctly
  98. // cspell:word Referencer
  99. const ReferencerClass = /** @type {EXPECTED_ANY} */ (Referencer);
  100. if (!ReferencerClass.prototype.PropertyDefinition) {
  101. ReferencerClass.prototype.PropertyDefinition =
  102. ReferencerClass.prototype.Property;
  103. }
  104. /**
  105. * @typedef {object} ReexportInfo
  106. * @property {Module} module
  107. * @property {string[]} export
  108. */
  109. /** @typedef {RawBinding | SymbolBinding} Binding */
  110. /**
  111. * @typedef {object} RawBinding
  112. * @property {ModuleInfo} info
  113. * @property {string} rawName
  114. * @property {string=} comment
  115. * @property {string[]} ids
  116. * @property {string[]} exportName
  117. */
  118. /**
  119. * @typedef {object} SymbolBinding
  120. * @property {ConcatenatedModuleInfo} info
  121. * @property {string} name
  122. * @property {string=} comment
  123. * @property {string[]} ids
  124. * @property {string[]} exportName
  125. */
  126. /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */
  127. /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */
  128. /**
  129. * @typedef {object} ConcatenatedModuleInfo
  130. * @property {"concatenated"} type
  131. * @property {Module} module
  132. * @property {number} index
  133. * @property {Program | undefined} ast
  134. * @property {Source | undefined} internalSource
  135. * @property {ReplaceSource | undefined} source
  136. * @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
  137. * @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements
  138. * @property {Scope | undefined} globalScope
  139. * @property {Scope | undefined} moduleScope
  140. * @property {Map<string, string>} internalNames
  141. * @property {Map<string, string> | undefined} exportMap
  142. * @property {Map<string, string> | undefined} rawExportMap
  143. * @property {string=} namespaceExportSymbol
  144. * @property {string | undefined} namespaceObjectName
  145. * @property {boolean} interopNamespaceObjectUsed
  146. * @property {string | undefined} interopNamespaceObjectName
  147. * @property {boolean} interopNamespaceObject2Used
  148. * @property {string | undefined} interopNamespaceObject2Name
  149. * @property {boolean} interopDefaultAccessUsed
  150. * @property {string | undefined} interopDefaultAccessName
  151. */
  152. /**
  153. * @typedef {object} ExternalModuleInfo
  154. * @property {"external"} type
  155. * @property {Module} module
  156. * @property {RuntimeSpec | boolean} runtimeCondition
  157. * @property {number} index
  158. * @property {string | undefined} name
  159. * @property {boolean} interopNamespaceObjectUsed
  160. * @property {string | undefined} interopNamespaceObjectName
  161. * @property {boolean} interopNamespaceObject2Used
  162. * @property {string | undefined} interopNamespaceObject2Name
  163. * @property {boolean} interopDefaultAccessUsed
  164. * @property {string | undefined} interopDefaultAccessName
  165. */
  166. /**
  167. * @typedef {object} ReferenceToModuleInfo
  168. * @property {"reference"} type
  169. * @property {RuntimeSpec | boolean} runtimeCondition
  170. * @property {ModuleInfo} target
  171. */
  172. /**
  173. * @template T
  174. * @param {string} property property
  175. * @param {function(T[keyof T], T[keyof T]): 0 | 1 | -1} comparator comparator
  176. * @returns {Comparator<T>} comparator
  177. */
  178. const createComparator = (property, comparator) => (a, b) =>
  179. comparator(
  180. a[/** @type {keyof T} */ (property)],
  181. b[/** @type {keyof T} */ (property)]
  182. );
  183. /**
  184. * @param {number} a a
  185. * @param {number} b b
  186. * @returns {0 | 1 | -1} result
  187. */
  188. const compareNumbers = (a, b) => {
  189. if (Number.isNaN(a)) {
  190. if (!Number.isNaN(b)) {
  191. return 1;
  192. }
  193. } else {
  194. if (Number.isNaN(b)) {
  195. return -1;
  196. }
  197. if (a !== b) {
  198. return a < b ? -1 : 1;
  199. }
  200. }
  201. return 0;
  202. };
  203. const bySourceOrder = createComparator("sourceOrder", compareNumbers);
  204. const byRangeStart = createComparator("rangeStart", compareNumbers);
  205. /**
  206. * @param {Iterable<string>} iterable iterable object
  207. * @returns {string} joined iterable object
  208. */
  209. const joinIterableWithComma = iterable => {
  210. // This is more performant than Array.from().join(", ")
  211. // as it doesn't create an array
  212. let str = "";
  213. let first = true;
  214. for (const item of iterable) {
  215. if (first) {
  216. first = false;
  217. } else {
  218. str += ", ";
  219. }
  220. str += item;
  221. }
  222. return str;
  223. };
  224. /**
  225. * @typedef {object} ConcatenationEntry
  226. * @property {"concatenated" | "external"} type
  227. * @property {Module} module
  228. * @property {RuntimeSpec | boolean} runtimeCondition
  229. */
  230. /**
  231. * @param {ModuleGraph} moduleGraph the module graph
  232. * @param {ModuleInfo} info module info
  233. * @param {string[]} exportName exportName
  234. * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap
  235. * @param {RuntimeSpec} runtime for which runtime
  236. * @param {RequestShortener} requestShortener the request shortener
  237. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  238. * @param {Set<ConcatenatedModuleInfo>} neededNamespaceObjects modules for which a namespace object should be generated
  239. * @param {boolean} asCall asCall
  240. * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
  241. * @param {boolean | undefined} asiSafe asiSafe
  242. * @param {Set<ExportInfo>} alreadyVisited alreadyVisited
  243. * @returns {Binding} the final variable
  244. */
  245. const getFinalBinding = (
  246. moduleGraph,
  247. info,
  248. exportName,
  249. moduleToInfoMap,
  250. runtime,
  251. requestShortener,
  252. runtimeTemplate,
  253. neededNamespaceObjects,
  254. asCall,
  255. strictHarmonyModule,
  256. asiSafe,
  257. alreadyVisited = new Set()
  258. ) => {
  259. const exportsType = info.module.getExportsType(
  260. moduleGraph,
  261. strictHarmonyModule
  262. );
  263. if (exportName.length === 0) {
  264. switch (exportsType) {
  265. case "default-only":
  266. info.interopNamespaceObject2Used = true;
  267. return {
  268. info,
  269. rawName: /** @type {string} */ (info.interopNamespaceObject2Name),
  270. ids: exportName,
  271. exportName
  272. };
  273. case "default-with-named":
  274. info.interopNamespaceObjectUsed = true;
  275. return {
  276. info,
  277. rawName: /** @type {string} */ (info.interopNamespaceObjectName),
  278. ids: exportName,
  279. exportName
  280. };
  281. case "namespace":
  282. case "dynamic":
  283. break;
  284. default:
  285. throw new Error(`Unexpected exportsType ${exportsType}`);
  286. }
  287. } else {
  288. switch (exportsType) {
  289. case "namespace":
  290. break;
  291. case "default-with-named":
  292. switch (exportName[0]) {
  293. case "default":
  294. exportName = exportName.slice(1);
  295. break;
  296. case "__esModule":
  297. return {
  298. info,
  299. rawName: "/* __esModule */true",
  300. ids: exportName.slice(1),
  301. exportName
  302. };
  303. }
  304. break;
  305. case "default-only": {
  306. const exportId = exportName[0];
  307. if (exportId === "__esModule") {
  308. return {
  309. info,
  310. rawName: "/* __esModule */true",
  311. ids: exportName.slice(1),
  312. exportName
  313. };
  314. }
  315. exportName = exportName.slice(1);
  316. if (exportId !== "default") {
  317. return {
  318. info,
  319. rawName:
  320. "/* non-default import from default-exporting module */undefined",
  321. ids: exportName,
  322. exportName
  323. };
  324. }
  325. break;
  326. }
  327. case "dynamic":
  328. switch (exportName[0]) {
  329. case "default": {
  330. exportName = exportName.slice(1);
  331. info.interopDefaultAccessUsed = true;
  332. const defaultExport = asCall
  333. ? `${info.interopDefaultAccessName}()`
  334. : asiSafe
  335. ? `(${info.interopDefaultAccessName}())`
  336. : asiSafe === false
  337. ? `;(${info.interopDefaultAccessName}())`
  338. : `${info.interopDefaultAccessName}.a`;
  339. return {
  340. info,
  341. rawName: defaultExport,
  342. ids: exportName,
  343. exportName
  344. };
  345. }
  346. case "__esModule":
  347. return {
  348. info,
  349. rawName: "/* __esModule */true",
  350. ids: exportName.slice(1),
  351. exportName
  352. };
  353. }
  354. break;
  355. default:
  356. throw new Error(`Unexpected exportsType ${exportsType}`);
  357. }
  358. }
  359. if (exportName.length === 0) {
  360. switch (info.type) {
  361. case "concatenated":
  362. neededNamespaceObjects.add(info);
  363. return {
  364. info,
  365. rawName:
  366. /** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
  367. (info.namespaceObjectName),
  368. ids: exportName,
  369. exportName
  370. };
  371. case "external":
  372. return {
  373. info,
  374. rawName:
  375. /** @type {NonNullable<ExternalModuleInfo["name"]>} */
  376. (info.name),
  377. ids: exportName,
  378. exportName
  379. };
  380. }
  381. }
  382. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  383. const exportInfo = exportsInfo.getExportInfo(exportName[0]);
  384. if (alreadyVisited.has(exportInfo)) {
  385. return {
  386. info,
  387. rawName: "/* circular reexport */ Object(function x() { x() }())",
  388. ids: [],
  389. exportName
  390. };
  391. }
  392. alreadyVisited.add(exportInfo);
  393. switch (info.type) {
  394. case "concatenated": {
  395. const exportId = exportName[0];
  396. if (exportInfo.provided === false) {
  397. // It's not provided, but it could be on the prototype
  398. neededNamespaceObjects.add(info);
  399. return {
  400. info,
  401. rawName: /** @type {string} */ (info.namespaceObjectName),
  402. ids: exportName,
  403. exportName
  404. };
  405. }
  406. const directExport = info.exportMap && info.exportMap.get(exportId);
  407. if (directExport) {
  408. const usedName = /** @type {string[]} */ (
  409. exportsInfo.getUsedName(exportName, runtime)
  410. );
  411. if (!usedName) {
  412. return {
  413. info,
  414. rawName: "/* unused export */ undefined",
  415. ids: exportName.slice(1),
  416. exportName
  417. };
  418. }
  419. return {
  420. info,
  421. name: directExport,
  422. ids: usedName.slice(1),
  423. exportName
  424. };
  425. }
  426. const rawExport = info.rawExportMap && info.rawExportMap.get(exportId);
  427. if (rawExport) {
  428. return {
  429. info,
  430. rawName: rawExport,
  431. ids: exportName.slice(1),
  432. exportName
  433. };
  434. }
  435. const reexport = exportInfo.findTarget(moduleGraph, module =>
  436. moduleToInfoMap.has(module)
  437. );
  438. if (reexport === false) {
  439. throw new Error(
  440. `Target module of reexport from '${info.module.readableIdentifier(
  441. requestShortener
  442. )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from(
  443. moduleToInfoMap,
  444. ([m, info]) =>
  445. ` * ${info.type} ${m.readableIdentifier(requestShortener)}`
  446. ).join("\n")}`
  447. );
  448. }
  449. if (reexport) {
  450. const refInfo = moduleToInfoMap.get(reexport.module);
  451. return getFinalBinding(
  452. moduleGraph,
  453. /** @type {ModuleInfo} */ (refInfo),
  454. reexport.export
  455. ? [...reexport.export, ...exportName.slice(1)]
  456. : exportName.slice(1),
  457. moduleToInfoMap,
  458. runtime,
  459. requestShortener,
  460. runtimeTemplate,
  461. neededNamespaceObjects,
  462. asCall,
  463. /** @type {BuildMeta} */
  464. (info.module.buildMeta).strictHarmonyModule,
  465. asiSafe,
  466. alreadyVisited
  467. );
  468. }
  469. if (info.namespaceExportSymbol) {
  470. const usedName = /** @type {string[]} */ (
  471. exportsInfo.getUsedName(exportName, runtime)
  472. );
  473. return {
  474. info,
  475. rawName: /** @type {string} */ (info.namespaceObjectName),
  476. ids: usedName,
  477. exportName
  478. };
  479. }
  480. throw new Error(
  481. `Cannot get final name for export '${exportName.join(
  482. "."
  483. )}' of ${info.module.readableIdentifier(requestShortener)}`
  484. );
  485. }
  486. case "external": {
  487. const used = /** @type {string[]} */ (
  488. exportsInfo.getUsedName(exportName, runtime)
  489. );
  490. if (!used) {
  491. return {
  492. info,
  493. rawName: "/* unused export */ undefined",
  494. ids: exportName.slice(1),
  495. exportName
  496. };
  497. }
  498. const comment = equals(used, exportName)
  499. ? ""
  500. : Template.toNormalComment(`${exportName.join(".")}`);
  501. return { info, rawName: info.name + comment, ids: used, exportName };
  502. }
  503. }
  504. };
  505. /**
  506. * @param {ModuleGraph} moduleGraph the module graph
  507. * @param {ModuleInfo} info module info
  508. * @param {string[]} exportName exportName
  509. * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap
  510. * @param {RuntimeSpec} runtime for which runtime
  511. * @param {RequestShortener} requestShortener the request shortener
  512. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  513. * @param {Set<ConcatenatedModuleInfo>} neededNamespaceObjects modules for which a namespace object should be generated
  514. * @param {boolean} asCall asCall
  515. * @param {boolean | undefined} callContext callContext
  516. * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
  517. * @param {boolean | undefined} asiSafe asiSafe
  518. * @returns {string} the final name
  519. */
  520. const getFinalName = (
  521. moduleGraph,
  522. info,
  523. exportName,
  524. moduleToInfoMap,
  525. runtime,
  526. requestShortener,
  527. runtimeTemplate,
  528. neededNamespaceObjects,
  529. asCall,
  530. callContext,
  531. strictHarmonyModule,
  532. asiSafe
  533. ) => {
  534. const binding = getFinalBinding(
  535. moduleGraph,
  536. info,
  537. exportName,
  538. moduleToInfoMap,
  539. runtime,
  540. requestShortener,
  541. runtimeTemplate,
  542. neededNamespaceObjects,
  543. asCall,
  544. strictHarmonyModule,
  545. asiSafe
  546. );
  547. {
  548. const { ids, comment } = binding;
  549. let reference;
  550. let isPropertyAccess;
  551. if ("rawName" in binding) {
  552. reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`;
  553. isPropertyAccess = ids.length > 0;
  554. } else {
  555. const { info, name: exportId } = binding;
  556. const name = info.internalNames.get(exportId);
  557. if (!name) {
  558. throw new Error(
  559. `The export "${exportId}" in "${info.module.readableIdentifier(
  560. requestShortener
  561. )}" has no internal name (existing names: ${
  562. Array.from(
  563. info.internalNames,
  564. ([name, symbol]) => `${name}: ${symbol}`
  565. ).join(", ") || "none"
  566. })`
  567. );
  568. }
  569. reference = `${name}${comment || ""}${propertyAccess(ids)}`;
  570. isPropertyAccess = ids.length > 1;
  571. }
  572. if (isPropertyAccess && asCall && callContext === false) {
  573. return asiSafe
  574. ? `(0,${reference})`
  575. : asiSafe === false
  576. ? `;(0,${reference})`
  577. : `/*#__PURE__*/Object(${reference})`;
  578. }
  579. return reference;
  580. }
  581. };
  582. /**
  583. * @typedef {object} ConcatenateModuleHooks
  584. * @property {SyncBailHook<[Record<string, string>, ConcatenatedModule], boolean | void>} exportsDefinitions
  585. */
  586. /** @type {WeakMap<Compilation, ConcatenateModuleHooks>} */
  587. const compilationHooksMap = new WeakMap();
  588. class ConcatenatedModule extends Module {
  589. /**
  590. * @param {Module} rootModule the root module of the concatenation
  591. * @param {Set<Module>} modules all modules in the concatenation (including the root module)
  592. * @param {RuntimeSpec} runtime the runtime
  593. * @param {Compilation} compilation the compilation
  594. * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching
  595. * @param {string | HashConstructor=} hashFunction hash function to use
  596. * @returns {ConcatenatedModule} the module
  597. */
  598. static create(
  599. rootModule,
  600. modules,
  601. runtime,
  602. compilation,
  603. associatedObjectForCache,
  604. hashFunction = DEFAULTS.HASH_FUNCTION
  605. ) {
  606. const identifier = ConcatenatedModule._createIdentifier(
  607. rootModule,
  608. modules,
  609. associatedObjectForCache,
  610. hashFunction
  611. );
  612. return new ConcatenatedModule({
  613. identifier,
  614. rootModule,
  615. modules,
  616. runtime,
  617. compilation
  618. });
  619. }
  620. /**
  621. * @param {Compilation} compilation the compilation
  622. * @returns {ConcatenateModuleHooks} the attached hooks
  623. */
  624. static getCompilationHooks(compilation) {
  625. let hooks = compilationHooksMap.get(compilation);
  626. if (hooks === undefined) {
  627. hooks = {
  628. exportsDefinitions: new SyncBailHook(["definitions", "module"])
  629. };
  630. compilationHooksMap.set(compilation, hooks);
  631. }
  632. return hooks;
  633. }
  634. /**
  635. * @param {object} options options
  636. * @param {string} options.identifier the identifier of the module
  637. * @param {Module} options.rootModule the root module of the concatenation
  638. * @param {RuntimeSpec} options.runtime the selected runtime
  639. * @param {Set<Module>} options.modules all concatenated modules
  640. * @param {Compilation} options.compilation the compilation
  641. */
  642. constructor({ identifier, rootModule, modules, runtime, compilation }) {
  643. super(JAVASCRIPT_MODULE_TYPE_ESM, null, rootModule && rootModule.layer);
  644. // Info from Factory
  645. /** @type {string} */
  646. this._identifier = identifier;
  647. /** @type {Module} */
  648. this.rootModule = rootModule;
  649. /** @type {Set<Module>} */
  650. this._modules = modules;
  651. this._runtime = runtime;
  652. this.factoryMeta = rootModule && rootModule.factoryMeta;
  653. /** @type {Compilation | undefined} */
  654. this.compilation = compilation;
  655. }
  656. /**
  657. * Assuming this module is in the cache. Update the (cached) module with
  658. * the fresh module from the factory. Usually updates internal references
  659. * and properties.
  660. * @param {Module} module fresh module
  661. * @returns {void}
  662. */
  663. updateCacheModule(module) {
  664. throw new Error("Must not be called");
  665. }
  666. /**
  667. * @returns {SourceTypes} types available (do not mutate)
  668. */
  669. getSourceTypes() {
  670. return JS_TYPES;
  671. }
  672. get modules() {
  673. return Array.from(this._modules);
  674. }
  675. /**
  676. * @returns {string} a unique identifier of the module
  677. */
  678. identifier() {
  679. return this._identifier;
  680. }
  681. /**
  682. * @param {RequestShortener} requestShortener the request shortener
  683. * @returns {string} a user readable identifier of the module
  684. */
  685. readableIdentifier(requestShortener) {
  686. return `${this.rootModule.readableIdentifier(
  687. requestShortener
  688. )} + ${this._modules.size - 1} modules`;
  689. }
  690. /**
  691. * @param {LibIdentOptions} options options
  692. * @returns {string | null} an identifier for library inclusion
  693. */
  694. libIdent(options) {
  695. return this.rootModule.libIdent(options);
  696. }
  697. /**
  698. * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
  699. */
  700. nameForCondition() {
  701. return this.rootModule.nameForCondition();
  702. }
  703. /**
  704. * @param {ModuleGraph} moduleGraph the module graph
  705. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  706. */
  707. getSideEffectsConnectionState(moduleGraph) {
  708. return this.rootModule.getSideEffectsConnectionState(moduleGraph);
  709. }
  710. /**
  711. * @param {WebpackOptions} options webpack options
  712. * @param {Compilation} compilation the compilation
  713. * @param {ResolverWithOptions} resolver the resolver
  714. * @param {InputFileSystem} fs the file system
  715. * @param {BuildCallback} callback callback function
  716. * @returns {void}
  717. */
  718. build(options, compilation, resolver, fs, callback) {
  719. const { rootModule } = this;
  720. const { moduleArgument, exportsArgument } =
  721. /** @type {BuildInfo} */
  722. (rootModule.buildInfo);
  723. this.buildInfo = {
  724. strict: true,
  725. cacheable: true,
  726. moduleArgument,
  727. exportsArgument,
  728. fileDependencies: new LazySet(),
  729. contextDependencies: new LazySet(),
  730. missingDependencies: new LazySet(),
  731. topLevelDeclarations: new Set(),
  732. assets: undefined
  733. };
  734. this.buildMeta = rootModule.buildMeta;
  735. this.clearDependenciesAndBlocks();
  736. this.clearWarningsAndErrors();
  737. for (const m of this._modules) {
  738. // populate cacheable
  739. if (!(/** @type {BuildInfo} */ (m.buildInfo).cacheable)) {
  740. this.buildInfo.cacheable = false;
  741. }
  742. // populate dependencies
  743. for (const d of m.dependencies.filter(
  744. dep =>
  745. !(dep instanceof HarmonyImportDependency) ||
  746. !this._modules.has(
  747. /** @type {Module} */ (compilation.moduleGraph.getModule(dep))
  748. )
  749. )) {
  750. this.dependencies.push(d);
  751. }
  752. // populate blocks
  753. for (const d of m.blocks) {
  754. this.blocks.push(d);
  755. }
  756. // populate warnings
  757. const warnings = m.getWarnings();
  758. if (warnings !== undefined) {
  759. for (const warning of warnings) {
  760. this.addWarning(warning);
  761. }
  762. }
  763. // populate errors
  764. const errors = m.getErrors();
  765. if (errors !== undefined) {
  766. for (const error of errors) {
  767. this.addError(error);
  768. }
  769. }
  770. const { assets, assetsInfo, topLevelDeclarations } =
  771. /** @type {BuildInfo} */ (m.buildInfo);
  772. // populate topLevelDeclarations
  773. if (topLevelDeclarations) {
  774. const topLevelDeclarations = this.buildInfo.topLevelDeclarations;
  775. if (topLevelDeclarations !== undefined) {
  776. for (const decl of topLevelDeclarations) {
  777. topLevelDeclarations.add(decl);
  778. }
  779. }
  780. } else {
  781. this.buildInfo.topLevelDeclarations = undefined;
  782. }
  783. // populate assets
  784. if (assets) {
  785. if (this.buildInfo.assets === undefined) {
  786. this.buildInfo.assets = Object.create(null);
  787. }
  788. Object.assign(
  789. /** @type {NonNullable<BuildInfo["assets"]>} */
  790. (
  791. /** @type {BuildInfo} */
  792. (this.buildInfo).assets
  793. ),
  794. assets
  795. );
  796. }
  797. if (assetsInfo) {
  798. if (this.buildInfo.assetsInfo === undefined) {
  799. this.buildInfo.assetsInfo = new Map();
  800. }
  801. for (const [key, value] of assetsInfo) {
  802. this.buildInfo.assetsInfo.set(key, value);
  803. }
  804. }
  805. }
  806. callback();
  807. }
  808. /**
  809. * @param {string=} type the source type for which the size should be estimated
  810. * @returns {number} the estimated size of the module (must be non-zero)
  811. */
  812. size(type) {
  813. // Guess size from embedded modules
  814. let size = 0;
  815. for (const module of this._modules) {
  816. size += module.size(type);
  817. }
  818. return size;
  819. }
  820. /**
  821. * @private
  822. * @param {Module} rootModule the root of the concatenation
  823. * @param {Set<Module>} modulesSet a set of modules which should be concatenated
  824. * @param {RuntimeSpec} runtime for this runtime
  825. * @param {ModuleGraph} moduleGraph the module graph
  826. * @returns {ConcatenationEntry[]} concatenation list
  827. */
  828. _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) {
  829. /** @type {ConcatenationEntry[]} */
  830. const list = [];
  831. /** @type {Map<Module, RuntimeSpec | true>} */
  832. const existingEntries = new Map();
  833. /**
  834. * @param {Module} module a module
  835. * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order
  836. */
  837. const getConcatenatedImports = module => {
  838. const connections = Array.from(
  839. moduleGraph.getOutgoingConnections(module)
  840. );
  841. if (module === rootModule) {
  842. for (const c of moduleGraph.getOutgoingConnections(this))
  843. connections.push(c);
  844. }
  845. /**
  846. * @type {Array<{ connection: ModuleGraphConnection, sourceOrder: number, rangeStart: number }>}
  847. */
  848. const references = connections
  849. .filter(connection => {
  850. if (!(connection.dependency instanceof HarmonyImportDependency))
  851. return false;
  852. return (
  853. connection &&
  854. connection.resolvedOriginModule === module &&
  855. connection.module &&
  856. connection.isTargetActive(runtime)
  857. );
  858. })
  859. .map(connection => {
  860. const dep = /** @type {HarmonyImportDependency} */ (
  861. connection.dependency
  862. );
  863. return {
  864. connection,
  865. sourceOrder: dep.sourceOrder,
  866. rangeStart: dep.range && dep.range[0]
  867. };
  868. });
  869. /**
  870. * bySourceOrder
  871. * @example
  872. * import a from "a"; // sourceOrder=1
  873. * import b from "b"; // sourceOrder=2
  874. *
  875. * byRangeStart
  876. * @example
  877. * import {a, b} from "a"; // sourceOrder=1
  878. * a.a(); // first range
  879. * b.b(); // second range
  880. *
  881. * If there is no reexport, we have the same source.
  882. * If there is reexport, but module has side effects, this will lead to reexport module only.
  883. * If there is side-effects-free reexport, we can get simple deterministic result with range start comparison.
  884. */
  885. references.sort(concatComparators(bySourceOrder, byRangeStart));
  886. /** @type {Map<Module, { connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} */
  887. const referencesMap = new Map();
  888. for (const { connection } of references) {
  889. const runtimeCondition = filterRuntime(runtime, r =>
  890. connection.isTargetActive(r)
  891. );
  892. if (runtimeCondition === false) continue;
  893. const module = connection.module;
  894. const entry = referencesMap.get(module);
  895. if (entry === undefined) {
  896. referencesMap.set(module, { connection, runtimeCondition });
  897. continue;
  898. }
  899. entry.runtimeCondition = mergeRuntimeConditionNonFalse(
  900. entry.runtimeCondition,
  901. runtimeCondition,
  902. runtime
  903. );
  904. }
  905. return referencesMap.values();
  906. };
  907. /**
  908. * @param {ModuleGraphConnection} connection graph connection
  909. * @param {RuntimeSpec | true} runtimeCondition runtime condition
  910. * @returns {void}
  911. */
  912. const enterModule = (connection, runtimeCondition) => {
  913. const module = connection.module;
  914. if (!module) return;
  915. const existingEntry = existingEntries.get(module);
  916. if (existingEntry === true) {
  917. return;
  918. }
  919. if (modulesSet.has(module)) {
  920. existingEntries.set(module, true);
  921. if (runtimeCondition !== true) {
  922. throw new Error(
  923. `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString(
  924. runtimeCondition
  925. )}). This should not happen.`
  926. );
  927. }
  928. const imports = getConcatenatedImports(module);
  929. for (const { connection, runtimeCondition } of imports)
  930. enterModule(connection, runtimeCondition);
  931. list.push({
  932. type: "concatenated",
  933. module: connection.module,
  934. runtimeCondition
  935. });
  936. } else {
  937. if (existingEntry !== undefined) {
  938. const reducedRuntimeCondition = subtractRuntimeCondition(
  939. runtimeCondition,
  940. existingEntry,
  941. runtime
  942. );
  943. if (reducedRuntimeCondition === false) return;
  944. runtimeCondition = reducedRuntimeCondition;
  945. existingEntries.set(
  946. connection.module,
  947. mergeRuntimeConditionNonFalse(
  948. existingEntry,
  949. runtimeCondition,
  950. runtime
  951. )
  952. );
  953. } else {
  954. existingEntries.set(connection.module, runtimeCondition);
  955. }
  956. if (list.length > 0) {
  957. const lastItem = list[list.length - 1];
  958. if (
  959. lastItem.type === "external" &&
  960. lastItem.module === connection.module
  961. ) {
  962. lastItem.runtimeCondition = mergeRuntimeCondition(
  963. lastItem.runtimeCondition,
  964. runtimeCondition,
  965. runtime
  966. );
  967. return;
  968. }
  969. }
  970. list.push({
  971. type: "external",
  972. get module() {
  973. // We need to use a getter here, because the module in the dependency
  974. // could be replaced by some other process (i. e. also replaced with a
  975. // concatenated module)
  976. return connection.module;
  977. },
  978. runtimeCondition
  979. });
  980. }
  981. };
  982. existingEntries.set(rootModule, true);
  983. const imports = getConcatenatedImports(rootModule);
  984. for (const { connection, runtimeCondition } of imports)
  985. enterModule(connection, runtimeCondition);
  986. list.push({
  987. type: "concatenated",
  988. module: rootModule,
  989. runtimeCondition: true
  990. });
  991. return list;
  992. }
  993. /**
  994. * @param {Module} rootModule the root module of the concatenation
  995. * @param {Set<Module>} modules all modules in the concatenation (including the root module)
  996. * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching
  997. * @param {string | HashConstructor=} hashFunction hash function to use
  998. * @returns {string} the identifier
  999. */
  1000. static _createIdentifier(
  1001. rootModule,
  1002. modules,
  1003. associatedObjectForCache,
  1004. hashFunction = DEFAULTS.HASH_FUNCTION
  1005. ) {
  1006. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  1007. /** @type {string} */ (rootModule.context),
  1008. associatedObjectForCache
  1009. );
  1010. const identifiers = [];
  1011. for (const module of modules) {
  1012. identifiers.push(cachedMakePathsRelative(module.identifier()));
  1013. }
  1014. identifiers.sort();
  1015. const hash = createHash(hashFunction);
  1016. hash.update(identifiers.join(" "));
  1017. return `${rootModule.identifier()}|${hash.digest("hex")}`;
  1018. }
  1019. /**
  1020. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  1021. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  1022. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  1023. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  1024. */
  1025. addCacheDependencies(
  1026. fileDependencies,
  1027. contextDependencies,
  1028. missingDependencies,
  1029. buildDependencies
  1030. ) {
  1031. for (const module of this._modules) {
  1032. module.addCacheDependencies(
  1033. fileDependencies,
  1034. contextDependencies,
  1035. missingDependencies,
  1036. buildDependencies
  1037. );
  1038. }
  1039. }
  1040. /**
  1041. * @param {CodeGenerationContext} context context for code generation
  1042. * @returns {CodeGenerationResult} result
  1043. */
  1044. codeGeneration({
  1045. dependencyTemplates,
  1046. runtimeTemplate,
  1047. moduleGraph,
  1048. chunkGraph,
  1049. runtime: generationRuntime,
  1050. codeGenerationResults
  1051. }) {
  1052. /** @type {RuntimeRequirements} */
  1053. const runtimeRequirements = new Set();
  1054. const runtime = intersectRuntime(generationRuntime, this._runtime);
  1055. const requestShortener = runtimeTemplate.requestShortener;
  1056. // Meta info for each module
  1057. const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo(
  1058. moduleGraph,
  1059. runtime
  1060. );
  1061. // Set with modules that need a generated namespace object
  1062. /** @type {Set<ConcatenatedModuleInfo>} */
  1063. const neededNamespaceObjects = new Set();
  1064. // Generate source code and analyse scopes
  1065. // Prepare a ReplaceSource for the final source
  1066. for (const info of moduleToInfoMap.values()) {
  1067. this._analyseModule(
  1068. moduleToInfoMap,
  1069. info,
  1070. dependencyTemplates,
  1071. runtimeTemplate,
  1072. moduleGraph,
  1073. chunkGraph,
  1074. runtime,
  1075. /** @type {CodeGenerationResults} */
  1076. (codeGenerationResults)
  1077. );
  1078. }
  1079. // List of all used names to avoid conflicts
  1080. const allUsedNames = new Set(RESERVED_NAMES);
  1081. // Updated Top level declarations are created by renaming
  1082. const topLevelDeclarations = new Set();
  1083. // List of additional names in scope for module references
  1084. /** @type {Map<string, ScopeInfo>} */
  1085. const usedNamesInScopeInfo = new Map();
  1086. // Set of already checked scopes
  1087. const ignoredScopes = new Set();
  1088. // get all global names
  1089. for (const info of modulesWithInfo) {
  1090. if (info.type === "concatenated") {
  1091. // ignore symbols from moduleScope
  1092. if (info.moduleScope) {
  1093. ignoredScopes.add(info.moduleScope);
  1094. }
  1095. // The super class expression in class scopes behaves weird
  1096. // We get ranges of all super class expressions to make
  1097. // renaming to work correctly
  1098. const superClassCache = new WeakMap();
  1099. /**
  1100. * @param {Scope} scope scope
  1101. * @returns {{ range: Range, variables: Variable[] }[]} result
  1102. */
  1103. const getSuperClassExpressions = scope => {
  1104. const cacheEntry = superClassCache.get(scope);
  1105. if (cacheEntry !== undefined) return cacheEntry;
  1106. const superClassExpressions = [];
  1107. for (const childScope of scope.childScopes) {
  1108. if (childScope.type !== "class") continue;
  1109. const block = childScope.block;
  1110. if (
  1111. (block.type === "ClassDeclaration" ||
  1112. block.type === "ClassExpression") &&
  1113. block.superClass
  1114. ) {
  1115. superClassExpressions.push({
  1116. range: /** @type {Range} */ (block.superClass.range),
  1117. variables: childScope.variables
  1118. });
  1119. }
  1120. }
  1121. superClassCache.set(scope, superClassExpressions);
  1122. return superClassExpressions;
  1123. };
  1124. // add global symbols
  1125. if (info.globalScope) {
  1126. for (const reference of info.globalScope.through) {
  1127. const name = reference.identifier.name;
  1128. if (ConcatenationScope.isModuleReference(name)) {
  1129. const match = ConcatenationScope.matchModuleReference(name);
  1130. if (!match) continue;
  1131. const referencedInfo = modulesWithInfo[match.index];
  1132. if (referencedInfo.type === "reference")
  1133. throw new Error("Module reference can't point to a reference");
  1134. const binding = getFinalBinding(
  1135. moduleGraph,
  1136. referencedInfo,
  1137. match.ids,
  1138. moduleToInfoMap,
  1139. runtime,
  1140. requestShortener,
  1141. runtimeTemplate,
  1142. neededNamespaceObjects,
  1143. false,
  1144. /** @type {BuildMeta} */
  1145. (info.module.buildMeta).strictHarmonyModule,
  1146. true
  1147. );
  1148. if (!binding.ids) continue;
  1149. const { usedNames, alreadyCheckedScopes } =
  1150. getUsedNamesInScopeInfo(
  1151. usedNamesInScopeInfo,
  1152. binding.info.module.identifier(),
  1153. "name" in binding ? binding.name : ""
  1154. );
  1155. for (const expr of getSuperClassExpressions(reference.from)) {
  1156. if (
  1157. expr.range[0] <=
  1158. /** @type {Range} */ (reference.identifier.range)[0] &&
  1159. expr.range[1] >=
  1160. /** @type {Range} */ (reference.identifier.range)[1]
  1161. ) {
  1162. for (const variable of expr.variables) {
  1163. usedNames.add(variable.name);
  1164. }
  1165. }
  1166. }
  1167. addScopeSymbols(
  1168. reference.from,
  1169. usedNames,
  1170. alreadyCheckedScopes,
  1171. ignoredScopes
  1172. );
  1173. } else {
  1174. allUsedNames.add(name);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }
  1180. // generate names for symbols
  1181. for (const info of moduleToInfoMap.values()) {
  1182. const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo(
  1183. usedNamesInScopeInfo,
  1184. info.module.identifier(),
  1185. ""
  1186. );
  1187. switch (info.type) {
  1188. case "concatenated": {
  1189. const variables = /** @type {Scope} */ (info.moduleScope).variables;
  1190. for (const variable of variables) {
  1191. const name = variable.name;
  1192. const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo(
  1193. usedNamesInScopeInfo,
  1194. info.module.identifier(),
  1195. name
  1196. );
  1197. if (allUsedNames.has(name) || usedNames.has(name)) {
  1198. const references = getAllReferences(variable);
  1199. for (const ref of references) {
  1200. addScopeSymbols(
  1201. ref.from,
  1202. usedNames,
  1203. alreadyCheckedScopes,
  1204. ignoredScopes
  1205. );
  1206. }
  1207. const newName = findNewName(
  1208. name,
  1209. allUsedNames,
  1210. usedNames,
  1211. info.module.readableIdentifier(requestShortener)
  1212. );
  1213. allUsedNames.add(newName);
  1214. info.internalNames.set(name, newName);
  1215. topLevelDeclarations.add(newName);
  1216. const source = /** @type {ReplaceSource} */ (info.source);
  1217. const allIdentifiers = new Set(
  1218. references.map(r => r.identifier).concat(variable.identifiers)
  1219. );
  1220. for (const identifier of allIdentifiers) {
  1221. const r = /** @type {Range} */ (identifier.range);
  1222. const path = getPathInAst(
  1223. /** @type {NonNullable<ConcatenatedModuleInfo["ast"]>} */
  1224. (info.ast),
  1225. identifier
  1226. );
  1227. if (path && path.length > 1) {
  1228. const maybeProperty =
  1229. path[1].type === "AssignmentPattern" &&
  1230. path[1].left === path[0]
  1231. ? path[2]
  1232. : path[1];
  1233. if (
  1234. maybeProperty.type === "Property" &&
  1235. maybeProperty.shorthand
  1236. ) {
  1237. source.insert(r[1], `: ${newName}`);
  1238. continue;
  1239. }
  1240. }
  1241. source.replace(r[0], r[1] - 1, newName);
  1242. }
  1243. } else {
  1244. allUsedNames.add(name);
  1245. info.internalNames.set(name, name);
  1246. topLevelDeclarations.add(name);
  1247. }
  1248. }
  1249. let namespaceObjectName;
  1250. if (info.namespaceExportSymbol) {
  1251. namespaceObjectName = info.internalNames.get(
  1252. info.namespaceExportSymbol
  1253. );
  1254. } else {
  1255. namespaceObjectName = findNewName(
  1256. "namespaceObject",
  1257. allUsedNames,
  1258. namespaceObjectUsedNames,
  1259. info.module.readableIdentifier(requestShortener)
  1260. );
  1261. allUsedNames.add(namespaceObjectName);
  1262. }
  1263. info.namespaceObjectName =
  1264. /** @type {string} */
  1265. (namespaceObjectName);
  1266. topLevelDeclarations.add(namespaceObjectName);
  1267. break;
  1268. }
  1269. case "external": {
  1270. const externalName = findNewName(
  1271. "",
  1272. allUsedNames,
  1273. namespaceObjectUsedNames,
  1274. info.module.readableIdentifier(requestShortener)
  1275. );
  1276. allUsedNames.add(externalName);
  1277. info.name = externalName;
  1278. topLevelDeclarations.add(externalName);
  1279. break;
  1280. }
  1281. }
  1282. const buildMeta = /** @type {BuildMeta} */ (info.module.buildMeta);
  1283. if (buildMeta.exportsType !== "namespace") {
  1284. const externalNameInterop = findNewName(
  1285. "namespaceObject",
  1286. allUsedNames,
  1287. namespaceObjectUsedNames,
  1288. info.module.readableIdentifier(requestShortener)
  1289. );
  1290. allUsedNames.add(externalNameInterop);
  1291. info.interopNamespaceObjectName = externalNameInterop;
  1292. topLevelDeclarations.add(externalNameInterop);
  1293. }
  1294. if (
  1295. buildMeta.exportsType === "default" &&
  1296. buildMeta.defaultObject !== "redirect"
  1297. ) {
  1298. const externalNameInterop = findNewName(
  1299. "namespaceObject2",
  1300. allUsedNames,
  1301. namespaceObjectUsedNames,
  1302. info.module.readableIdentifier(requestShortener)
  1303. );
  1304. allUsedNames.add(externalNameInterop);
  1305. info.interopNamespaceObject2Name = externalNameInterop;
  1306. topLevelDeclarations.add(externalNameInterop);
  1307. }
  1308. if (buildMeta.exportsType === "dynamic" || !buildMeta.exportsType) {
  1309. const externalNameInterop = findNewName(
  1310. "default",
  1311. allUsedNames,
  1312. namespaceObjectUsedNames,
  1313. info.module.readableIdentifier(requestShortener)
  1314. );
  1315. allUsedNames.add(externalNameInterop);
  1316. info.interopDefaultAccessName = externalNameInterop;
  1317. topLevelDeclarations.add(externalNameInterop);
  1318. }
  1319. }
  1320. // Find and replace references to modules
  1321. for (const info of moduleToInfoMap.values()) {
  1322. if (info.type === "concatenated") {
  1323. const globalScope = /** @type {Scope} */ (info.globalScope);
  1324. for (const reference of globalScope.through) {
  1325. const name = reference.identifier.name;
  1326. const match = ConcatenationScope.matchModuleReference(name);
  1327. if (match) {
  1328. const referencedInfo = modulesWithInfo[match.index];
  1329. if (referencedInfo.type === "reference")
  1330. throw new Error("Module reference can't point to a reference");
  1331. const finalName = getFinalName(
  1332. moduleGraph,
  1333. referencedInfo,
  1334. match.ids,
  1335. moduleToInfoMap,
  1336. runtime,
  1337. requestShortener,
  1338. runtimeTemplate,
  1339. neededNamespaceObjects,
  1340. match.call,
  1341. !match.directImport,
  1342. /** @type {BuildMeta} */
  1343. (info.module.buildMeta).strictHarmonyModule,
  1344. match.asiSafe
  1345. );
  1346. const r = /** @type {Range} */ (reference.identifier.range);
  1347. const source = /** @type {ReplaceSource} */ (info.source);
  1348. // range is extended by 2 chars to cover the appended "._"
  1349. source.replace(r[0], r[1] + 1, finalName);
  1350. }
  1351. }
  1352. }
  1353. }
  1354. // Map with all root exposed used exports
  1355. /** @type {Map<string, (requestShortener: RequestShortener) => string>} */
  1356. const exportsMap = new Map();
  1357. // Set with all root exposed unused exports
  1358. /** @type {Set<string>} */
  1359. const unusedExports = new Set();
  1360. const rootInfo =
  1361. /** @type {ConcatenatedModuleInfo} */
  1362. (moduleToInfoMap.get(this.rootModule));
  1363. const strictHarmonyModule =
  1364. /** @type {BuildMeta} */
  1365. (rootInfo.module.buildMeta).strictHarmonyModule;
  1366. const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module);
  1367. /** @type {Record<string, string>} */
  1368. const exportsFinalName = {};
  1369. for (const exportInfo of exportsInfo.orderedExports) {
  1370. const name = exportInfo.name;
  1371. if (exportInfo.provided === false) continue;
  1372. const used = exportInfo.getUsedName(undefined, runtime);
  1373. if (!used) {
  1374. unusedExports.add(name);
  1375. continue;
  1376. }
  1377. exportsMap.set(used, requestShortener => {
  1378. try {
  1379. const finalName = getFinalName(
  1380. moduleGraph,
  1381. rootInfo,
  1382. [name],
  1383. moduleToInfoMap,
  1384. runtime,
  1385. requestShortener,
  1386. runtimeTemplate,
  1387. neededNamespaceObjects,
  1388. false,
  1389. false,
  1390. strictHarmonyModule,
  1391. true
  1392. );
  1393. exportsFinalName[used] = finalName;
  1394. return `/* ${
  1395. exportInfo.isReexport() ? "reexport" : "binding"
  1396. } */ ${finalName}`;
  1397. } catch (err) {
  1398. /** @type {Error} */
  1399. (err).message +=
  1400. `\nwhile generating the root export '${name}' (used name: '${used}')`;
  1401. throw err;
  1402. }
  1403. });
  1404. }
  1405. const result = new ConcatSource();
  1406. // add harmony compatibility flag (must be first because of possible circular dependencies)
  1407. let shouldAddHarmonyFlag = false;
  1408. if (
  1409. moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !==
  1410. UsageState.Unused
  1411. ) {
  1412. shouldAddHarmonyFlag = true;
  1413. }
  1414. // define exports
  1415. if (exportsMap.size > 0) {
  1416. const { exportsDefinitions } = ConcatenatedModule.getCompilationHooks(
  1417. /** @type {Compilation} */
  1418. (this.compilation)
  1419. );
  1420. const definitions = [];
  1421. for (const [key, value] of exportsMap) {
  1422. definitions.push(
  1423. `\n ${propertyName(key)}: ${runtimeTemplate.returningFunction(
  1424. value(requestShortener)
  1425. )}`
  1426. );
  1427. }
  1428. const shouldSkipRenderDefinitions = exportsDefinitions.call(
  1429. exportsFinalName,
  1430. this
  1431. );
  1432. if (!shouldSkipRenderDefinitions) {
  1433. runtimeRequirements.add(RuntimeGlobals.exports);
  1434. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  1435. if (shouldAddHarmonyFlag) {
  1436. result.add("// ESM COMPAT FLAG\n");
  1437. result.add(
  1438. runtimeTemplate.defineEsModuleFlagStatement({
  1439. exportsArgument: this.exportsArgument,
  1440. runtimeRequirements
  1441. })
  1442. );
  1443. }
  1444. result.add("\n// EXPORTS\n");
  1445. result.add(
  1446. `${RuntimeGlobals.definePropertyGetters}(${
  1447. this.exportsArgument
  1448. }, {${definitions.join(",")}\n});\n`
  1449. );
  1450. } else {
  1451. /** @type {BuildMeta} */
  1452. (this.buildMeta).exportsFinalName = exportsFinalName;
  1453. }
  1454. }
  1455. // list unused exports
  1456. if (unusedExports.size > 0) {
  1457. result.add(
  1458. `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n`
  1459. );
  1460. }
  1461. // generate namespace objects
  1462. const namespaceObjectSources = new Map();
  1463. for (const info of neededNamespaceObjects) {
  1464. if (info.namespaceExportSymbol) continue;
  1465. const nsObj = [];
  1466. const exportsInfo = moduleGraph.getExportsInfo(info.module);
  1467. for (const exportInfo of exportsInfo.orderedExports) {
  1468. if (exportInfo.provided === false) continue;
  1469. const usedName = exportInfo.getUsedName(undefined, runtime);
  1470. if (usedName) {
  1471. const finalName = getFinalName(
  1472. moduleGraph,
  1473. info,
  1474. [exportInfo.name],
  1475. moduleToInfoMap,
  1476. runtime,
  1477. requestShortener,
  1478. runtimeTemplate,
  1479. neededNamespaceObjects,
  1480. false,
  1481. undefined,
  1482. /** @type {BuildMeta} */
  1483. (info.module.buildMeta).strictHarmonyModule,
  1484. true
  1485. );
  1486. nsObj.push(
  1487. `\n ${propertyName(usedName)}: ${runtimeTemplate.returningFunction(
  1488. finalName
  1489. )}`
  1490. );
  1491. }
  1492. }
  1493. const name = info.namespaceObjectName;
  1494. const defineGetters =
  1495. nsObj.length > 0
  1496. ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join(
  1497. ","
  1498. )}\n});\n`
  1499. : "";
  1500. if (nsObj.length > 0)
  1501. runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
  1502. namespaceObjectSources.set(
  1503. info,
  1504. `
  1505. // NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)}
  1506. var ${name} = {};
  1507. ${RuntimeGlobals.makeNamespaceObject}(${name});
  1508. ${defineGetters}`
  1509. );
  1510. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1511. }
  1512. // define required namespace objects (must be before evaluation modules)
  1513. for (const info of modulesWithInfo) {
  1514. if (info.type === "concatenated") {
  1515. const source = namespaceObjectSources.get(info);
  1516. if (!source) continue;
  1517. result.add(source);
  1518. }
  1519. }
  1520. const chunkInitFragments = [];
  1521. // evaluate modules in order
  1522. for (const rawInfo of modulesWithInfo) {
  1523. let name;
  1524. let isConditional = false;
  1525. const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo;
  1526. switch (info.type) {
  1527. case "concatenated": {
  1528. result.add(
  1529. `\n;// ${info.module.readableIdentifier(requestShortener)}\n`
  1530. );
  1531. result.add(/** @type {ReplaceSource} */ (info.source));
  1532. if (info.chunkInitFragments) {
  1533. for (const f of info.chunkInitFragments) chunkInitFragments.push(f);
  1534. }
  1535. if (info.runtimeRequirements) {
  1536. for (const r of info.runtimeRequirements) {
  1537. runtimeRequirements.add(r);
  1538. }
  1539. }
  1540. name = info.namespaceObjectName;
  1541. break;
  1542. }
  1543. case "external": {
  1544. result.add(
  1545. `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
  1546. requestShortener
  1547. )}\n`
  1548. );
  1549. runtimeRequirements.add(RuntimeGlobals.require);
  1550. const { runtimeCondition } =
  1551. /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */
  1552. (rawInfo);
  1553. const condition = runtimeTemplate.runtimeConditionExpression({
  1554. chunkGraph,
  1555. runtimeCondition,
  1556. runtime,
  1557. runtimeRequirements
  1558. });
  1559. if (condition !== "true") {
  1560. isConditional = true;
  1561. result.add(`if (${condition}) {\n`);
  1562. }
  1563. result.add(
  1564. `var ${info.name} = ${RuntimeGlobals.require}(${JSON.stringify(
  1565. chunkGraph.getModuleId(info.module)
  1566. )});`
  1567. );
  1568. name = info.name;
  1569. break;
  1570. }
  1571. default:
  1572. // @ts-expect-error never is expected here
  1573. throw new Error(`Unsupported concatenation entry type ${info.type}`);
  1574. }
  1575. if (info.interopNamespaceObjectUsed) {
  1576. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  1577. result.add(
  1578. `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);`
  1579. );
  1580. }
  1581. if (info.interopNamespaceObject2Used) {
  1582. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  1583. result.add(
  1584. `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});`
  1585. );
  1586. }
  1587. if (info.interopDefaultAccessUsed) {
  1588. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  1589. result.add(
  1590. `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});`
  1591. );
  1592. }
  1593. if (isConditional) {
  1594. result.add("\n}");
  1595. }
  1596. }
  1597. const data = new Map();
  1598. if (chunkInitFragments.length > 0)
  1599. data.set("chunkInitFragments", chunkInitFragments);
  1600. data.set("topLevelDeclarations", topLevelDeclarations);
  1601. /** @type {CodeGenerationResult} */
  1602. const resultEntry = {
  1603. sources: new Map([["javascript", new CachedSource(result)]]),
  1604. data,
  1605. runtimeRequirements
  1606. };
  1607. return resultEntry;
  1608. }
  1609. /**
  1610. * @param {Map<Module, ModuleInfo>} modulesMap modulesMap
  1611. * @param {ModuleInfo} info info
  1612. * @param {DependencyTemplates} dependencyTemplates dependencyTemplates
  1613. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate
  1614. * @param {ModuleGraph} moduleGraph moduleGraph
  1615. * @param {ChunkGraph} chunkGraph chunkGraph
  1616. * @param {RuntimeSpec} runtime runtime
  1617. * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults
  1618. */
  1619. _analyseModule(
  1620. modulesMap,
  1621. info,
  1622. dependencyTemplates,
  1623. runtimeTemplate,
  1624. moduleGraph,
  1625. chunkGraph,
  1626. runtime,
  1627. codeGenerationResults
  1628. ) {
  1629. if (info.type === "concatenated") {
  1630. const m = info.module;
  1631. try {
  1632. // Create a concatenation scope to track and capture information
  1633. const concatenationScope = new ConcatenationScope(modulesMap, info);
  1634. // TODO cache codeGeneration results
  1635. const codeGenResult = m.codeGeneration({
  1636. dependencyTemplates,
  1637. runtimeTemplate,
  1638. moduleGraph,
  1639. chunkGraph,
  1640. runtime,
  1641. concatenationScope,
  1642. codeGenerationResults,
  1643. sourceTypes: JS_TYPES
  1644. });
  1645. const source =
  1646. /** @type {Source} */
  1647. (codeGenResult.sources.get("javascript"));
  1648. const data = codeGenResult.data;
  1649. const chunkInitFragments = data && data.get("chunkInitFragments");
  1650. const code = source.source().toString();
  1651. let ast;
  1652. try {
  1653. ast = JavascriptParser._parse(code, {
  1654. sourceType: "module"
  1655. });
  1656. } catch (_err) {
  1657. const err =
  1658. /** @type {Error & { loc?: { line: number, column: number } }} */
  1659. (_err);
  1660. if (
  1661. err.loc &&
  1662. typeof err.loc === "object" &&
  1663. typeof err.loc.line === "number"
  1664. ) {
  1665. const lineNumber = err.loc.line;
  1666. const lines = code.split("\n");
  1667. err.message += `\n| ${lines
  1668. .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
  1669. .join("\n| ")}`;
  1670. }
  1671. throw err;
  1672. }
  1673. const scopeManager = eslintScope.analyze(ast, {
  1674. ecmaVersion: 6,
  1675. sourceType: "module",
  1676. optimistic: true,
  1677. ignoreEval: true,
  1678. impliedStrict: true
  1679. });
  1680. const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast));
  1681. const moduleScope = globalScope.childScopes[0];
  1682. const resultSource = new ReplaceSource(source);
  1683. info.runtimeRequirements =
  1684. /** @type {ReadOnlyRuntimeRequirements} */
  1685. (codeGenResult.runtimeRequirements);
  1686. info.ast = ast;
  1687. info.internalSource = source;
  1688. info.source = resultSource;
  1689. info.chunkInitFragments = chunkInitFragments;
  1690. info.globalScope = globalScope;
  1691. info.moduleScope = moduleScope;
  1692. } catch (err) {
  1693. /** @type {Error} */
  1694. (err).message +=
  1695. `\nwhile analyzing module ${m.identifier()} for concatenation`;
  1696. throw err;
  1697. }
  1698. }
  1699. }
  1700. /**
  1701. * @param {ModuleGraph} moduleGraph the module graph
  1702. * @param {RuntimeSpec} runtime the runtime
  1703. * @returns {[ModuleInfoOrReference[], Map<Module, ModuleInfo>]} module info items
  1704. */
  1705. _getModulesWithInfo(moduleGraph, runtime) {
  1706. const orderedConcatenationList = this._createConcatenationList(
  1707. this.rootModule,
  1708. this._modules,
  1709. runtime,
  1710. moduleGraph
  1711. );
  1712. /** @type {Map<Module, ModuleInfo>} */
  1713. const map = new Map();
  1714. const list = orderedConcatenationList.map((info, index) => {
  1715. let item = map.get(info.module);
  1716. if (item === undefined) {
  1717. switch (info.type) {
  1718. case "concatenated":
  1719. item = {
  1720. type: "concatenated",
  1721. module: info.module,
  1722. index,
  1723. ast: undefined,
  1724. internalSource: undefined,
  1725. runtimeRequirements: undefined,
  1726. source: undefined,
  1727. globalScope: undefined,
  1728. moduleScope: undefined,
  1729. internalNames: new Map(),
  1730. exportMap: undefined,
  1731. rawExportMap: undefined,
  1732. namespaceExportSymbol: undefined,
  1733. namespaceObjectName: undefined,
  1734. interopNamespaceObjectUsed: false,
  1735. interopNamespaceObjectName: undefined,
  1736. interopNamespaceObject2Used: false,
  1737. interopNamespaceObject2Name: undefined,
  1738. interopDefaultAccessUsed: false,
  1739. interopDefaultAccessName: undefined
  1740. };
  1741. break;
  1742. case "external":
  1743. item = {
  1744. type: "external",
  1745. module: info.module,
  1746. runtimeCondition: info.runtimeCondition,
  1747. index,
  1748. name: undefined,
  1749. interopNamespaceObjectUsed: false,
  1750. interopNamespaceObjectName: undefined,
  1751. interopNamespaceObject2Used: false,
  1752. interopNamespaceObject2Name: undefined,
  1753. interopDefaultAccessUsed: false,
  1754. interopDefaultAccessName: undefined
  1755. };
  1756. break;
  1757. default:
  1758. throw new Error(
  1759. `Unsupported concatenation entry type ${info.type}`
  1760. );
  1761. }
  1762. map.set(
  1763. /** @type {ModuleInfo} */ (item).module,
  1764. /** @type {ModuleInfo} */ (item)
  1765. );
  1766. return /** @type {ModuleInfo} */ (item);
  1767. }
  1768. /** @type {ReferenceToModuleInfo} */
  1769. const ref = {
  1770. type: "reference",
  1771. runtimeCondition: info.runtimeCondition,
  1772. target: item
  1773. };
  1774. return ref;
  1775. });
  1776. return [list, map];
  1777. }
  1778. /**
  1779. * @param {Hash} hash the hash used to track dependencies
  1780. * @param {UpdateHashContext} context context
  1781. * @returns {void}
  1782. */
  1783. updateHash(hash, context) {
  1784. const { chunkGraph, runtime } = context;
  1785. for (const info of this._createConcatenationList(
  1786. this.rootModule,
  1787. this._modules,
  1788. intersectRuntime(runtime, this._runtime),
  1789. chunkGraph.moduleGraph
  1790. )) {
  1791. switch (info.type) {
  1792. case "concatenated":
  1793. info.module.updateHash(hash, context);
  1794. break;
  1795. case "external":
  1796. hash.update(`${chunkGraph.getModuleId(info.module)}`);
  1797. // TODO runtimeCondition
  1798. break;
  1799. }
  1800. }
  1801. super.updateHash(hash, context);
  1802. }
  1803. /**
  1804. * @param {ObjectDeserializerContext} context context
  1805. * @returns {ConcatenatedModule} ConcatenatedModule
  1806. */
  1807. static deserialize(context) {
  1808. const obj = new ConcatenatedModule({
  1809. identifier: /** @type {EXPECTED_ANY} */ (undefined),
  1810. rootModule: /** @type {EXPECTED_ANY} */ (undefined),
  1811. modules: /** @type {EXPECTED_ANY} */ (undefined),
  1812. runtime: undefined,
  1813. compilation: /** @type {EXPECTED_ANY} */ (undefined)
  1814. });
  1815. obj.deserialize(context);
  1816. return obj;
  1817. }
  1818. }
  1819. makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule");
  1820. module.exports = ConcatenatedModule;