ConcatenatedModule.js 54 KB

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