JoinRequestPartPlugin.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Resolver")} Resolver */
  7. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  8. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  9. const namespaceStartCharCode = "@".charCodeAt(0);
  10. module.exports = class JoinRequestPartPlugin {
  11. /**
  12. * @param {string | ResolveStepHook} source source
  13. * @param {string | ResolveStepHook} target target
  14. */
  15. constructor(source, target) {
  16. this.source = source;
  17. this.target = target;
  18. }
  19. /**
  20. * @param {Resolver} resolver the resolver
  21. * @returns {void}
  22. */
  23. apply(resolver) {
  24. const target = resolver.ensureHook(this.target);
  25. resolver
  26. .getHook(this.source)
  27. .tapAsync(
  28. "JoinRequestPartPlugin",
  29. (request, resolveContext, callback) => {
  30. const req = request.request || "";
  31. let i = req.indexOf("/", 3);
  32. if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) {
  33. i = req.indexOf("/", i + 1);
  34. }
  35. /** @type {string} */
  36. let moduleName;
  37. /** @type {string} */
  38. let remainingRequest;
  39. /** @type {boolean} */
  40. let fullySpecified;
  41. if (i < 0) {
  42. moduleName = req;
  43. remainingRequest = ".";
  44. fullySpecified = false;
  45. } else {
  46. moduleName = req.slice(0, i);
  47. remainingRequest = "." + req.slice(i);
  48. fullySpecified = /** @type {boolean} */ (request.fullySpecified);
  49. }
  50. /** @type {ResolveRequest} */
  51. const obj = {
  52. ...request,
  53. path: resolver.join(
  54. /** @type {string} */
  55. (request.path),
  56. moduleName
  57. ),
  58. relativePath:
  59. request.relativePath &&
  60. resolver.join(request.relativePath, moduleName),
  61. request: remainingRequest,
  62. fullySpecified
  63. };
  64. resolver.doResolve(target, obj, null, resolveContext, callback);
  65. }
  66. );
  67. }
  68. };