RootsPlugin.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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").ResolveStepHook} ResolveStepHook */
  9. class RootsPlugin {
  10. /**
  11. * @param {string | ResolveStepHook} source source hook
  12. * @param {Set<string>} roots roots
  13. * @param {string | ResolveStepHook} target target hook
  14. */
  15. constructor(source, roots, target) {
  16. this.roots = Array.from(roots);
  17. this.source = source;
  18. this.target = target;
  19. }
  20. /**
  21. * @param {Resolver} resolver the resolver
  22. * @returns {void}
  23. */
  24. apply(resolver) {
  25. const target = resolver.ensureHook(this.target);
  26. resolver
  27. .getHook(this.source)
  28. .tapAsync("RootsPlugin", (request, resolveContext, callback) => {
  29. const req = request.request;
  30. if (!req) return callback();
  31. if (!req.startsWith("/")) return callback();
  32. forEachBail(
  33. this.roots,
  34. (root, callback) => {
  35. const path = resolver.join(root, req.slice(1));
  36. const obj = {
  37. ...request,
  38. path,
  39. relativePath: request.relativePath && path
  40. };
  41. resolver.doResolve(
  42. target,
  43. obj,
  44. `root path ${root}`,
  45. resolveContext,
  46. callback
  47. );
  48. },
  49. callback
  50. );
  51. });
  52. }
  53. }
  54. module.exports = RootsPlugin;