ExportsFieldPlugin.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const DescriptionFileUtils = require("./DescriptionFileUtils");
  7. const forEachBail = require("./forEachBail");
  8. const { processExportsField } = require("./util/entrypoints");
  9. const { parseIdentifier } = require("./util/identifier");
  10. const {
  11. invalidSegmentRegEx,
  12. deprecatedInvalidSegmentRegEx
  13. } = require("./util/path");
  14. /** @typedef {import("./Resolver")} Resolver */
  15. /** @typedef {import("./Resolver").JsonObject} JsonObject */
  16. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  17. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  18. /** @typedef {import("./util/entrypoints").ExportsField} ExportsField */
  19. /** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */
  20. module.exports = class ExportsFieldPlugin {
  21. /**
  22. * @param {string | ResolveStepHook} source source
  23. * @param {Set<string>} conditionNames condition names
  24. * @param {string | string[]} fieldNamePath name path
  25. * @param {string | ResolveStepHook} target target
  26. */
  27. constructor(source, conditionNames, fieldNamePath, target) {
  28. this.source = source;
  29. this.target = target;
  30. this.conditionNames = conditionNames;
  31. this.fieldName = fieldNamePath;
  32. /** @type {WeakMap<JsonObject, FieldProcessor>} */
  33. this.fieldProcessorCache = new WeakMap();
  34. }
  35. /**
  36. * @param {Resolver} resolver the resolver
  37. * @returns {void}
  38. */
  39. apply(resolver) {
  40. const target = resolver.ensureHook(this.target);
  41. resolver
  42. .getHook(this.source)
  43. .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => {
  44. // When there is no description file, abort
  45. if (!request.descriptionFilePath) return callback();
  46. if (
  47. // When the description file is inherited from parent, abort
  48. // (There is no description file inside of this package)
  49. request.relativePath !== "." ||
  50. request.request === undefined
  51. )
  52. return callback();
  53. const remainingRequest =
  54. request.query || request.fragment
  55. ? (request.request === "." ? "./" : request.request) +
  56. request.query +
  57. request.fragment
  58. : request.request;
  59. const exportsField =
  60. /** @type {ExportsField|null|undefined} */
  61. (
  62. DescriptionFileUtils.getField(
  63. /** @type {JsonObject} */ (request.descriptionFileData),
  64. this.fieldName
  65. )
  66. );
  67. if (!exportsField) return callback();
  68. if (request.directory) {
  69. return callback(
  70. new Error(
  71. `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)`
  72. )
  73. );
  74. }
  75. /** @type {string[]} */
  76. let paths;
  77. /** @type {string | null} */
  78. let usedField;
  79. try {
  80. // We attach the cache to the description file instead of the exportsField value
  81. // because we use a WeakMap and the exportsField could be a string too.
  82. // Description file is always an object when exports field can be accessed.
  83. let fieldProcessor = this.fieldProcessorCache.get(
  84. /** @type {JsonObject} */ (request.descriptionFileData)
  85. );
  86. if (fieldProcessor === undefined) {
  87. fieldProcessor = processExportsField(exportsField);
  88. this.fieldProcessorCache.set(
  89. /** @type {JsonObject} */ (request.descriptionFileData),
  90. fieldProcessor
  91. );
  92. }
  93. [paths, usedField] = fieldProcessor(
  94. remainingRequest,
  95. this.conditionNames
  96. );
  97. } catch (/** @type {unknown} */ err) {
  98. if (resolveContext.log) {
  99. resolveContext.log(
  100. `Exports field in ${request.descriptionFilePath} can't be processed: ${err}`
  101. );
  102. }
  103. return callback(/** @type {Error} */ (err));
  104. }
  105. if (paths.length === 0) {
  106. return callback(
  107. new Error(
  108. `Package path ${remainingRequest} is not exported from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})`
  109. )
  110. );
  111. }
  112. forEachBail(
  113. paths,
  114. /**
  115. * @param {string} p path
  116. * @param {(err?: null|Error, result?: null|ResolveRequest) => void} callback callback
  117. * @param {number} i index
  118. * @returns {void}
  119. */
  120. (p, callback, i) => {
  121. const parsedIdentifier = parseIdentifier(p);
  122. if (!parsedIdentifier) return callback();
  123. const [relativePath, query, fragment] = parsedIdentifier;
  124. if (relativePath.length === 0 || !relativePath.startsWith("./")) {
  125. if (paths.length === i) {
  126. return callback(
  127. new Error(
  128. `Invalid "exports" target "${p}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`
  129. )
  130. );
  131. }
  132. return callback();
  133. }
  134. if (
  135. invalidSegmentRegEx.exec(relativePath.slice(2)) !== null &&
  136. deprecatedInvalidSegmentRegEx.test(relativePath.slice(2)) !== null
  137. ) {
  138. if (paths.length === i) {
  139. return callback(
  140. new Error(
  141. `Invalid "exports" target "${p}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`
  142. )
  143. );
  144. }
  145. return callback();
  146. }
  147. /** @type {ResolveRequest} */
  148. const obj = {
  149. ...request,
  150. request: undefined,
  151. path: resolver.join(
  152. /** @type {string} */ (request.descriptionFileRoot),
  153. relativePath
  154. ),
  155. relativePath,
  156. query,
  157. fragment
  158. };
  159. resolver.doResolve(
  160. target,
  161. obj,
  162. "using exports field: " + p,
  163. resolveContext,
  164. (err, result) => {
  165. if (err) return callback(err);
  166. // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400
  167. if (result === undefined) return callback(null, null);
  168. callback(null, result);
  169. }
  170. );
  171. },
  172. /**
  173. * @param {null|Error} [err] error
  174. * @param {null|ResolveRequest} [result] result
  175. * @returns {void}
  176. */
  177. (err, result) => callback(err, result || null)
  178. );
  179. });
  180. }
  181. };