ConditionalPlugin.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. module.exports = class ConditionalPlugin {
  10. /**
  11. * @param {string | ResolveStepHook} source source
  12. * @param {Partial<ResolveRequest>} test compare object
  13. * @param {string | null} message log message
  14. * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches
  15. * @param {string | ResolveStepHook} target target
  16. */
  17. constructor(source, test, message, allowAlternatives, target) {
  18. this.source = source;
  19. this.test = test;
  20. this.message = message;
  21. this.allowAlternatives = allowAlternatives;
  22. this.target = target;
  23. }
  24. /**
  25. * @param {Resolver} resolver the resolver
  26. * @returns {void}
  27. */
  28. apply(resolver) {
  29. const target = resolver.ensureHook(this.target);
  30. const { test, message, allowAlternatives } = this;
  31. const keys = /** @type {(keyof ResolveRequest)[]} */ (Object.keys(test));
  32. resolver
  33. .getHook(this.source)
  34. .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => {
  35. for (const prop of keys) {
  36. if (request[prop] !== test[prop]) return callback();
  37. }
  38. resolver.doResolve(
  39. target,
  40. request,
  41. message,
  42. resolveContext,
  43. allowAlternatives
  44. ? callback
  45. : (err, result) => {
  46. if (err) return callback(err);
  47. // Don't allow other alternatives
  48. if (result === undefined) return callback(null, null);
  49. callback(null, result);
  50. }
  51. );
  52. });
  53. }
  54. };