HarmonyImportDependency.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ConditionalInitFragment = require("../ConditionalInitFragment");
  7. const Dependency = require("../Dependency");
  8. const InitFragment = require("../InitFragment");
  9. const Template = require("../Template");
  10. const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment");
  11. const isGeneratorLowered = require("../async-modules/isGeneratorLowered");
  12. const { filterRuntime, mergeRuntime } = require("../util/runtime");
  13. const HarmonyLinkingError = require("./HarmonyLinkingError");
  14. const { ImportPhase, ImportPhaseUtils } = require("./ImportPhase");
  15. const ModuleDependency = require("./ModuleDependency");
  16. /** @import { ReplaceSource } from "webpack-sources" */
  17. /**
  18. * @import {
  19. * JavascriptParserOptions
  20. * } from "../../declarations/WebpackOptions"
  21. */
  22. /** @import { ReferencedExports } from "../Dependency" */
  23. /** @import { DependencyTemplateContext } from "../DependencyTemplate" */
  24. /** @import ExportsInfo from "../ExportsInfo" */
  25. /** @import Module, { BuildMeta } from "../Module" */
  26. /** @import ModuleGraph from "../ModuleGraph" */
  27. /** @import WebpackError from "../errors/WebpackError" */
  28. /** @import { ImportAttributes } from "../javascript/JavascriptParser" */
  29. /** @import { ImportPhaseType } from "./ImportPhase" */
  30. /**
  31. * @import {
  32. * ObjectDeserializerContext,
  33. * ObjectSerializerContext
  34. * } from "../serialization/ObjectMiddleware"
  35. */
  36. /** @import { RuntimeSpec } from "../util/runtime" */
  37. /** @typedef {0 | 1 | 2 | 3} ExportPresenceMode */
  38. const ExportPresenceModes = {
  39. NONE: /** @type {ExportPresenceMode} */ (0),
  40. WARN: /** @type {ExportPresenceMode} */ (1),
  41. AUTO: /** @type {ExportPresenceMode} */ (2),
  42. ERROR: /** @type {ExportPresenceMode} */ (3),
  43. /**
  44. * Returns result.
  45. * @param {string | false} str param
  46. * @returns {ExportPresenceMode} result
  47. */
  48. fromUserOption(str) {
  49. switch (str) {
  50. case "error":
  51. return ExportPresenceModes.ERROR;
  52. case "warn":
  53. return ExportPresenceModes.WARN;
  54. case "auto":
  55. return ExportPresenceModes.AUTO;
  56. case false:
  57. return ExportPresenceModes.NONE;
  58. default:
  59. throw new Error(`Invalid export presence value ${str}`);
  60. }
  61. },
  62. /**
  63. * Resolve export presence mode from parser options with a specific key and shared fallbacks.
  64. * @param {string | false | undefined} specificValue the type-specific option value (e.g. importExportsPresence or reexportExportsPresence)
  65. * @param {JavascriptParserOptions} options parser options
  66. * @returns {ExportPresenceMode} resolved mode
  67. */
  68. resolveFromOptions(specificValue, options) {
  69. if (specificValue !== undefined) {
  70. return ExportPresenceModes.fromUserOption(specificValue);
  71. }
  72. if (options.exportsPresence !== undefined) {
  73. return ExportPresenceModes.fromUserOption(options.exportsPresence);
  74. }
  75. return options.strictExportPresence
  76. ? ExportPresenceModes.ERROR
  77. : ExportPresenceModes.AUTO;
  78. }
  79. };
  80. /**
  81. * Get the non-optional leading part of a member chain.
  82. * @param {string[]} members members
  83. * @param {boolean[]} membersOptionals optionality for each member
  84. * @returns {string[]} the non-optional prefix
  85. */
  86. const getNonOptionalPart = (members, membersOptionals) => {
  87. let i = 0;
  88. while (i < members.length && membersOptionals[i] === false) i++;
  89. return i !== members.length ? members.slice(0, i) : members;
  90. };
  91. /** @typedef {string[]} Ids */
  92. class HarmonyImportDependency extends ModuleDependency {
  93. /**
  94. * Creates an instance of HarmonyImportDependency.
  95. * @param {string} request request string
  96. * @param {number} sourceOrder source order
  97. * @param {ImportPhaseType=} phase import phase
  98. * @param {ImportAttributes=} attributes import attributes
  99. */
  100. constructor(
  101. request,
  102. sourceOrder,
  103. phase = ImportPhase.Evaluation,
  104. attributes = undefined
  105. ) {
  106. super(request, sourceOrder);
  107. /** @type {ImportPhaseType} */
  108. this.phase = phase;
  109. /** @type {ImportAttributes | undefined} */
  110. this.attributes = attributes;
  111. /** @type {boolean} */
  112. this._lazyMake = false;
  113. }
  114. get category() {
  115. return "esm";
  116. }
  117. /**
  118. * Whether the lazy barrel currently defers creating this dependency's target module (lazy barrel optimization).
  119. * @returns {boolean} true while deferred, so it must not be processed or rendered
  120. */
  121. isLazy() {
  122. return this._lazyMake;
  123. }
  124. /**
  125. * Sets whether the lazy barrel defers creating this dependency's target module (lazy barrel optimization).
  126. * @param {boolean} value true to defer, false to create it now
  127. */
  128. setLazy(value) {
  129. this._lazyMake = value;
  130. }
  131. /**
  132. * Returns true if this dependency can be concatenated
  133. * @param {boolean} concatenateCommonJsModules whether optimization.concatenateModules.commonjs is enabled
  134. * @returns {boolean} true if this dependency can be concatenated
  135. */
  136. canConcatenate(concatenateCommonJsModules) {
  137. return true;
  138. }
  139. /**
  140. * Returns an identifier to merge equal requests.
  141. * @returns {string | null} an identifier to merge equal requests
  142. */
  143. getResourceIdentifier() {
  144. let str = super.getResourceIdentifier();
  145. // We specifically use this check to avoid writing the default (`evaluation` or `0`) value and save memory
  146. if (this.phase) {
  147. str += `|phase${ImportPhaseUtils.stringify(this.phase)}`;
  148. }
  149. if (this.attributes) {
  150. str += `|attributes${JSON.stringify(this.attributes)}`;
  151. }
  152. return str;
  153. }
  154. /**
  155. * Returns list of exports referenced by this dependency
  156. * @param {ModuleGraph} moduleGraph module graph
  157. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  158. * @returns {ReferencedExports} referenced exports
  159. */
  160. getReferencedExports(moduleGraph, runtime) {
  161. return Dependency.NO_EXPORTS_REFERENCED;
  162. }
  163. /**
  164. * Returns name of the variable for the import.
  165. * @param {ModuleGraph} moduleGraph the module graph
  166. * @returns {string} name of the variable for the import
  167. */
  168. getImportVar(moduleGraph) {
  169. const module = /** @type {Module} */ (moduleGraph.getParentModule(this));
  170. const importedModule = /** @type {Module} */ (moduleGraph.getModule(this));
  171. const meta = moduleGraph.getMeta(module);
  172. const isDeferred =
  173. ImportPhaseUtils.isDefer(this.phase) &&
  174. !(/** @type {BuildMeta} */ (importedModule.buildMeta).async);
  175. const metaKey = isDeferred ? "deferredImportVarMap" : "importVarMap";
  176. let importVarMap = meta[metaKey];
  177. if (!importVarMap) {
  178. meta[metaKey] = importVarMap =
  179. /** @type {Map<Module, string>} */
  180. (new Map());
  181. }
  182. let importVar = importVarMap.get(importedModule);
  183. if (importVar) return importVar;
  184. importVar = `${Template.toIdentifier(this.userRequest)}__WEBPACK_${
  185. isDeferred ? "DEFERRED_" : ""
  186. }IMPORTED_MODULE_${importVarMap.size}__`;
  187. importVarMap.set(importedModule, importVar);
  188. return importVar;
  189. }
  190. /**
  191. * Gets module exports.
  192. * @param {DependencyTemplateContext} context the template context
  193. * @returns {string} the expression
  194. */
  195. getModuleExports({
  196. runtimeTemplate,
  197. moduleGraph,
  198. chunkGraph,
  199. runtimeRequirements
  200. }) {
  201. return runtimeTemplate.moduleExports({
  202. module: moduleGraph.getModule(this),
  203. chunkGraph,
  204. request: this.request,
  205. runtimeRequirements
  206. });
  207. }
  208. /**
  209. * Gets import statement.
  210. * @param {boolean} update create new variables or update existing one
  211. * @param {DependencyTemplateContext} templateContext the template context
  212. * @returns {[string, string]} the import statement and the compat statement
  213. */
  214. getImportStatement(
  215. update,
  216. { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements }
  217. ) {
  218. return runtimeTemplate.importStatement({
  219. update,
  220. module: /** @type {Module} */ (moduleGraph.getModule(this)),
  221. moduleGraph,
  222. chunkGraph,
  223. importVar: this.getImportVar(moduleGraph),
  224. request: this.request,
  225. originModule: module,
  226. runtimeRequirements,
  227. dependency: this
  228. });
  229. }
  230. /**
  231. * Gets linking errors.
  232. * @param {ModuleGraph} moduleGraph module graph
  233. * @param {Ids} ids imported ids
  234. * @param {string} additionalMessage extra info included in the error message
  235. * @returns {WebpackError[] | undefined} errors
  236. */
  237. getLinkingErrors(moduleGraph, ids, additionalMessage) {
  238. // Source phase imports don't have exports to check
  239. if (ImportPhaseUtils.isSource(this.phase)) {
  240. return;
  241. }
  242. const importedModule = moduleGraph.getModule(this);
  243. // ignore errors for missing or failed modules
  244. if (!importedModule || importedModule.getNumberOfErrors() > 0) {
  245. return;
  246. }
  247. const parentModule =
  248. /** @type {Module} */
  249. (moduleGraph.getParentModule(this));
  250. const exportsType = importedModule.getExportsType(
  251. moduleGraph,
  252. /** @type {BuildMeta} */ (parentModule.buildMeta).strictHarmonyModule
  253. );
  254. if (exportsType === "namespace" || exportsType === "default-with-named") {
  255. if (ids.length === 0) {
  256. return;
  257. }
  258. if (
  259. (exportsType !== "default-with-named" || ids[0] !== "default") &&
  260. moduleGraph.isExportProvided(importedModule, ids) === false
  261. ) {
  262. // We are sure that it's not provided
  263. // Try to provide detailed info in the error message
  264. let pos = 0;
  265. let exportsInfo = moduleGraph.getExportsInfo(importedModule);
  266. while (pos < ids.length && exportsInfo) {
  267. const id = ids[pos++];
  268. const exportInfo = exportsInfo.getReadOnlyExportInfo(id);
  269. if (exportInfo.provided === false) {
  270. // We are sure that it's not provided
  271. const providedExports = exportsInfo.getProvidedExports();
  272. const moreInfo = !Array.isArray(providedExports)
  273. ? " (possible exports unknown)"
  274. : providedExports.length === 0
  275. ? " (module has no exports)"
  276. : ` (possible exports: ${providedExports.join(", ")})`;
  277. return [
  278. new HarmonyLinkingError(
  279. `export ${ids
  280. .slice(0, pos)
  281. .map((id) => `'${id}'`)
  282. .join(".")} ${additionalMessage} was not found in '${
  283. this.userRequest
  284. }'${moreInfo}`
  285. )
  286. ];
  287. }
  288. exportsInfo =
  289. /** @type {ExportsInfo} */
  290. (exportInfo.getNestedExportsInfo());
  291. }
  292. // General error message
  293. return [
  294. new HarmonyLinkingError(
  295. `export ${ids
  296. .map((id) => `'${id}'`)
  297. .join(".")} ${additionalMessage} was not found in '${
  298. this.userRequest
  299. }'`
  300. )
  301. ];
  302. }
  303. }
  304. switch (exportsType) {
  305. case "default-only":
  306. // It's has only a default export
  307. if (ids.length > 0 && ids[0] !== "default") {
  308. // In strict harmony modules we only support the default export
  309. return [
  310. new HarmonyLinkingError(
  311. `Can't import the named export ${ids
  312. .map((id) => `'${id}'`)
  313. .join(
  314. "."
  315. )} ${additionalMessage} from default-exporting module (only default export is available)`
  316. )
  317. ];
  318. }
  319. break;
  320. case "default-with-named":
  321. // It has a default export and named properties redirect
  322. // In some cases we still want to warn here
  323. if (
  324. ids.length > 0 &&
  325. ids[0] !== "default" &&
  326. /** @type {BuildMeta} */
  327. (importedModule.buildMeta).defaultObject === "redirect-warn"
  328. ) {
  329. // For these modules only the default export is supported
  330. return [
  331. new HarmonyLinkingError(
  332. `Should not import the named export ${ids
  333. .map((id) => `'${id}'`)
  334. .join(
  335. "."
  336. )} ${additionalMessage} from default-exporting module (only default export is available soon)`
  337. )
  338. ];
  339. }
  340. break;
  341. }
  342. }
  343. /**
  344. * Serializes this instance into the provided serializer context.
  345. * @param {ObjectSerializerContext} context context
  346. */
  347. serialize(context) {
  348. const { write } = context;
  349. write(this.attributes);
  350. write(this.phase);
  351. write(this._lazyMake);
  352. super.serialize(context);
  353. }
  354. /**
  355. * Restores this instance from the provided deserializer context.
  356. * @param {ObjectDeserializerContext} context context
  357. */
  358. deserialize(context) {
  359. const { read } = context;
  360. this.attributes = read();
  361. this.phase = read();
  362. this._lazyMake = read();
  363. super.deserialize(context);
  364. }
  365. }
  366. /** @type {WeakMap<Module, WeakMap<Module, RuntimeSpec | boolean>>} */
  367. const importEmittedMap = new WeakMap();
  368. HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends (
  369. ModuleDependency.Template
  370. ) {
  371. /**
  372. * Applies the plugin by registering its hooks on the compiler.
  373. * @param {Dependency} dependency the dependency for which the template should be applied
  374. * @param {ReplaceSource} source the current replace source which can be modified
  375. * @param {DependencyTemplateContext} templateContext the context object
  376. * @returns {void}
  377. */
  378. apply(dependency, source, templateContext) {
  379. const dep = /** @type {HarmonyImportDependency} */ (dependency);
  380. const { module, chunkGraph, moduleGraph, runtime } = templateContext;
  381. const connection = moduleGraph.getConnection(dep);
  382. // deferred by lazy barrel: never resolved, must not render a missing module
  383. if (connection === undefined && dep.isLazy()) {
  384. return;
  385. }
  386. if (connection && !connection.isTargetActive(runtime)) return;
  387. const referencedModule = connection && connection.module;
  388. if (
  389. connection &&
  390. connection.weak &&
  391. referencedModule &&
  392. chunkGraph.getModuleId(referencedModule) === null
  393. ) {
  394. // in weak references, module might not be in any chunk
  395. // but that's ok, we don't need that logic in this case
  396. return;
  397. }
  398. const moduleKey = referencedModule
  399. ? referencedModule.identifier()
  400. : dep.request;
  401. const key = `${
  402. ImportPhaseUtils.isDefer(dep.phase)
  403. ? "deferred "
  404. : ImportPhaseUtils.isSource(dep.phase)
  405. ? "source "
  406. : ""
  407. }harmony import ${moduleKey}`;
  408. const runtimeCondition = dep.weak
  409. ? false
  410. : connection
  411. ? filterRuntime(runtime, (r) => connection.isTargetActive(r))
  412. : true;
  413. if (module && referencedModule) {
  414. let emittedModules = importEmittedMap.get(module);
  415. if (emittedModules === undefined) {
  416. emittedModules = new WeakMap();
  417. importEmittedMap.set(module, emittedModules);
  418. }
  419. let mergedRuntimeCondition = runtimeCondition;
  420. const oldRuntimeCondition = emittedModules.get(referencedModule) || false;
  421. if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) {
  422. if (mergedRuntimeCondition === false || oldRuntimeCondition === true) {
  423. mergedRuntimeCondition = oldRuntimeCondition;
  424. } else {
  425. mergedRuntimeCondition = mergeRuntime(
  426. oldRuntimeCondition,
  427. mergedRuntimeCondition
  428. );
  429. }
  430. }
  431. emittedModules.set(referencedModule, mergedRuntimeCondition);
  432. }
  433. const importStatement = dep.getImportStatement(false, templateContext);
  434. if (
  435. referencedModule &&
  436. templateContext.moduleGraph.isAsync(referencedModule)
  437. ) {
  438. templateContext.initFragments.push(
  439. new ConditionalInitFragment(
  440. importStatement[0],
  441. InitFragment.STAGE_HARMONY_IMPORTS,
  442. /** @type {number} */ (dep.sourceOrder),
  443. key,
  444. runtimeCondition
  445. )
  446. );
  447. const importVar = dep.getImportVar(templateContext.moduleGraph);
  448. // When the consuming module is emitted as a generator (target without
  449. // `async`/`await`), the dependency `await` must become `yield`.
  450. const generatorLowered = isGeneratorLowered(
  451. /** @type {Module} */ (module),
  452. moduleGraph,
  453. templateContext.runtimeTemplate
  454. );
  455. templateContext.initFragments.push(
  456. new AwaitDependenciesInitFragment(
  457. new Map([[importVar, importVar]]),
  458. generatorLowered
  459. )
  460. );
  461. templateContext.initFragments.push(
  462. new ConditionalInitFragment(
  463. importStatement[1],
  464. InitFragment.STAGE_ASYNC_HARMONY_IMPORTS,
  465. /** @type {number} */ (dep.sourceOrder),
  466. `${key} compat`,
  467. runtimeCondition
  468. )
  469. );
  470. } else {
  471. templateContext.initFragments.push(
  472. new ConditionalInitFragment(
  473. importStatement[0] + importStatement[1],
  474. InitFragment.STAGE_HARMONY_IMPORTS,
  475. /** @type {number} */ (dep.sourceOrder),
  476. key,
  477. runtimeCondition
  478. )
  479. );
  480. }
  481. }
  482. /**
  483. * Gets import emitted runtime.
  484. * @param {Module} module the module
  485. * @param {Module} referencedModule the referenced module
  486. * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted
  487. */
  488. static getImportEmittedRuntime(module, referencedModule) {
  489. const emittedModules = importEmittedMap.get(module);
  490. if (emittedModules === undefined) return false;
  491. return emittedModules.get(referencedModule) || false;
  492. }
  493. };
  494. HarmonyImportDependency.ExportPresenceModes = ExportPresenceModes;
  495. HarmonyImportDependency.getNonOptionalPart = getNonOptionalPart;
  496. module.exports = HarmonyImportDependency;