absolutePath.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. /** @typedef {import("ajv").Ajv} Ajv */
  7. /** @typedef {import("ajv").ValidateFunction} ValidateFunction */
  8. /** @typedef {import("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */
  9. /**
  10. * @param {string} message
  11. * @param {object} schema
  12. * @param {string} data
  13. * @returns {SchemaUtilErrorObject}
  14. */
  15. function errorMessage(message, schema, data) {
  16. return {
  17. // @ts-ignore
  18. // eslint-disable-next-line no-undefined
  19. dataPath: undefined,
  20. // @ts-ignore
  21. // eslint-disable-next-line no-undefined
  22. schemaPath: undefined,
  23. keyword: 'absolutePath',
  24. params: {
  25. absolutePath: data
  26. },
  27. message,
  28. parentSchema: schema
  29. };
  30. }
  31. /**
  32. * @param {boolean} shouldBeAbsolute
  33. * @param {object} schema
  34. * @param {string} data
  35. * @returns {SchemaUtilErrorObject}
  36. */
  37. function getErrorFor(shouldBeAbsolute, schema, data) {
  38. const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify(data)} is an absolute path!`;
  39. return errorMessage(message, schema, data);
  40. }
  41. /**
  42. *
  43. * @param {Ajv} ajv
  44. * @returns {Ajv}
  45. */
  46. function addAbsolutePathKeyword(ajv) {
  47. ajv.addKeyword('absolutePath', {
  48. errors: true,
  49. type: 'string',
  50. compile(schema, parentSchema) {
  51. /** @type {ValidateFunction} */
  52. const callback = data => {
  53. let passes = true;
  54. const isExclamationMarkPresent = data.includes('!');
  55. if (isExclamationMarkPresent) {
  56. callback.errors = [errorMessage(`The provided value ${JSON.stringify(data)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`, parentSchema, data)];
  57. passes = false;
  58. } // ?:[A-Za-z]:\\ - Windows absolute path
  59. // \\\\ - Windows network absolute path
  60. // \/ - Unix-like OS absolute path
  61. const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data);
  62. if (!isCorrectAbsolutePath) {
  63. callback.errors = [getErrorFor(schema, parentSchema, data)];
  64. passes = false;
  65. }
  66. return passes;
  67. };
  68. callback.errors = [];
  69. return callback;
  70. }
  71. });
  72. return ajv;
  73. }
  74. var _default = addAbsolutePathKeyword;
  75. exports.default = _default;