RootsPlugin.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const forEachBail = require("./forEachBail");
  7. /** @typedef {import("./Resolver")} Resolver */
  8. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  9. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  10. class RootsPlugin {
  11. /**
  12. * @param {string | ResolveStepHook} source source hook
  13. * @param {Set<string>} roots roots
  14. * @param {string | ResolveStepHook} target target hook
  15. */
  16. constructor(source, roots, target) {
  17. this.roots = Array.from(roots);
  18. this.source = source;
  19. this.target = target;
  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("RootsPlugin", (request, resolveContext, callback) => {
  30. const req = request.request;
  31. if (!req) return callback();
  32. if (!req.startsWith("/")) return callback();
  33. forEachBail(
  34. this.roots,
  35. /**
  36. * @param {string} root root
  37. * @param {(err?: null|Error, result?: null|ResolveRequest) => void} callback callback
  38. * @returns {void}
  39. */
  40. (root, callback) => {
  41. const path = resolver.join(root, req.slice(1));
  42. /** @type {ResolveRequest} */
  43. const obj = {
  44. ...request,
  45. path,
  46. relativePath: request.relativePath && path
  47. };
  48. resolver.doResolve(
  49. target,
  50. obj,
  51. `root path ${root}`,
  52. resolveContext,
  53. callback
  54. );
  55. },
  56. callback
  57. );
  58. });
  59. }
  60. }
  61. module.exports = RootsPlugin;