ajv.absolutePath.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. const errorMessage = (schema, data, message) => ({
  3. keyword: "absolutePath",
  4. params: { absolutePath: data },
  5. message: message,
  6. parentSchema: schema
  7. });
  8. const getErrorFor = (shouldBeAbsolute, data, schema) => {
  9. const message = shouldBeAbsolute
  10. ? `The provided value ${JSON.stringify(data)} is not an absolute path!`
  11. : `A relative path is expected. However, the provided value ${JSON.stringify(
  12. data
  13. )} is an absolute path!`;
  14. return errorMessage(schema, data, message);
  15. };
  16. module.exports = ajv =>
  17. ajv.addKeyword("absolutePath", {
  18. errors: true,
  19. type: "string",
  20. compile(expected, schema) {
  21. function callback(data) {
  22. let passes = true;
  23. const isExclamationMarkPresent = data.includes("!");
  24. if (isExclamationMarkPresent) {
  25. callback.errors = [
  26. errorMessage(
  27. schema,
  28. data,
  29. `The provided value ${JSON.stringify(
  30. data
  31. )} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`
  32. )
  33. ];
  34. passes = false;
  35. }
  36. // ?:[A-Za-z]:\\ - Windows absolute path
  37. // \\\\ - Windows network absolute path
  38. // \/ - Unix-like OS absolute path
  39. const isCorrectAbsolutePath =
  40. expected === /^(?:[A-Za-z]:\\|\\\\|\/)/.test(data);
  41. if (!isCorrectAbsolutePath) {
  42. callback.errors = [getErrorFor(expected, data, schema)];
  43. passes = false;
  44. }
  45. return passes;
  46. }
  47. callback.errors = [];
  48. return callback;
  49. }
  50. });