ConcatenatedModule.js 67 KB

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