RuntimeTemplate.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const InitFragment = require("./InitFragment");
  7. const RuntimeGlobals = require("./RuntimeGlobals");
  8. const Template = require("./Template");
  9. const { equals } = require("./util/ArrayHelpers");
  10. const compileBooleanMatcher = require("./util/compileBooleanMatcher");
  11. const propertyAccess = require("./util/propertyAccess");
  12. const { forEachRuntime, subtractRuntime } = require("./util/runtime");
  13. /** @typedef {import("../declarations/WebpackOptions").Environment} Environment */
  14. /** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
  15. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  16. /** @typedef {import("./Chunk")} Chunk */
  17. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  18. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  19. /** @typedef {import("./CodeGenerationResults").CodeGenerationResult} CodeGenerationResult */
  20. /** @typedef {import("./Compilation")} Compilation */
  21. /** @typedef {import("./Dependency")} Dependency */
  22. /** @typedef {import("./Module")} Module */
  23. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  24. /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
  25. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  26. /** @typedef {import("./RequestShortener")} RequestShortener */
  27. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  28. /**
  29. * @param {Module} module the module
  30. * @param {ChunkGraph} chunkGraph the chunk graph
  31. * @returns {string} error message
  32. */
  33. const noModuleIdErrorMessage = (module, chunkGraph) => {
  34. return `Module ${module.identifier()} has no id assigned.
  35. This should not happen.
  36. It's in these chunks: ${
  37. Array.from(
  38. chunkGraph.getModuleChunksIterable(module),
  39. c => c.name || c.id || c.debugId
  40. ).join(", ") || "none"
  41. } (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
  42. Module has these incoming connections: ${Array.from(
  43. chunkGraph.moduleGraph.getIncomingConnections(module),
  44. connection =>
  45. `\n - ${
  46. connection.originModule && connection.originModule.identifier()
  47. } ${connection.dependency && connection.dependency.type} ${
  48. (connection.explanations &&
  49. Array.from(connection.explanations).join(", ")) ||
  50. ""
  51. }`
  52. ).join("")}`;
  53. };
  54. /**
  55. * @param {string | undefined} definition global object definition
  56. * @returns {string | undefined} save to use global object
  57. */
  58. function getGlobalObject(definition) {
  59. if (!definition) return definition;
  60. const trimmed = definition.trim();
  61. if (
  62. // identifier, we do not need real identifier regarding ECMAScript/Unicode
  63. trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) ||
  64. // iife
  65. // call expression
  66. // expression in parentheses
  67. trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu)
  68. )
  69. return trimmed;
  70. return `Object(${trimmed})`;
  71. }
  72. class RuntimeTemplate {
  73. /**
  74. * @param {Compilation} compilation the compilation
  75. * @param {OutputOptions} outputOptions the compilation output options
  76. * @param {RequestShortener} requestShortener the request shortener
  77. */
  78. constructor(compilation, outputOptions, requestShortener) {
  79. this.compilation = compilation;
  80. this.outputOptions = outputOptions || {};
  81. this.requestShortener = requestShortener;
  82. this.globalObject =
  83. /** @type {string} */
  84. (getGlobalObject(outputOptions.globalObject));
  85. this.contentHashReplacement = "X".repeat(
  86. /** @type {NonNullable<OutputOptions["hashDigestLength"]>} */
  87. (outputOptions.hashDigestLength)
  88. );
  89. }
  90. isIIFE() {
  91. return this.outputOptions.iife;
  92. }
  93. isModule() {
  94. return this.outputOptions.module;
  95. }
  96. supportsConst() {
  97. return /** @type {Environment} */ (this.outputOptions.environment).const;
  98. }
  99. supportsArrowFunction() {
  100. return /** @type {Environment} */ (this.outputOptions.environment)
  101. .arrowFunction;
  102. }
  103. supportsAsyncFunction() {
  104. return /** @type {Environment} */ (this.outputOptions.environment)
  105. .asyncFunction;
  106. }
  107. supportsOptionalChaining() {
  108. return /** @type {Environment} */ (this.outputOptions.environment)
  109. .optionalChaining;
  110. }
  111. supportsForOf() {
  112. return /** @type {Environment} */ (this.outputOptions.environment).forOf;
  113. }
  114. supportsDestructuring() {
  115. return /** @type {Environment} */ (this.outputOptions.environment)
  116. .destructuring;
  117. }
  118. supportsBigIntLiteral() {
  119. return /** @type {Environment} */ (this.outputOptions.environment)
  120. .bigIntLiteral;
  121. }
  122. supportsDynamicImport() {
  123. return /** @type {Environment} */ (this.outputOptions.environment)
  124. .dynamicImport;
  125. }
  126. supportsEcmaScriptModuleSyntax() {
  127. return /** @type {Environment} */ (this.outputOptions.environment).module;
  128. }
  129. supportTemplateLiteral() {
  130. return /** @type {Environment} */ (this.outputOptions.environment)
  131. .templateLiteral;
  132. }
  133. /**
  134. * @param {string} returnValue return value
  135. * @param {string} args arguments
  136. * @returns {string} returning function
  137. */
  138. returningFunction(returnValue, args = "") {
  139. return this.supportsArrowFunction()
  140. ? `(${args}) => (${returnValue})`
  141. : `function(${args}) { return ${returnValue}; }`;
  142. }
  143. /**
  144. * @param {string} args arguments
  145. * @param {string | string[]} body body
  146. * @returns {string} basic function
  147. */
  148. basicFunction(args, body) {
  149. return this.supportsArrowFunction()
  150. ? `(${args}) => {\n${Template.indent(body)}\n}`
  151. : `function(${args}) {\n${Template.indent(body)}\n}`;
  152. }
  153. /**
  154. * @param {Array<string|{expr: string}>} args args
  155. * @returns {string} result expression
  156. */
  157. concatenation(...args) {
  158. const len = args.length;
  159. if (len === 2) return this._es5Concatenation(args);
  160. if (len === 0) return '""';
  161. if (len === 1) {
  162. return typeof args[0] === "string"
  163. ? JSON.stringify(args[0])
  164. : `"" + ${args[0].expr}`;
  165. }
  166. if (!this.supportTemplateLiteral()) return this._es5Concatenation(args);
  167. // cost comparison between template literal and concatenation:
  168. // both need equal surroundings: `xxx` vs "xxx"
  169. // template literal has constant cost of 3 chars for each expression
  170. // es5 concatenation has cost of 3 + n chars for n expressions in row
  171. // when a es5 concatenation ends with an expression it reduces cost by 3
  172. // when a es5 concatenation starts with an single expression it reduces cost by 3
  173. // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3)
  174. // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12)
  175. let templateCost = 0;
  176. let concatenationCost = 0;
  177. let lastWasExpr = false;
  178. for (const arg of args) {
  179. const isExpr = typeof arg !== "string";
  180. if (isExpr) {
  181. templateCost += 3;
  182. concatenationCost += lastWasExpr ? 1 : 4;
  183. }
  184. lastWasExpr = isExpr;
  185. }
  186. if (lastWasExpr) concatenationCost -= 3;
  187. if (typeof args[0] !== "string" && typeof args[1] === "string")
  188. concatenationCost -= 3;
  189. if (concatenationCost <= templateCost) return this._es5Concatenation(args);
  190. return `\`${args
  191. .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`))
  192. .join("")}\``;
  193. }
  194. /**
  195. * @param {Array<string|{expr: string}>} args args (len >= 2)
  196. * @returns {string} result expression
  197. * @private
  198. */
  199. _es5Concatenation(args) {
  200. const str = args
  201. .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr))
  202. .join(" + ");
  203. // when the first two args are expression, we need to prepend "" + to force string
  204. // concatenation instead of number addition.
  205. return typeof args[0] !== "string" && typeof args[1] !== "string"
  206. ? `"" + ${str}`
  207. : str;
  208. }
  209. /**
  210. * @param {string} expression expression
  211. * @param {string} args arguments
  212. * @returns {string} expression function code
  213. */
  214. expressionFunction(expression, args = "") {
  215. return this.supportsArrowFunction()
  216. ? `(${args}) => (${expression})`
  217. : `function(${args}) { ${expression}; }`;
  218. }
  219. /**
  220. * @returns {string} empty function code
  221. */
  222. emptyFunction() {
  223. return this.supportsArrowFunction() ? "x => {}" : "function() {}";
  224. }
  225. /**
  226. * @param {string[]} items items
  227. * @param {string} value value
  228. * @returns {string} destructure array code
  229. */
  230. destructureArray(items, value) {
  231. return this.supportsDestructuring()
  232. ? `var [${items.join(", ")}] = ${value};`
  233. : Template.asString(
  234. items.map((item, i) => `var ${item} = ${value}[${i}];`)
  235. );
  236. }
  237. /**
  238. * @param {string[]} items items
  239. * @param {string} value value
  240. * @returns {string} destructure object code
  241. */
  242. destructureObject(items, value) {
  243. return this.supportsDestructuring()
  244. ? `var {${items.join(", ")}} = ${value};`
  245. : Template.asString(
  246. items.map(item => `var ${item} = ${value}${propertyAccess([item])};`)
  247. );
  248. }
  249. /**
  250. * @param {string} args arguments
  251. * @param {string} body body
  252. * @returns {string} IIFE code
  253. */
  254. iife(args, body) {
  255. return `(${this.basicFunction(args, body)})()`;
  256. }
  257. /**
  258. * @param {string} variable variable
  259. * @param {string} array array
  260. * @param {string | string[]} body body
  261. * @returns {string} for each code
  262. */
  263. forEach(variable, array, body) {
  264. return this.supportsForOf()
  265. ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}`
  266. : `${array}.forEach(function(${variable}) {\n${Template.indent(
  267. body
  268. )}\n});`;
  269. }
  270. /**
  271. * Add a comment
  272. * @param {object} options Information content of the comment
  273. * @param {string=} options.request request string used originally
  274. * @param {string=} options.chunkName name of the chunk referenced
  275. * @param {string=} options.chunkReason reason information of the chunk
  276. * @param {string=} options.message additional message
  277. * @param {string=} options.exportName name of the export
  278. * @returns {string} comment
  279. */
  280. comment({ request, chunkName, chunkReason, message, exportName }) {
  281. let content;
  282. if (this.outputOptions.pathinfo) {
  283. content = [message, request, chunkName, chunkReason]
  284. .filter(Boolean)
  285. .map(item => this.requestShortener.shorten(item))
  286. .join(" | ");
  287. } else {
  288. content = [message, chunkName, chunkReason]
  289. .filter(Boolean)
  290. .map(item => this.requestShortener.shorten(item))
  291. .join(" | ");
  292. }
  293. if (!content) return "";
  294. if (this.outputOptions.pathinfo) {
  295. return Template.toComment(content) + " ";
  296. } else {
  297. return Template.toNormalComment(content) + " ";
  298. }
  299. }
  300. /**
  301. * @param {object} options generation options
  302. * @param {string=} options.request request string used originally
  303. * @returns {string} generated error block
  304. */
  305. throwMissingModuleErrorBlock({ request }) {
  306. const err = `Cannot find module '${request}'`;
  307. return `var e = new Error(${JSON.stringify(
  308. err
  309. )}); e.code = 'MODULE_NOT_FOUND'; throw e;`;
  310. }
  311. /**
  312. * @param {object} options generation options
  313. * @param {string=} options.request request string used originally
  314. * @returns {string} generated error function
  315. */
  316. throwMissingModuleErrorFunction({ request }) {
  317. return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock(
  318. { request }
  319. )} }`;
  320. }
  321. /**
  322. * @param {object} options generation options
  323. * @param {string=} options.request request string used originally
  324. * @returns {string} generated error IIFE
  325. */
  326. missingModule({ request }) {
  327. return `Object(${this.throwMissingModuleErrorFunction({ request })}())`;
  328. }
  329. /**
  330. * @param {object} options generation options
  331. * @param {string=} options.request request string used originally
  332. * @returns {string} generated error statement
  333. */
  334. missingModuleStatement({ request }) {
  335. return `${this.missingModule({ request })};\n`;
  336. }
  337. /**
  338. * @param {object} options generation options
  339. * @param {string=} options.request request string used originally
  340. * @returns {string} generated error code
  341. */
  342. missingModulePromise({ request }) {
  343. return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({
  344. request
  345. })})`;
  346. }
  347. /**
  348. * @param {Object} options options object
  349. * @param {ChunkGraph} options.chunkGraph the chunk graph
  350. * @param {Module} options.module the module
  351. * @param {string=} options.request the request that should be printed as comment
  352. * @param {string=} options.idExpr expression to use as id expression
  353. * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned
  354. * @returns {string} the code
  355. */
  356. weakError({ module, chunkGraph, request, idExpr, type }) {
  357. const moduleId = chunkGraph.getModuleId(module);
  358. const errorMessage =
  359. moduleId === null
  360. ? JSON.stringify("Module is not available (weak dependency)")
  361. : idExpr
  362. ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
  363. : JSON.stringify(
  364. `Module '${moduleId}' is not available (weak dependency)`
  365. );
  366. const comment = request ? Template.toNormalComment(request) + " " : "";
  367. const errorStatements =
  368. `var e = new Error(${errorMessage}); ` +
  369. comment +
  370. "e.code = 'MODULE_NOT_FOUND'; throw e;";
  371. switch (type) {
  372. case "statements":
  373. return errorStatements;
  374. case "promise":
  375. return `Promise.resolve().then(${this.basicFunction(
  376. "",
  377. errorStatements
  378. )})`;
  379. case "expression":
  380. return this.iife("", errorStatements);
  381. }
  382. }
  383. /**
  384. * @param {Object} options options object
  385. * @param {Module} options.module the module
  386. * @param {ChunkGraph} options.chunkGraph the chunk graph
  387. * @param {string=} options.request the request that should be printed as comment
  388. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  389. * @returns {string} the expression
  390. */
  391. moduleId({ module, chunkGraph, request, weak }) {
  392. if (!module) {
  393. return this.missingModule({
  394. request
  395. });
  396. }
  397. const moduleId = chunkGraph.getModuleId(module);
  398. if (moduleId === null) {
  399. if (weak) {
  400. return "null /* weak dependency, without id */";
  401. }
  402. throw new Error(
  403. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  404. module,
  405. chunkGraph
  406. )}`
  407. );
  408. }
  409. return `${this.comment({ request })}${JSON.stringify(moduleId)}`;
  410. }
  411. /**
  412. * @param {Object} options options object
  413. * @param {Module | null} options.module the module
  414. * @param {ChunkGraph} options.chunkGraph the chunk graph
  415. * @param {string=} options.request the request that should be printed as comment
  416. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  417. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  418. * @returns {string} the expression
  419. */
  420. moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) {
  421. if (!module) {
  422. return this.missingModule({
  423. request
  424. });
  425. }
  426. const moduleId = chunkGraph.getModuleId(module);
  427. if (moduleId === null) {
  428. if (weak) {
  429. // only weak referenced modules don't get an id
  430. // we can always emit an error emitting code here
  431. return this.weakError({
  432. module,
  433. chunkGraph,
  434. request,
  435. type: "expression"
  436. });
  437. }
  438. throw new Error(
  439. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  440. module,
  441. chunkGraph
  442. )}`
  443. );
  444. }
  445. runtimeRequirements.add(RuntimeGlobals.require);
  446. return `${RuntimeGlobals.require}(${this.moduleId({
  447. module,
  448. chunkGraph,
  449. request,
  450. weak
  451. })})`;
  452. }
  453. /**
  454. * @param {Object} options options object
  455. * @param {Module | null} options.module the module
  456. * @param {ChunkGraph} options.chunkGraph the chunk graph
  457. * @param {string} options.request the request that should be printed as comment
  458. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  459. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  460. * @returns {string} the expression
  461. */
  462. moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) {
  463. return this.moduleRaw({
  464. module,
  465. chunkGraph,
  466. request,
  467. weak,
  468. runtimeRequirements
  469. });
  470. }
  471. /**
  472. * @param {Object} options options object
  473. * @param {Module} options.module the module
  474. * @param {ChunkGraph} options.chunkGraph the chunk graph
  475. * @param {string} options.request the request that should be printed as comment
  476. * @param {boolean=} options.strict if the current module is in strict esm mode
  477. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  478. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  479. * @returns {string} the expression
  480. */
  481. moduleNamespace({
  482. module,
  483. chunkGraph,
  484. request,
  485. strict,
  486. weak,
  487. runtimeRequirements
  488. }) {
  489. if (!module) {
  490. return this.missingModule({
  491. request
  492. });
  493. }
  494. if (chunkGraph.getModuleId(module) === null) {
  495. if (weak) {
  496. // only weak referenced modules don't get an id
  497. // we can always emit an error emitting code here
  498. return this.weakError({
  499. module,
  500. chunkGraph,
  501. request,
  502. type: "expression"
  503. });
  504. }
  505. throw new Error(
  506. `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage(
  507. module,
  508. chunkGraph
  509. )}`
  510. );
  511. }
  512. const moduleId = this.moduleId({
  513. module,
  514. chunkGraph,
  515. request,
  516. weak
  517. });
  518. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  519. switch (exportsType) {
  520. case "namespace":
  521. return this.moduleRaw({
  522. module,
  523. chunkGraph,
  524. request,
  525. weak,
  526. runtimeRequirements
  527. });
  528. case "default-with-named":
  529. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  530. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`;
  531. case "default-only":
  532. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  533. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`;
  534. case "dynamic":
  535. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  536. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`;
  537. }
  538. }
  539. /**
  540. * @param {Object} options options object
  541. * @param {ChunkGraph} options.chunkGraph the chunk graph
  542. * @param {AsyncDependenciesBlock=} options.block the current dependencies block
  543. * @param {Module} options.module the module
  544. * @param {string} options.request the request that should be printed as comment
  545. * @param {string} options.message a message for the comment
  546. * @param {boolean=} options.strict if the current module is in strict esm mode
  547. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  548. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  549. * @returns {string} the promise expression
  550. */
  551. moduleNamespacePromise({
  552. chunkGraph,
  553. block,
  554. module,
  555. request,
  556. message,
  557. strict,
  558. weak,
  559. runtimeRequirements
  560. }) {
  561. if (!module) {
  562. return this.missingModulePromise({
  563. request
  564. });
  565. }
  566. const moduleId = chunkGraph.getModuleId(module);
  567. if (moduleId === null) {
  568. if (weak) {
  569. // only weak referenced modules don't get an id
  570. // we can always emit an error emitting code here
  571. return this.weakError({
  572. module,
  573. chunkGraph,
  574. request,
  575. type: "promise"
  576. });
  577. }
  578. throw new Error(
  579. `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage(
  580. module,
  581. chunkGraph
  582. )}`
  583. );
  584. }
  585. const promise = this.blockPromise({
  586. chunkGraph,
  587. block,
  588. message,
  589. runtimeRequirements
  590. });
  591. let appending;
  592. let idExpr = JSON.stringify(chunkGraph.getModuleId(module));
  593. const comment = this.comment({
  594. request
  595. });
  596. let header = "";
  597. if (weak) {
  598. if (idExpr.length > 8) {
  599. // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"'
  600. header += `var id = ${idExpr}; `;
  601. idExpr = "id";
  602. }
  603. runtimeRequirements.add(RuntimeGlobals.moduleFactories);
  604. header += `if(!${
  605. RuntimeGlobals.moduleFactories
  606. }[${idExpr}]) { ${this.weakError({
  607. module,
  608. chunkGraph,
  609. request,
  610. idExpr,
  611. type: "statements"
  612. })} } `;
  613. }
  614. const moduleIdExpr = this.moduleId({
  615. module,
  616. chunkGraph,
  617. request,
  618. weak
  619. });
  620. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  621. let fakeType = 16;
  622. switch (exportsType) {
  623. case "namespace":
  624. if (header) {
  625. const rawModule = this.moduleRaw({
  626. module,
  627. chunkGraph,
  628. request,
  629. weak,
  630. runtimeRequirements
  631. });
  632. appending = `.then(${this.basicFunction(
  633. "",
  634. `${header}return ${rawModule};`
  635. )})`;
  636. } else {
  637. runtimeRequirements.add(RuntimeGlobals.require);
  638. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  639. }
  640. break;
  641. case "dynamic":
  642. fakeType |= 4;
  643. /* fall through */
  644. case "default-with-named":
  645. fakeType |= 2;
  646. /* fall through */
  647. case "default-only":
  648. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  649. if (chunkGraph.moduleGraph.isAsync(module)) {
  650. if (header) {
  651. const rawModule = this.moduleRaw({
  652. module,
  653. chunkGraph,
  654. request,
  655. weak,
  656. runtimeRequirements
  657. });
  658. appending = `.then(${this.basicFunction(
  659. "",
  660. `${header}return ${rawModule};`
  661. )})`;
  662. } else {
  663. runtimeRequirements.add(RuntimeGlobals.require);
  664. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  665. }
  666. appending += `.then(${this.returningFunction(
  667. `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
  668. "m"
  669. )})`;
  670. } else {
  671. fakeType |= 1;
  672. if (header) {
  673. const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
  674. appending = `.then(${this.basicFunction(
  675. "",
  676. `${header}return ${returnExpression};`
  677. )})`;
  678. } else {
  679. appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`;
  680. }
  681. }
  682. break;
  683. }
  684. return `${promise || "Promise.resolve()"}${appending}`;
  685. }
  686. /**
  687. * @param {Object} options options object
  688. * @param {ChunkGraph} options.chunkGraph the chunk graph
  689. * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated
  690. * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes
  691. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  692. * @returns {string} expression
  693. */
  694. runtimeConditionExpression({
  695. chunkGraph,
  696. runtimeCondition,
  697. runtime,
  698. runtimeRequirements
  699. }) {
  700. if (runtimeCondition === undefined) return "true";
  701. if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`;
  702. /** @type {Set<string>} */
  703. const positiveRuntimeIds = new Set();
  704. forEachRuntime(runtimeCondition, runtime =>
  705. positiveRuntimeIds.add(
  706. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  707. )
  708. );
  709. /** @type {Set<string>} */
  710. const negativeRuntimeIds = new Set();
  711. forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime =>
  712. negativeRuntimeIds.add(
  713. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  714. )
  715. );
  716. runtimeRequirements.add(RuntimeGlobals.runtimeId);
  717. return compileBooleanMatcher.fromLists(
  718. Array.from(positiveRuntimeIds),
  719. Array.from(negativeRuntimeIds)
  720. )(RuntimeGlobals.runtimeId);
  721. }
  722. /**
  723. *
  724. * @param {Object} options options object
  725. * @param {boolean=} options.update whether a new variable should be created or the existing one updated
  726. * @param {Module} options.module the module
  727. * @param {ChunkGraph} options.chunkGraph the chunk graph
  728. * @param {string} options.request the request that should be printed as comment
  729. * @param {string} options.importVar name of the import variable
  730. * @param {Module} options.originModule module in which the statement is emitted
  731. * @param {boolean=} options.weak true, if this is a weak dependency
  732. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  733. * @returns {[string, string]} the import statement and the compat statement
  734. */
  735. importStatement({
  736. update,
  737. module,
  738. chunkGraph,
  739. request,
  740. importVar,
  741. originModule,
  742. weak,
  743. runtimeRequirements
  744. }) {
  745. if (!module) {
  746. return [
  747. this.missingModuleStatement({
  748. request
  749. }),
  750. ""
  751. ];
  752. }
  753. if (chunkGraph.getModuleId(module) === null) {
  754. if (weak) {
  755. // only weak referenced modules don't get an id
  756. // we can always emit an error emitting code here
  757. return [
  758. this.weakError({
  759. module,
  760. chunkGraph,
  761. request,
  762. type: "statements"
  763. }),
  764. ""
  765. ];
  766. }
  767. throw new Error(
  768. `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage(
  769. module,
  770. chunkGraph
  771. )}`
  772. );
  773. }
  774. const moduleId = this.moduleId({
  775. module,
  776. chunkGraph,
  777. request,
  778. weak
  779. });
  780. const optDeclaration = update ? "" : "var ";
  781. const exportsType = module.getExportsType(
  782. chunkGraph.moduleGraph,
  783. /** @type {BuildMeta} */
  784. (originModule.buildMeta).strictHarmonyModule
  785. );
  786. runtimeRequirements.add(RuntimeGlobals.require);
  787. const importContent = `/* harmony import */ ${optDeclaration}${importVar} = ${RuntimeGlobals.require}(${moduleId});\n`;
  788. if (exportsType === "dynamic") {
  789. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  790. return [
  791. importContent,
  792. `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n`
  793. ];
  794. }
  795. return [importContent, ""];
  796. }
  797. /**
  798. * @param {Object} options options
  799. * @param {ModuleGraph} options.moduleGraph the module graph
  800. * @param {Module} options.module the module
  801. * @param {string} options.request the request
  802. * @param {string | string[]} options.exportName the export name
  803. * @param {Module} options.originModule the origin module
  804. * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
  805. * @param {boolean} options.isCall true, if expression will be called
  806. * @param {boolean | null} options.callContext when false, call context will not be preserved
  807. * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
  808. * @param {string} options.importVar the identifier name of the import variable
  809. * @param {InitFragment<TODO>[]} options.initFragments init fragments will be added here
  810. * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
  811. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  812. * @returns {string} expression
  813. */
  814. exportFromImport({
  815. moduleGraph,
  816. module,
  817. request,
  818. exportName,
  819. originModule,
  820. asiSafe,
  821. isCall,
  822. callContext,
  823. defaultInterop,
  824. importVar,
  825. initFragments,
  826. runtime,
  827. runtimeRequirements
  828. }) {
  829. if (!module) {
  830. return this.missingModule({
  831. request
  832. });
  833. }
  834. if (!Array.isArray(exportName)) {
  835. exportName = exportName ? [exportName] : [];
  836. }
  837. const exportsType = module.getExportsType(
  838. moduleGraph,
  839. /** @type {BuildMeta} */
  840. (originModule.buildMeta).strictHarmonyModule
  841. );
  842. if (defaultInterop) {
  843. if (exportName.length > 0 && exportName[0] === "default") {
  844. switch (exportsType) {
  845. case "dynamic":
  846. if (isCall) {
  847. return `${importVar}_default()${propertyAccess(exportName, 1)}`;
  848. } else {
  849. return asiSafe
  850. ? `(${importVar}_default()${propertyAccess(exportName, 1)})`
  851. : asiSafe === false
  852. ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
  853. : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
  854. }
  855. case "default-only":
  856. case "default-with-named":
  857. exportName = exportName.slice(1);
  858. break;
  859. }
  860. } else if (exportName.length > 0) {
  861. if (exportsType === "default-only") {
  862. return (
  863. "/* non-default import from non-esm module */undefined" +
  864. propertyAccess(exportName, 1)
  865. );
  866. } else if (
  867. exportsType !== "namespace" &&
  868. exportName[0] === "__esModule"
  869. ) {
  870. return "/* __esModule */true";
  871. }
  872. } else if (
  873. exportsType === "default-only" ||
  874. exportsType === "default-with-named"
  875. ) {
  876. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  877. initFragments.push(
  878. new InitFragment(
  879. `var ${importVar}_namespace_cache;\n`,
  880. InitFragment.STAGE_CONSTANTS,
  881. -1,
  882. `${importVar}_namespace_cache`
  883. )
  884. );
  885. return `/*#__PURE__*/ ${
  886. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  887. }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
  888. RuntimeGlobals.createFakeNamespaceObject
  889. }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
  890. }
  891. }
  892. if (exportName.length > 0) {
  893. const exportsInfo = moduleGraph.getExportsInfo(module);
  894. const used = exportsInfo.getUsedName(exportName, runtime);
  895. if (!used) {
  896. const comment = Template.toNormalComment(
  897. `unused export ${propertyAccess(exportName)}`
  898. );
  899. return `${comment} undefined`;
  900. }
  901. const comment = equals(used, exportName)
  902. ? ""
  903. : Template.toNormalComment(propertyAccess(exportName)) + " ";
  904. const access = `${importVar}${comment}${propertyAccess(used)}`;
  905. if (isCall && callContext === false) {
  906. return asiSafe
  907. ? `(0,${access})`
  908. : asiSafe === false
  909. ? `;(0,${access})`
  910. : `/*#__PURE__*/Object(${access})`;
  911. }
  912. return access;
  913. } else {
  914. return importVar;
  915. }
  916. }
  917. /**
  918. * @param {Object} options options
  919. * @param {AsyncDependenciesBlock | undefined} options.block the async block
  920. * @param {string} options.message the message
  921. * @param {ChunkGraph} options.chunkGraph the chunk graph
  922. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  923. * @returns {string} expression
  924. */
  925. blockPromise({ block, message, chunkGraph, runtimeRequirements }) {
  926. if (!block) {
  927. const comment = this.comment({
  928. message
  929. });
  930. return `Promise.resolve(${comment.trim()})`;
  931. }
  932. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  933. if (!chunkGroup || chunkGroup.chunks.length === 0) {
  934. const comment = this.comment({
  935. message
  936. });
  937. return `Promise.resolve(${comment.trim()})`;
  938. }
  939. const chunks = chunkGroup.chunks.filter(
  940. chunk => !chunk.hasRuntime() && chunk.id !== null
  941. );
  942. const comment = this.comment({
  943. message,
  944. chunkName: block.chunkName
  945. });
  946. if (chunks.length === 1) {
  947. const chunkId = JSON.stringify(chunks[0].id);
  948. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  949. const fetchPriority = chunkGroup.options.fetchPriority;
  950. if (fetchPriority) {
  951. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  952. }
  953. return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId}${
  954. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  955. })`;
  956. } else if (chunks.length > 0) {
  957. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  958. const fetchPriority = chunkGroup.options.fetchPriority;
  959. if (fetchPriority) {
  960. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  961. }
  962. /**
  963. * @param {Chunk} chunk chunk
  964. * @returns {string} require chunk id code
  965. */
  966. const requireChunkId = chunk =>
  967. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${
  968. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  969. })`;
  970. return `Promise.all(${comment.trim()}[${chunks
  971. .map(requireChunkId)
  972. .join(", ")}])`;
  973. } else {
  974. return `Promise.resolve(${comment.trim()})`;
  975. }
  976. }
  977. /**
  978. * @param {Object} options options
  979. * @param {AsyncDependenciesBlock} options.block the async block
  980. * @param {ChunkGraph} options.chunkGraph the chunk graph
  981. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  982. * @param {string=} options.request request string used originally
  983. * @returns {string} expression
  984. */
  985. asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) {
  986. const dep = block.dependencies[0];
  987. const module = chunkGraph.moduleGraph.getModule(dep);
  988. const ensureChunk = this.blockPromise({
  989. block,
  990. message: "",
  991. chunkGraph,
  992. runtimeRequirements
  993. });
  994. const factory = this.returningFunction(
  995. this.moduleRaw({
  996. module,
  997. chunkGraph,
  998. request,
  999. runtimeRequirements
  1000. })
  1001. );
  1002. return this.returningFunction(
  1003. ensureChunk.startsWith("Promise.resolve(")
  1004. ? `${factory}`
  1005. : `${ensureChunk}.then(${this.returningFunction(factory)})`
  1006. );
  1007. }
  1008. /**
  1009. * @param {Object} options options
  1010. * @param {Dependency} options.dependency the dependency
  1011. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1012. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1013. * @param {string=} options.request request string used originally
  1014. * @returns {string} expression
  1015. */
  1016. syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) {
  1017. const module = chunkGraph.moduleGraph.getModule(dependency);
  1018. const factory = this.returningFunction(
  1019. this.moduleRaw({
  1020. module,
  1021. chunkGraph,
  1022. request,
  1023. runtimeRequirements
  1024. })
  1025. );
  1026. return this.returningFunction(factory);
  1027. }
  1028. /**
  1029. * @param {Object} options options
  1030. * @param {string} options.exportsArgument the name of the exports object
  1031. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1032. * @returns {string} statement
  1033. */
  1034. defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) {
  1035. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1036. runtimeRequirements.add(RuntimeGlobals.exports);
  1037. return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
  1038. }
  1039. /**
  1040. * @param {Object} options options object
  1041. * @param {Module} options.module the module
  1042. * @param {string} options.publicPath the public path
  1043. * @param {RuntimeSpec=} options.runtime runtime
  1044. * @param {CodeGenerationResults} options.codeGenerationResults the code generation results
  1045. * @returns {string} the url of the asset
  1046. */
  1047. assetUrl({ publicPath, runtime, module, codeGenerationResults }) {
  1048. if (!module) {
  1049. return "data:,";
  1050. }
  1051. const codeGen = codeGenerationResults.get(module, runtime);
  1052. const data = /** @type {NonNullable<CodeGenerationResult["data"]>} */ (
  1053. codeGen.data
  1054. );
  1055. const url = data.get("url");
  1056. if (url) return url.toString();
  1057. const filename = data.get("filename");
  1058. return publicPath + filename;
  1059. }
  1060. }
  1061. module.exports = RuntimeTemplate;