absolutePath.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */
  8. /**
  9. *
  10. * @param {string} data
  11. * @param {object} schema
  12. * @param {string} message
  13. * @returns {object} // Todo `returns` should be `SchemaUtilErrorObject`
  14. */
  15. function errorMessage(message, schema, data) {
  16. return {
  17. keyword: 'absolutePath',
  18. params: {
  19. absolutePath: data
  20. },
  21. message,
  22. parentSchema: schema
  23. };
  24. }
  25. /**
  26. * @param {boolean} shouldBeAbsolute
  27. * @param {object} schema
  28. * @param {string} data
  29. * @returns {object}
  30. */
  31. function getErrorFor(shouldBeAbsolute, schema, data) {
  32. 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!`;
  33. return errorMessage(message, schema, data);
  34. }
  35. /**
  36. *
  37. * @param {Ajv} ajv
  38. * @returns {Ajv}
  39. */
  40. function addAbsolutePathKeyword(ajv) {
  41. ajv.addKeyword('absolutePath', {
  42. errors: true,
  43. type: 'string',
  44. compile(schema, parentSchema) {
  45. /**
  46. * @param {any} data
  47. * @returns {boolean}
  48. */
  49. function callback(data) {
  50. let passes = true;
  51. const isExclamationMarkPresent = data.includes('!');
  52. if (isExclamationMarkPresent) {
  53. 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)];
  54. passes = false;
  55. } // ?:[A-Za-z]:\\ - Windows absolute path
  56. // \\\\ - Windows network absolute path
  57. // \/ - Unix-like OS absolute path
  58. const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data);
  59. if (!isCorrectAbsolutePath) {
  60. callback.errors = [getErrorFor(schema, parentSchema, data)];
  61. passes = false;
  62. }
  63. return passes;
  64. }
  65. /** @type {null | Array<SchemaUtilErrorObject>}*/
  66. callback.errors = [];
  67. return callback;
  68. }
  69. });
  70. return ajv;
  71. }
  72. var _default = addAbsolutePathKeyword;
  73. exports.default = _default;