ValidationError.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _memorize = _interopRequireDefault(require("./util/memorize"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. /** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
  9. /** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
  10. /** @typedef {import("./validate").Schema} Schema */
  11. /** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */
  12. /** @typedef {import("./validate").PostFormatter} PostFormatter */
  13. /** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */
  14. /** @enum {number} */
  15. const SPECIFICITY = {
  16. type: 1,
  17. not: 1,
  18. oneOf: 1,
  19. anyOf: 1,
  20. if: 1,
  21. enum: 1,
  22. const: 1,
  23. instanceof: 1,
  24. required: 2,
  25. pattern: 2,
  26. patternRequired: 2,
  27. format: 2,
  28. formatMinimum: 2,
  29. formatMaximum: 2,
  30. minimum: 2,
  31. exclusiveMinimum: 2,
  32. maximum: 2,
  33. exclusiveMaximum: 2,
  34. multipleOf: 2,
  35. uniqueItems: 2,
  36. contains: 2,
  37. minLength: 2,
  38. maxLength: 2,
  39. minItems: 2,
  40. maxItems: 2,
  41. minProperties: 2,
  42. maxProperties: 2,
  43. dependencies: 2,
  44. propertyNames: 2,
  45. additionalItems: 2,
  46. additionalProperties: 2,
  47. absolutePath: 2
  48. };
  49. /**
  50. * @param {string} value
  51. * @returns {value is number}
  52. */
  53. function isNumeric(value) {
  54. return /^-?\d+$/.test(value);
  55. }
  56. /**
  57. *
  58. * @param {Array<SchemaUtilErrorObject>} array
  59. * @param {(item: SchemaUtilErrorObject) => number} fn
  60. * @returns {Array<SchemaUtilErrorObject>}
  61. */
  62. function filterMax(array, fn) {
  63. const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0);
  64. return array.filter(item => fn(item) === evaluatedMax);
  65. }
  66. /**
  67. *
  68. * @param {Array<SchemaUtilErrorObject>} children
  69. * @returns {Array<SchemaUtilErrorObject>}
  70. */
  71. function filterChildren(children) {
  72. let newChildren = children;
  73. newChildren = filterMax(newChildren,
  74. /**
  75. *
  76. * @param {SchemaUtilErrorObject} error
  77. * @returns {number}
  78. */
  79. error => error.instancePath ? error.instancePath.length : 0);
  80. newChildren = filterMax(newChildren,
  81. /**
  82. * @param {SchemaUtilErrorObject} error
  83. * @returns {number}
  84. */
  85. error => SPECIFICITY[/** @type {keyof typeof SPECIFICITY} */error.keyword] || 2);
  86. return newChildren;
  87. }
  88. /**
  89. * Find all children errors
  90. * @param {Array<SchemaUtilErrorObject>} children
  91. * @param {Array<string>} schemaPaths
  92. * @return {number} returns index of first child
  93. */
  94. function findAllChildren(children, schemaPaths) {
  95. let i = children.length - 1;
  96. const predicate =
  97. /**
  98. * @param {string} schemaPath
  99. * @returns {boolean}
  100. */
  101. schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0;
  102. while (i > -1 && !schemaPaths.every(predicate)) {
  103. if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") {
  104. const refs = extractRefs(children[i]);
  105. const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath));
  106. i = childrenStart - 1;
  107. } else {
  108. i -= 1;
  109. }
  110. }
  111. return i + 1;
  112. }
  113. /**
  114. * Extracts all refs from schema
  115. * @param {SchemaUtilErrorObject} error
  116. * @return {Array<string>}
  117. */
  118. function extractRefs(error) {
  119. const {
  120. schema
  121. } = error;
  122. if (!Array.isArray(schema)) {
  123. return [];
  124. }
  125. return schema.map(({
  126. $ref
  127. }) => $ref).filter(s => s);
  128. }
  129. /**
  130. * Groups children by their first level parent (assuming that error is root)
  131. * @param {Array<SchemaUtilErrorObject>} children
  132. * @return {Array<SchemaUtilErrorObject>}
  133. */
  134. function groupChildrenByFirstChild(children) {
  135. const result = [];
  136. let i = children.length - 1;
  137. while (i > 0) {
  138. const child = children[i];
  139. if (child.keyword === "anyOf" || child.keyword === "oneOf") {
  140. const refs = extractRefs(child);
  141. const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath));
  142. if (childrenStart !== i) {
  143. result.push(Object.assign({}, child, {
  144. children: children.slice(childrenStart, i)
  145. }));
  146. i = childrenStart;
  147. } else {
  148. result.push(child);
  149. }
  150. } else {
  151. result.push(child);
  152. }
  153. i -= 1;
  154. }
  155. if (i === 0) {
  156. result.push(children[i]);
  157. }
  158. return result.reverse();
  159. }
  160. /**
  161. * @param {string} str
  162. * @param {string} prefix
  163. * @returns {string}
  164. */
  165. function indent(str, prefix) {
  166. return str.replace(/\n(?!$)/g, `\n${prefix}`);
  167. }
  168. /**
  169. * @param {Schema} schema
  170. * @returns {schema is (Schema & {not: Schema})}
  171. */
  172. function hasNotInSchema(schema) {
  173. return !!schema.not;
  174. }
  175. /**
  176. * @param {Schema} schema
  177. * @return {Schema}
  178. */
  179. function findFirstTypedSchema(schema) {
  180. if (hasNotInSchema(schema)) {
  181. return findFirstTypedSchema(schema.not);
  182. }
  183. return schema;
  184. }
  185. /**
  186. * @param {Schema} schema
  187. * @return {boolean}
  188. */
  189. function canApplyNot(schema) {
  190. const typedSchema = findFirstTypedSchema(schema);
  191. return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema);
  192. }
  193. /**
  194. * @param {any} maybeObj
  195. * @returns {boolean}
  196. */
  197. function isObject(maybeObj) {
  198. return typeof maybeObj === "object" && maybeObj !== null;
  199. }
  200. /**
  201. * @param {Schema} schema
  202. * @returns {boolean}
  203. */
  204. function likeNumber(schema) {
  205. return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined";
  206. }
  207. /**
  208. * @param {Schema} schema
  209. * @returns {boolean}
  210. */
  211. function likeInteger(schema) {
  212. return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined";
  213. }
  214. /**
  215. * @param {Schema} schema
  216. * @returns {boolean}
  217. */
  218. function likeString(schema) {
  219. return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined";
  220. }
  221. /**
  222. * @param {Schema} schema
  223. * @returns {boolean}
  224. */
  225. function likeBoolean(schema) {
  226. return schema.type === "boolean";
  227. }
  228. /**
  229. * @param {Schema} schema
  230. * @returns {boolean}
  231. */
  232. function likeArray(schema) {
  233. return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined";
  234. }
  235. /**
  236. * @param {Schema & {patternRequired?: Array<string>}} schema
  237. * @returns {boolean}
  238. */
  239. function likeObject(schema) {
  240. return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined";
  241. }
  242. /**
  243. * @param {Schema} schema
  244. * @returns {boolean}
  245. */
  246. function likeNull(schema) {
  247. return schema.type === "null";
  248. }
  249. /**
  250. * @param {string} type
  251. * @returns {string}
  252. */
  253. function getArticle(type) {
  254. if (/^[aeiou]/i.test(type)) {
  255. return "an";
  256. }
  257. return "a";
  258. }
  259. /**
  260. * @param {Schema=} schema
  261. * @returns {string}
  262. */
  263. function getSchemaNonTypes(schema) {
  264. if (!schema) {
  265. return "";
  266. }
  267. if (!schema.type) {
  268. if (likeNumber(schema) || likeInteger(schema)) {
  269. return " | should be any non-number";
  270. }
  271. if (likeString(schema)) {
  272. return " | should be any non-string";
  273. }
  274. if (likeArray(schema)) {
  275. return " | should be any non-array";
  276. }
  277. if (likeObject(schema)) {
  278. return " | should be any non-object";
  279. }
  280. }
  281. return "";
  282. }
  283. /**
  284. * @param {Array<string>} hints
  285. * @returns {string}
  286. */
  287. function formatHints(hints) {
  288. return hints.length > 0 ? `(${hints.join(", ")})` : "";
  289. }
  290. const getUtilHints = (0, _memorize.default)(() =>
  291. // eslint-disable-next-line global-require
  292. require("./util/hints"));
  293. /**
  294. * @param {Schema} schema
  295. * @param {boolean} logic
  296. * @returns {string[]}
  297. */
  298. function getHints(schema, logic) {
  299. if (likeNumber(schema) || likeInteger(schema)) {
  300. const util = getUtilHints();
  301. return util.numberHints(schema, logic);
  302. } else if (likeString(schema)) {
  303. const util = getUtilHints();
  304. return util.stringHints(schema, logic);
  305. }
  306. return [];
  307. }
  308. class ValidationError extends Error {
  309. /**
  310. * @param {Array<SchemaUtilErrorObject>} errors
  311. * @param {Schema} schema
  312. * @param {ValidationErrorConfiguration} configuration
  313. */
  314. constructor(errors, schema, configuration = {}) {
  315. super();
  316. /** @type {string} */
  317. this.name = "ValidationError";
  318. /** @type {Array<SchemaUtilErrorObject>} */
  319. this.errors = errors;
  320. /** @type {Schema} */
  321. this.schema = schema;
  322. let headerNameFromSchema;
  323. let baseDataPathFromSchema;
  324. if (schema.title && (!configuration.name || !configuration.baseDataPath)) {
  325. const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/);
  326. if (splittedTitleFromSchema) {
  327. if (!configuration.name) {
  328. [, headerNameFromSchema] = splittedTitleFromSchema;
  329. }
  330. if (!configuration.baseDataPath) {
  331. [,, baseDataPathFromSchema] = splittedTitleFromSchema;
  332. }
  333. }
  334. }
  335. /** @type {string} */
  336. this.headerName = configuration.name || headerNameFromSchema || "Object";
  337. /** @type {string} */
  338. this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration";
  339. /** @type {PostFormatter | null} */
  340. this.postFormatter = configuration.postFormatter || null;
  341. const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`;
  342. /** @type {string} */
  343. this.message = `${header}${this.formatValidationErrors(errors)}`;
  344. Error.captureStackTrace(this, this.constructor);
  345. }
  346. /**
  347. * @param {string} path
  348. * @returns {Schema}
  349. */
  350. getSchemaPart(path) {
  351. const newPath = path.split("/");
  352. let schemaPart = this.schema;
  353. for (let i = 1; i < newPath.length; i++) {
  354. const inner = schemaPart[/** @type {keyof Schema} */newPath[i]];
  355. if (!inner) {
  356. break;
  357. }
  358. schemaPart = inner;
  359. }
  360. return schemaPart;
  361. }
  362. /**
  363. * @param {Schema} schema
  364. * @param {boolean} logic
  365. * @param {Array<Object>} prevSchemas
  366. * @returns {string}
  367. */
  368. formatSchema(schema, logic = true, prevSchemas = []) {
  369. let newLogic = logic;
  370. const formatInnerSchema =
  371. /**
  372. *
  373. * @param {Object} innerSchema
  374. * @param {boolean=} addSelf
  375. * @returns {string}
  376. */
  377. (innerSchema, addSelf) => {
  378. if (!addSelf) {
  379. return this.formatSchema(innerSchema, newLogic, prevSchemas);
  380. }
  381. if (prevSchemas.includes(innerSchema)) {
  382. return "(recursive)";
  383. }
  384. return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema));
  385. };
  386. if (hasNotInSchema(schema) && !likeObject(schema)) {
  387. if (canApplyNot(schema.not)) {
  388. newLogic = !logic;
  389. return formatInnerSchema(schema.not);
  390. }
  391. const needApplyLogicHere = !schema.not.not;
  392. const prefix = logic ? "" : "non ";
  393. newLogic = !logic;
  394. return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not);
  395. }
  396. if ( /** @type {Schema & {instanceof: string | Array<string>}} */schema.instanceof) {
  397. const {
  398. instanceof: value
  399. } = /** @type {Schema & {instanceof: string | Array<string>}} */schema;
  400. const values = !Array.isArray(value) ? [value] : value;
  401. return values.map(
  402. /**
  403. * @param {string} item
  404. * @returns {string}
  405. */
  406. item => item === "Function" ? "function" : item).join(" | ");
  407. }
  408. if (schema.enum) {
  409. const enumValues = /** @type {Array<any>} */schema.enum.map(item => {
  410. if (item === null && schema.undefinedAsNull) {
  411. return `${JSON.stringify(item)} | undefined`;
  412. }
  413. return JSON.stringify(item);
  414. }).join(" | ");
  415. return `${enumValues}`;
  416. }
  417. if (typeof schema.const !== "undefined") {
  418. return JSON.stringify(schema.const);
  419. }
  420. if (schema.oneOf) {
  421. return (/** @type {Array<Schema>} */schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ")
  422. );
  423. }
  424. if (schema.anyOf) {
  425. return (/** @type {Array<Schema>} */schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ")
  426. );
  427. }
  428. if (schema.allOf) {
  429. return (/** @type {Array<Schema>} */schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ")
  430. );
  431. }
  432. if ( /** @type {JSONSchema7} */schema.if) {
  433. const {
  434. if: ifValue,
  435. then: thenValue,
  436. else: elseValue
  437. } = /** @type {JSONSchema7} */schema;
  438. return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`;
  439. }
  440. if (schema.$ref) {
  441. return formatInnerSchema(this.getSchemaPart(schema.$ref), true);
  442. }
  443. if (likeNumber(schema) || likeInteger(schema)) {
  444. const [type, ...hints] = getHints(schema, logic);
  445. const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`;
  446. return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`;
  447. }
  448. if (likeString(schema)) {
  449. const [type, ...hints] = getHints(schema, logic);
  450. const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`;
  451. return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`;
  452. }
  453. if (likeBoolean(schema)) {
  454. return `${logic ? "" : "non-"}boolean`;
  455. }
  456. if (likeArray(schema)) {
  457. // not logic already applied in formatValidationError
  458. newLogic = true;
  459. const hints = [];
  460. if (typeof schema.minItems === "number") {
  461. hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`);
  462. }
  463. if (typeof schema.maxItems === "number") {
  464. hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`);
  465. }
  466. if (schema.uniqueItems) {
  467. hints.push("should not have duplicate items");
  468. }
  469. const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems);
  470. let items = "";
  471. if (schema.items) {
  472. if (Array.isArray(schema.items) && schema.items.length > 0) {
  473. items = `${
  474. /** @type {Array<Schema>} */schema.items.map(item => formatInnerSchema(item)).join(", ")}`;
  475. if (hasAdditionalItems) {
  476. if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) {
  477. hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`);
  478. }
  479. }
  480. } else if (schema.items && Object.keys(schema.items).length > 0) {
  481. // "additionalItems" is ignored
  482. items = `${formatInnerSchema(schema.items)}`;
  483. } else {
  484. // Fallback for empty `items` value
  485. items = "any";
  486. }
  487. } else {
  488. // "additionalItems" is ignored
  489. items = "any";
  490. }
  491. if (schema.contains && Object.keys(schema.contains).length > 0) {
  492. hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`);
  493. }
  494. return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
  495. }
  496. if (likeObject(schema)) {
  497. // not logic already applied in formatValidationError
  498. newLogic = true;
  499. const hints = [];
  500. if (typeof schema.minProperties === "number") {
  501. hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`);
  502. }
  503. if (typeof schema.maxProperties === "number") {
  504. hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`);
  505. }
  506. if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) {
  507. const patternProperties = Object.keys(schema.patternProperties);
  508. hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`);
  509. }
  510. const properties = schema.properties ? Object.keys(schema.properties) : [];
  511. /** @type {Array<string>} */
  512. // @ts-ignore
  513. const required = schema.required ? schema.required : [];
  514. const allProperties = [...new Set( /** @type {Array<string>} */[].concat(required).concat(properties))];
  515. const objectStructure = allProperties.map(property => {
  516. const isRequired = required.includes(property);
  517. // Some properties need quotes, maybe we should add check
  518. // Maybe we should output type of property (`foo: string`), but it is looks very unreadable
  519. return `${property}${isRequired ? "" : "?"}`;
  520. }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`<key>: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", ");
  521. const {
  522. dependencies,
  523. propertyNames,
  524. patternRequired
  525. } = /** @type {Schema & {patternRequired?: Array<string>;}} */schema;
  526. if (dependencies) {
  527. Object.keys(dependencies).forEach(dependencyName => {
  528. const dependency = dependencies[dependencyName];
  529. if (Array.isArray(dependency)) {
  530. hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`);
  531. } else {
  532. hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`);
  533. }
  534. });
  535. }
  536. if (propertyNames && Object.keys(propertyNames).length > 0) {
  537. hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`);
  538. }
  539. if (patternRequired && patternRequired.length > 0) {
  540. hints.push(`should have property matching pattern ${patternRequired.map(
  541. /**
  542. * @param {string} item
  543. * @returns {string}
  544. */
  545. item => JSON.stringify(item))}`);
  546. }
  547. return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`;
  548. }
  549. if (likeNull(schema)) {
  550. return `${logic ? "" : "non-"}null`;
  551. }
  552. if (Array.isArray(schema.type)) {
  553. // not logic already applied in formatValidationError
  554. return `${schema.type.join(" | ")}`;
  555. }
  556. // Fallback for unknown keywords
  557. // not logic already applied in formatValidationError
  558. /* istanbul ignore next */
  559. return JSON.stringify(schema, null, 2);
  560. }
  561. /**
  562. * @param {Schema=} schemaPart
  563. * @param {(boolean | Array<string>)=} additionalPath
  564. * @param {boolean=} needDot
  565. * @param {boolean=} logic
  566. * @returns {string}
  567. */
  568. getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) {
  569. if (!schemaPart) {
  570. return "";
  571. }
  572. if (Array.isArray(additionalPath)) {
  573. for (let i = 0; i < additionalPath.length; i++) {
  574. /** @type {Schema | undefined} */
  575. const inner = schemaPart[/** @type {keyof Schema} */additionalPath[i]];
  576. if (inner) {
  577. // eslint-disable-next-line no-param-reassign
  578. schemaPart = inner;
  579. } else {
  580. break;
  581. }
  582. }
  583. }
  584. while (schemaPart.$ref) {
  585. // eslint-disable-next-line no-param-reassign
  586. schemaPart = this.getSchemaPart(schemaPart.$ref);
  587. }
  588. let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`;
  589. if (schemaPart.description) {
  590. schemaText += `\n-> ${schemaPart.description}`;
  591. }
  592. if (schemaPart.link) {
  593. schemaText += `\n-> Read more at ${schemaPart.link}`;
  594. }
  595. return schemaText;
  596. }
  597. /**
  598. * @param {Schema=} schemaPart
  599. * @returns {string}
  600. */
  601. getSchemaPartDescription(schemaPart) {
  602. if (!schemaPart) {
  603. return "";
  604. }
  605. while (schemaPart.$ref) {
  606. // eslint-disable-next-line no-param-reassign
  607. schemaPart = this.getSchemaPart(schemaPart.$ref);
  608. }
  609. let schemaText = "";
  610. if (schemaPart.description) {
  611. schemaText += `\n-> ${schemaPart.description}`;
  612. }
  613. if (schemaPart.link) {
  614. schemaText += `\n-> Read more at ${schemaPart.link}`;
  615. }
  616. return schemaText;
  617. }
  618. /**
  619. * @param {SchemaUtilErrorObject} error
  620. * @returns {string}
  621. */
  622. formatValidationError(error) {
  623. const {
  624. keyword,
  625. instancePath: errorInstancePath
  626. } = error;
  627. const splittedInstancePath = errorInstancePath.split("/");
  628. /**
  629. * @type {Array<string>}
  630. */
  631. const defaultValue = [];
  632. const prettyInstancePath = splittedInstancePath.reduce((acc, val) => {
  633. if (val.length > 0) {
  634. if (isNumeric(val)) {
  635. acc.push(`[${val}]`);
  636. } else if (/^\[/.test(val)) {
  637. acc.push(val);
  638. } else {
  639. acc.push(`.${val}`);
  640. }
  641. }
  642. return acc;
  643. }, defaultValue).join("");
  644. const instancePath = `${this.baseDataPath}${prettyInstancePath}`;
  645. // const { keyword, instancePath: errorInstancePath } = error;
  646. // const instancePath = `${this.baseDataPath}${errorInstancePath.replace(/\//g, '.')}`;
  647. switch (keyword) {
  648. case "type":
  649. {
  650. const {
  651. parentSchema,
  652. params
  653. } = error;
  654. switch (params.type) {
  655. case "number":
  656. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  657. case "integer":
  658. return `${instancePath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`;
  659. case "string":
  660. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  661. case "boolean":
  662. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  663. case "array":
  664. return `${instancePath} should be an array:\n${this.getSchemaPartText(parentSchema)}`;
  665. case "object":
  666. return `${instancePath} should be an object:\n${this.getSchemaPartText(parentSchema)}`;
  667. case "null":
  668. return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`;
  669. default:
  670. return `${instancePath} should be:\n${this.getSchemaPartText(parentSchema)}`;
  671. }
  672. }
  673. case "instanceof":
  674. {
  675. const {
  676. parentSchema
  677. } = error;
  678. return `${instancePath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`;
  679. }
  680. case "pattern":
  681. {
  682. const {
  683. params,
  684. parentSchema
  685. } = error;
  686. const {
  687. pattern
  688. } = params;
  689. return `${instancePath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  690. }
  691. case "format":
  692. {
  693. const {
  694. params,
  695. parentSchema
  696. } = error;
  697. const {
  698. format
  699. } = params;
  700. return `${instancePath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  701. }
  702. case "formatMinimum":
  703. case "formatExclusiveMinimum":
  704. case "formatMaximum":
  705. case "formatExclusiveMaximum":
  706. {
  707. const {
  708. params,
  709. parentSchema
  710. } = error;
  711. const {
  712. comparison,
  713. limit
  714. } = params;
  715. return `${instancePath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  716. }
  717. case "minimum":
  718. case "maximum":
  719. case "exclusiveMinimum":
  720. case "exclusiveMaximum":
  721. {
  722. const {
  723. parentSchema,
  724. params
  725. } = error;
  726. const {
  727. comparison,
  728. limit
  729. } = params;
  730. const [, ...hints] = getHints( /** @type {Schema} */parentSchema, true);
  731. if (hints.length === 0) {
  732. hints.push(`should be ${comparison} ${limit}`);
  733. }
  734. return `${instancePath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  735. }
  736. case "multipleOf":
  737. {
  738. const {
  739. params,
  740. parentSchema
  741. } = error;
  742. const {
  743. multipleOf
  744. } = params;
  745. return `${instancePath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  746. }
  747. case "patternRequired":
  748. {
  749. const {
  750. params,
  751. parentSchema
  752. } = error;
  753. const {
  754. missingPattern
  755. } = params;
  756. return `${instancePath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  757. }
  758. case "minLength":
  759. {
  760. const {
  761. params,
  762. parentSchema
  763. } = error;
  764. const {
  765. limit
  766. } = params;
  767. if (limit === 1) {
  768. return `${instancePath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  769. }
  770. const length = limit - 1;
  771. return `${instancePath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  772. }
  773. case "minItems":
  774. {
  775. const {
  776. params,
  777. parentSchema
  778. } = error;
  779. const {
  780. limit
  781. } = params;
  782. if (limit === 1) {
  783. return `${instancePath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  784. }
  785. return `${instancePath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  786. }
  787. case "minProperties":
  788. {
  789. const {
  790. params,
  791. parentSchema
  792. } = error;
  793. const {
  794. limit
  795. } = params;
  796. if (limit === 1) {
  797. return `${instancePath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  798. }
  799. return `${instancePath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  800. }
  801. case "maxLength":
  802. {
  803. const {
  804. params,
  805. parentSchema
  806. } = error;
  807. const {
  808. limit
  809. } = params;
  810. const max = limit + 1;
  811. return `${instancePath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  812. }
  813. case "maxItems":
  814. {
  815. const {
  816. params,
  817. parentSchema
  818. } = error;
  819. const {
  820. limit
  821. } = params;
  822. return `${instancePath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  823. }
  824. case "maxProperties":
  825. {
  826. const {
  827. params,
  828. parentSchema
  829. } = error;
  830. const {
  831. limit
  832. } = params;
  833. return `${instancePath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  834. }
  835. case "uniqueItems":
  836. {
  837. const {
  838. params,
  839. parentSchema
  840. } = error;
  841. const {
  842. i
  843. } = params;
  844. return `${instancePath} should not contain the item '${
  845. /** @type {{ data: Array<any> }} **/error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  846. }
  847. case "additionalItems":
  848. {
  849. const {
  850. params,
  851. parentSchema
  852. } = error;
  853. const {
  854. limit
  855. } = params;
  856. return `${instancePath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`;
  857. }
  858. case "contains":
  859. {
  860. const {
  861. parentSchema
  862. } = error;
  863. return `${instancePath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`;
  864. }
  865. case "required":
  866. {
  867. const {
  868. parentSchema,
  869. params
  870. } = error;
  871. const missingProperty = params.missingProperty.replace(/^\./, "");
  872. const hasProperty = parentSchema && Boolean( /** @type {Schema} */
  873. parentSchema.properties && /** @type {Schema} */
  874. parentSchema.properties[missingProperty]);
  875. return `${instancePath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`;
  876. }
  877. case "additionalProperties":
  878. {
  879. const {
  880. params,
  881. parentSchema
  882. } = error;
  883. const {
  884. additionalProperty
  885. } = params;
  886. return `${instancePath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`;
  887. }
  888. case "dependencies":
  889. {
  890. const {
  891. params,
  892. parentSchema
  893. } = error;
  894. const {
  895. property,
  896. deps
  897. } = params;
  898. const dependencies = deps.split(",").map(
  899. /**
  900. * @param {string} dep
  901. * @returns {string}
  902. */
  903. dep => `'${dep.trim()}'`).join(", ");
  904. return `${instancePath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`;
  905. }
  906. case "propertyNames":
  907. {
  908. const {
  909. params,
  910. parentSchema,
  911. schema
  912. } = error;
  913. const {
  914. propertyName
  915. } = params;
  916. return `${instancePath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`;
  917. }
  918. case "enum":
  919. {
  920. const {
  921. parentSchema
  922. } = error;
  923. if (parentSchema && /** @type {Schema} */
  924. parentSchema.enum && /** @type {Schema} */
  925. parentSchema.enum.length === 1) {
  926. return `${instancePath} should be ${this.getSchemaPartText(parentSchema, false, true)}`;
  927. }
  928. return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
  929. }
  930. case "const":
  931. {
  932. const {
  933. parentSchema
  934. } = error;
  935. return `${instancePath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`;
  936. }
  937. case "not":
  938. {
  939. const postfix = likeObject( /** @type {Schema} */error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : "";
  940. const schemaOutput = this.getSchemaPartText(error.schema, false, false, false);
  941. if (canApplyNot(error.schema)) {
  942. return `${instancePath} should be any ${schemaOutput}${postfix}.`;
  943. }
  944. const {
  945. schema,
  946. parentSchema
  947. } = error;
  948. return `${instancePath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`;
  949. }
  950. case "oneOf":
  951. case "anyOf":
  952. {
  953. const {
  954. parentSchema,
  955. children
  956. } = error;
  957. if (children && children.length > 0) {
  958. if (error.schema.length === 1) {
  959. const lastChild = children[children.length - 1];
  960. const remainingChildren = children.slice(0, children.length - 1);
  961. return this.formatValidationError(Object.assign({}, lastChild, {
  962. children: remainingChildren,
  963. parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema)
  964. }));
  965. }
  966. let filteredChildren = filterChildren(children);
  967. if (filteredChildren.length === 1) {
  968. return this.formatValidationError(filteredChildren[0]);
  969. }
  970. filteredChildren = groupChildrenByFirstChild(filteredChildren);
  971. return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map(
  972. /**
  973. * @param {SchemaUtilErrorObject} nestedError
  974. * @returns {string}
  975. */
  976. nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`;
  977. }
  978. return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`;
  979. }
  980. case "if":
  981. {
  982. const {
  983. params,
  984. parentSchema
  985. } = error;
  986. const {
  987. failingKeyword
  988. } = params;
  989. return `${instancePath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`;
  990. }
  991. case "absolutePath":
  992. {
  993. const {
  994. message,
  995. parentSchema
  996. } = error;
  997. return `${instancePath}: ${message}${this.getSchemaPartDescription(parentSchema)}`;
  998. }
  999. /* istanbul ignore next */
  1000. default:
  1001. {
  1002. const {
  1003. message,
  1004. parentSchema
  1005. } = error;
  1006. const ErrorInJSON = JSON.stringify(error, null, 2);
  1007. // For `custom`, `false schema`, `$ref` keywords
  1008. // Fallback for unknown keywords
  1009. return `${instancePath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`;
  1010. }
  1011. }
  1012. }
  1013. /**
  1014. * @param {Array<SchemaUtilErrorObject>} errors
  1015. * @returns {string}
  1016. */
  1017. formatValidationErrors(errors) {
  1018. return errors.map(error => {
  1019. let formattedError = this.formatValidationError(error);
  1020. if (this.postFormatter) {
  1021. formattedError = this.postFormatter(formattedError, error);
  1022. }
  1023. return ` - ${indent(formattedError, " ")}`;
  1024. }).join("\n");
  1025. }
  1026. }
  1027. var _default = ValidationError;
  1028. exports.default = _default;