json-schema-describes-subset
Version:
Tools for static JSON schema analysis, including functions to determine if one schema describes a subset of another or if a schema describes the empty set or to convert a schema to its disjunctive normal form (DNF).
59 lines • 1.9 kB
JavaScript
import isObject from 'lodash/isObject.js';
import includes from 'lodash/includes.js';
import { isJSONSchema } from '../../json-schema/index.js';
const arrayKeywords = ['prefixItems', 'allOf', 'anyOf', 'oneOf'];
const objectKeywords = [
'$defs',
'definitions',
'properties',
'patternProperties',
'dependencies',
];
const schemaKeywords = [
'additionalItems',
'items',
'contains',
'additionalProperties',
'propertyNames',
'not',
'if',
'then',
'else',
'unevaluatedProperties',
'unevaluatedItems',
];
export function traverseJSONSchema(schema, callback, data, args) {
if (!isObject(schema) || Array.isArray(schema)) {
return;
}
const newData = callback(schema, data, { parent: args?.parent || null });
for (const [key, value] of Object.entries(schema)) {
if (includes(arrayKeywords, key)) {
if (Array.isArray(value)) {
value.forEach((subSchema) => {
if (isJSONSchema(subSchema)) {
traverseJSONSchema(subSchema, callback, newData, {
parent: schema,
});
}
});
}
}
else if (includes(objectKeywords, key)) {
if (isObject(value) && !Array.isArray(value))
Object.values(value).forEach((subSchema) => {
if (isJSONSchema(subSchema)) {
traverseJSONSchema(subSchema, callback, newData, {
parent: schema,
});
}
});
}
else if (includes(schemaKeywords, key) && isJSONSchema(value)) {
traverseJSONSchema(value, callback, newData, {
parent: schema,
});
}
}
}
//# sourceMappingURL=traverse-json-schema.js.map