intersection.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { parseDef } from "../parseDef.js";
  2. const isJsonSchema7AllOfType = (type) => {
  3. if ("type" in type && type.type === "string")
  4. return false;
  5. return "allOf" in type;
  6. };
  7. export function parseIntersectionDef(def, refs) {
  8. const allOf = [
  9. parseDef(def.left._def, {
  10. ...refs,
  11. currentPath: [...refs.currentPath, "allOf", "0"],
  12. }),
  13. parseDef(def.right._def, {
  14. ...refs,
  15. currentPath: [...refs.currentPath, "allOf", "1"],
  16. }),
  17. ].filter((x) => !!x);
  18. let unevaluatedProperties = refs.target === "jsonSchema2019-09"
  19. ? { unevaluatedProperties: false }
  20. : undefined;
  21. const mergedAllOf = [];
  22. // If either of the schemas is an allOf, merge them into a single allOf
  23. allOf.forEach((schema) => {
  24. if (isJsonSchema7AllOfType(schema)) {
  25. mergedAllOf.push(...schema.allOf);
  26. if (schema.unevaluatedProperties === undefined) {
  27. // If one of the schemas has no unevaluatedProperties set,
  28. // the merged schema should also have no unevaluatedProperties set
  29. unevaluatedProperties = undefined;
  30. }
  31. }
  32. else {
  33. let nestedSchema = schema;
  34. if ("additionalProperties" in schema &&
  35. schema.additionalProperties === false) {
  36. const { additionalProperties, ...rest } = schema;
  37. nestedSchema = rest;
  38. }
  39. else {
  40. // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties
  41. unevaluatedProperties = undefined;
  42. }
  43. mergedAllOf.push(nestedSchema);
  44. }
  45. });
  46. return mergedAllOf.length
  47. ? {
  48. allOf: mergedAllOf,
  49. ...unevaluatedProperties,
  50. }
  51. : undefined;
  52. }