RestrictionsPlugin.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. /** @typedef {import("./Resolver")} Resolver */
  7. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  8. const slashCode = "/".charCodeAt(0);
  9. const backslashCode = "\\".charCodeAt(0);
  10. const isInside = (path, parent) => {
  11. if (!path.startsWith(parent)) return false;
  12. if (path.length === parent.length) return true;
  13. const charCode = path.charCodeAt(parent.length);
  14. return charCode === slashCode || charCode === backslashCode;
  15. };
  16. module.exports = class RestrictionsPlugin {
  17. /**
  18. * @param {string | ResolveStepHook} source source
  19. * @param {Set<string | RegExp>} restrictions restrictions
  20. */
  21. constructor(source, restrictions) {
  22. this.source = source;
  23. this.restrictions = restrictions;
  24. }
  25. /**
  26. * @param {Resolver} resolver the resolver
  27. * @returns {void}
  28. */
  29. apply(resolver) {
  30. resolver
  31. .getHook(this.source)
  32. .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => {
  33. if (typeof request.path === "string") {
  34. const path = request.path;
  35. for (const rule of this.restrictions) {
  36. if (typeof rule === "string") {
  37. if (!isInside(path, rule)) {
  38. if (resolveContext.log) {
  39. resolveContext.log(
  40. `${path} is not inside of the restriction ${rule}`
  41. );
  42. }
  43. return callback(null, null);
  44. }
  45. } else if (!rule.test(path)) {
  46. if (resolveContext.log) {
  47. resolveContext.log(
  48. `${path} doesn't match the restriction ${rule}`
  49. );
  50. }
  51. return callback(null, null);
  52. }
  53. }
  54. }
  55. callback();
  56. });
  57. }
  58. };