Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

1132 wiersze
34 KiB

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