SelfReferencePlugin.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const DescriptionFileUtils = require("./DescriptionFileUtils");
  7. /** @typedef {import("./Resolver")} Resolver */
  8. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  9. const slashCode = "/".charCodeAt(0);
  10. module.exports = class SelfReferencePlugin {
  11. /**
  12. * @param {string | ResolveStepHook} source source
  13. * @param {string | string[]} fieldNamePath name path
  14. * @param {string | ResolveStepHook} target target
  15. */
  16. constructor(source, fieldNamePath, target) {
  17. this.source = source;
  18. this.target = target;
  19. this.fieldName = fieldNamePath;
  20. }
  21. /**
  22. * @param {Resolver} resolver the resolver
  23. * @returns {void}
  24. */
  25. apply(resolver) {
  26. const target = resolver.ensureHook(this.target);
  27. resolver
  28. .getHook(this.source)
  29. .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => {
  30. if (!request.descriptionFilePath) return callback();
  31. const req = request.request;
  32. if (!req) return callback();
  33. // Feature is only enabled when an exports field is present
  34. const exportsField = DescriptionFileUtils.getField(
  35. request.descriptionFileData,
  36. this.fieldName
  37. );
  38. if (!exportsField) return callback();
  39. const name = DescriptionFileUtils.getField(
  40. request.descriptionFileData,
  41. "name"
  42. );
  43. if (typeof name !== "string") return callback();
  44. if (
  45. req.startsWith(name) &&
  46. (req.length === name.length ||
  47. req.charCodeAt(name.length) === slashCode)
  48. ) {
  49. const remainingRequest = `.${req.slice(name.length)}`;
  50. const obj = {
  51. ...request,
  52. request: remainingRequest,
  53. path: /** @type {string} */ (request.descriptionFileRoot),
  54. relativePath: "."
  55. };
  56. resolver.doResolve(
  57. target,
  58. obj,
  59. "self reference",
  60. resolveContext,
  61. callback
  62. );
  63. } else {
  64. return callback();
  65. }
  66. });
  67. }
  68. };