json-schema-compatibility-checker 1.1.7 → 1.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/runtime-validator.d.ts +14 -8
- package/dist/cjs/runtime-validator.js +1 -1
- package/dist/cjs/runtime-validator.js.map +1 -1
- package/dist/cjs/subset-checker.js +1 -1
- package/dist/cjs/subset-checker.js.map +1 -1
- package/dist/esm/runtime-validator.d.ts +14 -8
- package/dist/esm/runtime-validator.js +1 -1
- package/dist/esm/runtime-validator.js.map +1 -1
- package/dist/esm/subset-checker.js +1 -1
- package/dist/esm/subset-checker.js.map +1 -1
- package/package.json +1 -1
|
@@ -17,25 +17,31 @@ export declare function isDataValidForSchema(schema: JSONSchema7Definition, data
|
|
|
17
17
|
*/
|
|
18
18
|
export declare function getRuntimeValidationErrors(schema: JSONSchema7Definition, data: unknown): SchemaError[];
|
|
19
19
|
/**
|
|
20
|
-
* Recursively strips
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* Recursively strips partial-mode constraints from a JSON Schema so that
|
|
21
|
+
* AJV validates only the values present in the data without penalizing
|
|
22
|
+
* absent or truncated entries.
|
|
23
|
+
*
|
|
24
|
+
* Stripped keywords:
|
|
25
|
+
* - `required` — missing properties are not errors in partial data
|
|
26
|
+
* - `additionalProperties` — extra properties are tolerated
|
|
27
|
+
* - `minItems` — truncated arrays (e.g. after template filtering) are tolerated
|
|
28
|
+
* - `minProperties` — objects with fewer keys than expected are tolerated
|
|
23
29
|
*
|
|
24
30
|
* Recurses into: `properties`, `items` (single + tuple), `oneOf`, `anyOf`,
|
|
25
31
|
* `allOf`, `then`, `else`.
|
|
26
32
|
*
|
|
27
33
|
* @param schema - The schema to strip (not mutated — returns a new object)
|
|
28
|
-
* @returns A new schema without
|
|
34
|
+
* @returns A new schema without partial-mode constraints at any level
|
|
29
35
|
*/
|
|
30
36
|
export declare function stripRequiredRecursive(schema: JSONSchema7): JSONSchema7;
|
|
31
37
|
/**
|
|
32
|
-
* Returns AJV validation errors for partial data — strips `required
|
|
33
|
-
* `additionalProperties` before compilation
|
|
34
|
-
* **present** in `data` are validated.
|
|
38
|
+
* Returns AJV validation errors for partial data — strips `required`,
|
|
39
|
+
* `additionalProperties`, `minItems`, and `minProperties` before compilation
|
|
40
|
+
* so that only the values **present** in `data` are validated.
|
|
35
41
|
*
|
|
36
42
|
* @param schema - The schema to validate against (not mutated)
|
|
37
43
|
* @param data - The partial runtime data
|
|
38
|
-
* @returns Normalized runtime validation errors for present
|
|
44
|
+
* @returns Normalized runtime validation errors for present values only
|
|
39
45
|
*/
|
|
40
46
|
export declare function getPartialRuntimeValidationErrors(schema: JSONSchema7Definition, data: unknown): SchemaError[];
|
|
41
47
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get clearAllValidatorCaches(){return clearAllValidatorCaches},get getPartialRuntimeValidationErrors(){return getPartialRuntimeValidationErrors},get getRuntimeValidationErrors(){return getRuntimeValidationErrors},get isDataValidForSchema(){return isDataValidForSchema},get stripRequiredRecursive(){return stripRequiredRecursive}});const _ajv=/*#__PURE__*/_interop_require_default(require("ajv"));const _ajvformats=/*#__PURE__*/_interop_require_default(require("ajv-formats"));const _typests=require("./types.js");const _utilsts=require("./utils.js");function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}const ajv=new _ajv.default({allErrors:true,strict:false,validateFormats:true,allowUnionTypes:true,messages:true});(0,_ajvformats.default)(ajv);const validatorCache=new WeakMap;class LRUCache{get(key){const value=this.cache.get(key);if(value===undefined)return undefined;this.cache.delete(key);this.cache.set(key,value);return value}set(key,value){if(this.cache.has(key)){this.cache.delete(key)}else if(this.cache.size>=this.max){const firstKey=this.cache.keys().next().value;if(firstKey!==undefined){this.cache.delete(firstKey)}}this.cache.set(key,value)}clear(){this.cache.clear()}constructor(maxSize){_define_property(this,"max",void 0);_define_property(this,"cache",new Map);this.max=maxSize}}const validatorStringCache=new LRUCache(500);function isObjectLike(value){return typeof value==="object"&&value!==null}function stableStringify(value){if(value===null||typeof value!=="object"){return JSON.stringify(value)}if(Array.isArray(value)){return`[${value.map(entry=>stableStringify(entry)).join(",")}]`}const entries=Object.entries(value).sort(([a],[b])=>a.localeCompare(b));return`{${entries.map(([key,entryValue])=>`${JSON.stringify(key)}:${stableStringify(entryValue)}`).join(",")}}`}function getSchemaTypeName(schema){if(schema.type===undefined)return"value";if(Array.isArray(schema.type)){return schema.type.join(" | ")}return schema.type}function stringifyValue(value){if(value===undefined)return"undefined";if(typeof value==="string")return value;return JSON.stringify(value)}function normalizeInstancePath(instancePath){if(instancePath==="")return"$root";const parts=instancePath.split("/").filter(Boolean);if(parts.length===0)return"$root";let path="";for(const rawPart of parts){const part=rawPart.replace(/~1/g,"/").replace(/~0/g,"~");const isArrayIndex=/^\d+$/.test(part);if(isArrayIndex){path+="[]";continue}path=path.length===0?part:`${path}.${part}`}return path||"$root"}function formatAllowedValues(values){if(values.length===0)return"no allowed values";const rendered=values.map(value=>typeof value==="string"?value:JSON.stringify(value));if(rendered.length===1)return rendered[0]??"";if(rendered.length===2)return`${rendered[0]} or ${rendered[1]}`;return`${rendered.slice(0,-1).join(", ")}, or ${rendered[rendered.length-1]}`}function formatExpected(error,schema){switch(error.keyword){case"type":{const expectedType=typeof error.params==="object"&&error.params!==null&&"type"in error.params?String(error.params.type):getSchemaTypeName(schema);return expectedType}case"enum":{return Array.isArray(schema.enum)?formatAllowedValues(schema.enum):"allowed enum value"}case"const":{return stringifyValue(schema.const)}case"required":{const missingProperty=typeof error.params==="object"&&error.params!==null&&"missingProperty"in error.params?String(error.params.missingProperty):"unknown";const targetSchema=schema.properties?.[missingProperty]&&typeof schema.properties[missingProperty]!=="boolean"?schema.properties[missingProperty]:undefined;if(targetSchema?.type!==undefined){const prefix=normalizeInstancePath(error.instancePath);const key=prefix==="$root"?missingProperty:`${prefix}.${missingProperty}`;return`${key}: ${getSchemaTypeName(targetSchema)}`}return`required property: ${missingProperty}`}case"minimum":return`>= ${String(schema.minimum)}`;case"maximum":return`<= ${String(schema.maximum)}`;case"exclusiveMinimum":return`> ${String(schema.exclusiveMinimum)}`;case"exclusiveMaximum":return`< ${String(schema.exclusiveMaximum)}`;case"multipleOf":return`multipleOf ${String(schema.multipleOf)}`;case"minLength":return`minLength: ${String(schema.minLength)}`;case"maxLength":return`maxLength: ${String(schema.maxLength)}`;case"pattern":return`pattern: ${String(schema.pattern)}`;case"format":return`format: ${String(schema.format)}`;case"minItems":return`minItems: ${String(schema.minItems)}`;case"maxItems":return`maxItems: ${String(schema.maxItems)}`;case"uniqueItems":return"uniqueItems: true";case"minProperties":return`minProperties: ${String(schema.minProperties)}`;case"maxProperties":return`maxProperties: ${String(schema.maxProperties)}`;case"additionalProperties":return"not allowed (additionalProperties: false)";case"propertyNames":return"valid property names";case"contains":return"contains at least one matching item";case"allOf":return"allOf constraints";case"anyOf":return"anyOf constraints";case"oneOf":return"oneOf constraints";case"not":return"not matching forbidden schema";default:return error.message??error.keyword}}function buildSchemaError(error,schema,data){const type=_typests.SchemaErrorType.RuntimeValidation;const baseKey=normalizeInstancePath(error.instancePath);if(error.keyword==="required"){const missingProperty=typeof error.params==="object"&&error.params!==null&&"missingProperty"in error.params?String(error.params.missingProperty):"unknown";return{type,key:baseKey==="$root"?missingProperty:`${baseKey}.${missingProperty}`,expected:formatExpected(error,schema),received:"undefined"}}if(error.keyword==="additionalProperties"){const additionalProperty=typeof error.params==="object"&&error.params!==null&&"additionalProperty"in error.params?String(error.params.additionalProperty):"unknown";return{type,key:baseKey==="$root"?additionalProperty:`${baseKey}.${additionalProperty}`,expected:formatExpected(error,schema),received:"present"}}return{type,key:baseKey,expected:formatExpected(error,schema),received:stringifyValue(data)}}function compileValidator(schema){if(isObjectLike(schema)){const cached=validatorCache.get(schema);if(cached!==undefined)return cached}const serialized=stableStringify(schema);const cachedByString=validatorStringCache.get(serialized);if(cachedByString!==undefined){if(isObjectLike(schema)){validatorCache.set(schema,cachedByString)}return cachedByString}const validate=ajv.compile(schema);if(isObjectLike(schema)){validatorCache.set(schema,validate)}validatorStringCache.set(serialized,validate);return validate}function isDataValidForSchema(schema,data){if(typeof schema==="boolean"){return schema}const validate=compileValidator(schema);return validate(data)===true}function getRuntimeValidationErrors(schema,data){if(typeof schema==="boolean"){if(schema)return[];return[{type:_typests.SchemaErrorType.RuntimeValidation,key:"$root",expected:"never",received:stringifyValue(data)}]}const validate=compileValidator(schema);const isValid=validate(data);if(isValid===true||validate.errors===null||validate.errors===undefined){return[]}return validate.errors.map(error=>buildSchemaError(error,schema,data))}function stripRequiredRecursive(schema){if(!(0,_utilsts.isPlainObj)(schema))return schema;const result={...schema};delete result.required;delete result.additionalProperties;if((0,_utilsts.isPlainObj)(result.properties)){const props={};for(const[key,value]of Object.entries(result.properties)){props[key]=typeof value==="object"&&value!==null?stripRequiredRecursive(value):value}result.properties=props}if((0,_utilsts.isPlainObj)(result.items)&&!Array.isArray(result.items)){result.items=stripRequiredRecursive(result.items)}if(Array.isArray(result.items)){result.items=result.items.map(item=>typeof item==="object"&&item!==null?stripRequiredRecursive(item):item)}for(const keyword of["oneOf","anyOf","allOf"]){if(Array.isArray(result[keyword])){result[keyword]=result[keyword].map(branch=>typeof branch==="object"&&branch!==null?stripRequiredRecursive(branch):branch)}}if((0,_utilsts.isPlainObj)(result.then)){result.then=stripRequiredRecursive(result.then)}if((0,_utilsts.isPlainObj)(result.else)){result.else=stripRequiredRecursive(result.else)}return result}function getPartialRuntimeValidationErrors(schema,data){if(typeof schema==="boolean"){return getRuntimeValidationErrors(schema,data)}const stripped=stripRequiredRecursive(schema);return getRuntimeValidationErrors(stripped,data)}function clearAllValidatorCaches(){validatorStringCache.clear();ajv.removeSchema()}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get clearAllValidatorCaches(){return clearAllValidatorCaches},get getPartialRuntimeValidationErrors(){return getPartialRuntimeValidationErrors},get getRuntimeValidationErrors(){return getRuntimeValidationErrors},get isDataValidForSchema(){return isDataValidForSchema},get stripRequiredRecursive(){return stripRequiredRecursive}});const _ajv=/*#__PURE__*/_interop_require_default(require("ajv"));const _ajvformats=/*#__PURE__*/_interop_require_default(require("ajv-formats"));const _typests=require("./types.js");const _utilsts=require("./utils.js");function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}const ajv=new _ajv.default({allErrors:true,strict:false,validateFormats:true,allowUnionTypes:true,messages:true});(0,_ajvformats.default)(ajv);const validatorCache=new WeakMap;class LRUCache{get(key){const value=this.cache.get(key);if(value===undefined)return undefined;this.cache.delete(key);this.cache.set(key,value);return value}set(key,value){if(this.cache.has(key)){this.cache.delete(key)}else if(this.cache.size>=this.max){const firstKey=this.cache.keys().next().value;if(firstKey!==undefined){this.cache.delete(firstKey)}}this.cache.set(key,value)}clear(){this.cache.clear()}constructor(maxSize){_define_property(this,"max",void 0);_define_property(this,"cache",new Map);this.max=maxSize}}const validatorStringCache=new LRUCache(500);function isObjectLike(value){return typeof value==="object"&&value!==null}function stableStringify(value){if(value===null||typeof value!=="object"){return JSON.stringify(value)}if(Array.isArray(value)){return`[${value.map(entry=>stableStringify(entry)).join(",")}]`}const entries=Object.entries(value).sort(([a],[b])=>a.localeCompare(b));return`{${entries.map(([key,entryValue])=>`${JSON.stringify(key)}:${stableStringify(entryValue)}`).join(",")}}`}function getSchemaTypeName(schema){if(schema.type===undefined)return"value";if(Array.isArray(schema.type)){return schema.type.join(" | ")}return schema.type}function stringifyValue(value){if(value===undefined)return"undefined";if(typeof value==="string")return value;return JSON.stringify(value)}function normalizeInstancePath(instancePath){if(instancePath==="")return"$root";const parts=instancePath.split("/").filter(Boolean);if(parts.length===0)return"$root";let path="";for(const rawPart of parts){const part=rawPart.replace(/~1/g,"/").replace(/~0/g,"~");const isArrayIndex=/^\d+$/.test(part);if(isArrayIndex){path+="[]";continue}path=path.length===0?part:`${path}.${part}`}return path||"$root"}function formatAllowedValues(values){if(values.length===0)return"no allowed values";const rendered=values.map(value=>typeof value==="string"?value:JSON.stringify(value));if(rendered.length===1)return rendered[0]??"";if(rendered.length===2)return`${rendered[0]} or ${rendered[1]}`;return`${rendered.slice(0,-1).join(", ")}, or ${rendered[rendered.length-1]}`}function formatExpected(error,schema){switch(error.keyword){case"type":{const expectedType=typeof error.params==="object"&&error.params!==null&&"type"in error.params?String(error.params.type):getSchemaTypeName(schema);return expectedType}case"enum":{return Array.isArray(schema.enum)?formatAllowedValues(schema.enum):"allowed enum value"}case"const":{return stringifyValue(schema.const)}case"required":{const missingProperty=typeof error.params==="object"&&error.params!==null&&"missingProperty"in error.params?String(error.params.missingProperty):"unknown";const targetSchema=schema.properties?.[missingProperty]&&typeof schema.properties[missingProperty]!=="boolean"?schema.properties[missingProperty]:undefined;if(targetSchema?.type!==undefined){const prefix=normalizeInstancePath(error.instancePath);const key=prefix==="$root"?missingProperty:`${prefix}.${missingProperty}`;return`${key}: ${getSchemaTypeName(targetSchema)}`}return`required property: ${missingProperty}`}case"minimum":return`>= ${String(schema.minimum)}`;case"maximum":return`<= ${String(schema.maximum)}`;case"exclusiveMinimum":return`> ${String(schema.exclusiveMinimum)}`;case"exclusiveMaximum":return`< ${String(schema.exclusiveMaximum)}`;case"multipleOf":return`multipleOf ${String(schema.multipleOf)}`;case"minLength":return`minLength: ${String(schema.minLength)}`;case"maxLength":return`maxLength: ${String(schema.maxLength)}`;case"pattern":return`pattern: ${String(schema.pattern)}`;case"format":return`format: ${String(schema.format)}`;case"minItems":return`minItems: ${String(schema.minItems)}`;case"maxItems":return`maxItems: ${String(schema.maxItems)}`;case"uniqueItems":return"uniqueItems: true";case"minProperties":return`minProperties: ${String(schema.minProperties)}`;case"maxProperties":return`maxProperties: ${String(schema.maxProperties)}`;case"additionalProperties":return"not allowed (additionalProperties: false)";case"propertyNames":return"valid property names";case"contains":return"contains at least one matching item";case"allOf":return"allOf constraints";case"anyOf":return"anyOf constraints";case"oneOf":return"oneOf constraints";case"not":return"not matching forbidden schema";default:return error.message??error.keyword}}function buildSchemaError(error,schema,data){const type=_typests.SchemaErrorType.RuntimeValidation;const baseKey=normalizeInstancePath(error.instancePath);if(error.keyword==="required"){const missingProperty=typeof error.params==="object"&&error.params!==null&&"missingProperty"in error.params?String(error.params.missingProperty):"unknown";return{type,key:baseKey==="$root"?missingProperty:`${baseKey}.${missingProperty}`,expected:formatExpected(error,schema),received:"undefined"}}if(error.keyword==="additionalProperties"){const additionalProperty=typeof error.params==="object"&&error.params!==null&&"additionalProperty"in error.params?String(error.params.additionalProperty):"unknown";return{type,key:baseKey==="$root"?additionalProperty:`${baseKey}.${additionalProperty}`,expected:formatExpected(error,schema),received:"present"}}return{type,key:baseKey,expected:formatExpected(error,schema),received:stringifyValue(data)}}function compileValidator(schema){if(isObjectLike(schema)){const cached=validatorCache.get(schema);if(cached!==undefined)return cached}const serialized=stableStringify(schema);const cachedByString=validatorStringCache.get(serialized);if(cachedByString!==undefined){if(isObjectLike(schema)){validatorCache.set(schema,cachedByString)}return cachedByString}const validate=ajv.compile(schema);if(isObjectLike(schema)){validatorCache.set(schema,validate)}validatorStringCache.set(serialized,validate);return validate}function isDataValidForSchema(schema,data){if(typeof schema==="boolean"){return schema}const validate=compileValidator(schema);return validate(data)===true}function getRuntimeValidationErrors(schema,data){if(typeof schema==="boolean"){if(schema)return[];return[{type:_typests.SchemaErrorType.RuntimeValidation,key:"$root",expected:"never",received:stringifyValue(data)}]}const validate=compileValidator(schema);const isValid=validate(data);if(isValid===true||validate.errors===null||validate.errors===undefined){return[]}return validate.errors.map(error=>buildSchemaError(error,schema,data))}function stripRequiredRecursive(schema){if(!(0,_utilsts.isPlainObj)(schema))return schema;const result={...schema};delete result.required;delete result.additionalProperties;delete result.minItems;delete result.minProperties;if((0,_utilsts.isPlainObj)(result.properties)){const props={};for(const[key,value]of Object.entries(result.properties)){props[key]=typeof value==="object"&&value!==null?stripRequiredRecursive(value):value}result.properties=props}if((0,_utilsts.isPlainObj)(result.items)&&!Array.isArray(result.items)){result.items=stripRequiredRecursive(result.items)}if(Array.isArray(result.items)){result.items=result.items.map(item=>typeof item==="object"&&item!==null?stripRequiredRecursive(item):item)}for(const keyword of["oneOf","anyOf","allOf"]){if(Array.isArray(result[keyword])){result[keyword]=result[keyword].map(branch=>typeof branch==="object"&&branch!==null?stripRequiredRecursive(branch):branch)}}if((0,_utilsts.isPlainObj)(result.then)){result.then=stripRequiredRecursive(result.then)}if((0,_utilsts.isPlainObj)(result.else)){result.else=stripRequiredRecursive(result.else)}return result}function getPartialRuntimeValidationErrors(schema,data){if(typeof schema==="boolean"){return getRuntimeValidationErrors(schema,data)}const stripped=stripRequiredRecursive(schema);return getRuntimeValidationErrors(stripped,data)}function clearAllValidatorCaches(){validatorStringCache.clear();ajv.removeSchema()}
|
|
2
2
|
//# sourceMappingURL=runtime-validator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime-validator.ts"],"sourcesContent":["import Ajv, { type ErrorObject, type ValidateFunction } from \"ajv\";\nimport addFormats from \"ajv-formats\";\nimport type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport type { SchemaError } from \"./types.ts\";\nimport { SchemaErrorType } from \"./types.ts\";\nimport { isPlainObj } from \"./utils.ts\";\n\n/**\n * ─── Runtime Validator ────────────────────────────────────────────────────────\n *\n * Centralizes runtime validation of JSON Schema Draft-07 schemas using AJV.\n *\n * Goals:\n * - Validate concrete runtime data against resolved schemas\n * - Reuse the same runtime engine for `check(..., { data })`\n * - Reuse the same runtime engine for `if/then/else` condition evaluation\n * - Keep the static subset-checking pipeline unchanged when no runtime data is provided\n *\n * Architecture — Singleton AJV instance:\n * The `ajv` constant below is a module-level singleton shared by every\n * `JsonSchemaCompatibilityChecker` instance in the same process. This is\n * intentional:\n * - Compiled validators are reused across checker instances, avoiding\n * redundant schema compilation and reducing memory usage.\n * - The WeakMap and LRU caches for `ValidateFunction` objects are valid\n * only for a single AJV instance; per-instance AJV would break caching.\n * - `ajv-formats` is registered once at module load; all standard Draft-07\n * formats are available globally.\n * - In worker-thread environments, each worker loads its own module scope\n * and gets its own AJV instance — no cross-worker sharing occurs.\n * - Custom AJV configuration or format registration is not supported\n * per-checker-instance. If needed in the future, the singleton could be\n * replaced with a factory, but this is intentionally deferred (YAGNI).\n *\n * Notes:\n * - AJV is configured in non-strict mode because this library intentionally\n * supports partially-specified / pragmatic schemas and some unsupported\n * keywords may appear in user input.\n * - Standard JSON Schema formats are enabled through `ajv-formats` so runtime\n * validation can influence condition resolution and `check(..., { data })`\n * consistently for supported formats.\n * - Unknown formats are still ignored in practice by the non-strict runtime\n * configuration instead of crashing the whole check pipeline.\n */\n\n// Singleton AJV instance — shared across all checker instances (see module JSDoc above)\nconst ajv = new Ajv({\n\tallErrors: true,\n\tstrict: false,\n\tvalidateFormats: true,\n\tallowUnionTypes: true,\n\tmessages: true,\n});\n\naddFormats(ajv);\n\n/**\n * Cache compiled validators by schema object reference.\n *\n * This mirrors the codebase's preference for WeakMap-based caching and avoids\n * recompiling validators for the same resolved schema instances.\n */\nconst validatorCache = new WeakMap<object, ValidateFunction>();\n\n/**\n * Minimal LRU cache using Map insertion-order guarantees for O(1) eviction.\n *\n * On `get`, the entry is moved to the end (most recently used).\n * On `set`, if the cache is full, the first entry (least recently used) is evicted.\n */\nclass LRUCache<K, V> {\n\tprivate readonly max: number;\n\tprivate readonly cache = new Map<K, V>();\n\n\tconstructor(maxSize: number) {\n\t\tthis.max = maxSize;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst value = this.cache.get(key);\n\t\tif (value === undefined) return undefined;\n\n\t\t// Move to end (most recently used)\n\t\tthis.cache.delete(key);\n\t\tthis.cache.set(key, value);\n\t\treturn value;\n\t}\n\n\tset(key: K, value: V): void {\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.delete(key);\n\t\t} else if (this.cache.size >= this.max) {\n\t\t\t// Evict least recently used (first key in iteration order)\n\t\t\tconst firstKey = this.cache.keys().next().value;\n\t\t\tif (firstKey !== undefined) {\n\t\t\t\tthis.cache.delete(firstKey);\n\t\t\t}\n\t\t}\n\t\tthis.cache.set(key, value);\n\t}\n\n\tclear(): void {\n\t\tthis.cache.clear();\n\t}\n}\n\n/**\n * LRU cache for compiled validators keyed by deterministic schema serialization.\n *\n * This is a fallback for schemas that are not stable object references (e.g.\n * freshly constructed schemas that are structurally identical to previously\n * seen ones). Bounded to 500 entries to prevent unbounded memory growth in\n * long-running processes. The WeakMap-based `validatorCache` remains the\n * primary cache for the hot path.\n */\nconst validatorStringCache = new LRUCache<string, ValidateFunction>(500);\n\nfunction isObjectLike(value: unknown): value is object {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction stableStringify(value: unknown): string {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn JSON.stringify(value);\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map((entry) => stableStringify(entry)).join(\",\")}]`;\n\t}\n\n\tconst entries = Object.entries(value as Record<string, unknown>).sort(\n\t\t([a], [b]) => a.localeCompare(b),\n\t);\n\n\treturn `{${entries\n\t\t.map(\n\t\t\t([key, entryValue]) =>\n\t\t\t\t`${JSON.stringify(key)}:${stableStringify(entryValue)}`,\n\t\t)\n\t\t.join(\",\")}}`;\n}\n\nfunction getSchemaTypeName(schema: JSONSchema7): string {\n\tif (schema.type === undefined) return \"value\";\n\n\tif (Array.isArray(schema.type)) {\n\t\treturn schema.type.join(\" | \");\n\t}\n\n\treturn schema.type;\n}\n\nfunction stringifyValue(value: unknown): string {\n\tif (value === undefined) return \"undefined\";\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value);\n}\n\nfunction normalizeInstancePath(instancePath: string): string {\n\tif (instancePath === \"\") return \"$root\";\n\n\tconst parts = instancePath.split(\"/\").filter(Boolean);\n\tif (parts.length === 0) return \"$root\";\n\n\tlet path = \"\";\n\n\tfor (const rawPart of parts) {\n\t\tconst part = rawPart.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\t\tconst isArrayIndex = /^\\d+$/.test(part);\n\n\t\tif (isArrayIndex) {\n\t\t\tpath += \"[]\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tpath = path.length === 0 ? part : `${path}.${part}`;\n\t}\n\n\treturn path || \"$root\";\n}\n\nfunction formatAllowedValues(values: unknown[]): string {\n\tif (values.length === 0) return \"no allowed values\";\n\n\tconst rendered = values.map((value) =>\n\t\ttypeof value === \"string\" ? value : JSON.stringify(value),\n\t);\n\n\tif (rendered.length === 1) return rendered[0] ?? \"\";\n\tif (rendered.length === 2) return `${rendered[0]} or ${rendered[1]}`;\n\n\treturn `${rendered.slice(0, -1).join(\", \")}, or ${rendered[rendered.length - 1]}`;\n}\n\nfunction formatExpected(error: ErrorObject, schema: JSONSchema7): string {\n\tswitch (error.keyword) {\n\t\tcase \"type\": {\n\t\t\tconst expectedType =\n\t\t\t\ttypeof error.params === \"object\" &&\n\t\t\t\terror.params !== null &&\n\t\t\t\t\"type\" in error.params\n\t\t\t\t\t? String(error.params.type)\n\t\t\t\t\t: getSchemaTypeName(schema);\n\n\t\t\treturn expectedType;\n\t\t}\n\n\t\tcase \"enum\": {\n\t\t\treturn Array.isArray(schema.enum)\n\t\t\t\t? formatAllowedValues(schema.enum)\n\t\t\t\t: \"allowed enum value\";\n\t\t}\n\n\t\tcase \"const\": {\n\t\t\treturn stringifyValue(schema.const);\n\t\t}\n\n\t\tcase \"required\": {\n\t\t\tconst missingProperty =\n\t\t\t\ttypeof error.params === \"object\" &&\n\t\t\t\terror.params !== null &&\n\t\t\t\t\"missingProperty\" in error.params\n\t\t\t\t\t? String(error.params.missingProperty)\n\t\t\t\t\t: \"unknown\";\n\n\t\t\tconst targetSchema =\n\t\t\t\tschema.properties?.[missingProperty] &&\n\t\t\t\ttypeof schema.properties[missingProperty] !== \"boolean\"\n\t\t\t\t\t? (schema.properties[missingProperty] as JSONSchema7)\n\t\t\t\t\t: undefined;\n\n\t\t\tif (targetSchema?.type !== undefined) {\n\t\t\t\tconst prefix = normalizeInstancePath(error.instancePath);\n\t\t\t\tconst key =\n\t\t\t\t\tprefix === \"$root\" ? missingProperty : `${prefix}.${missingProperty}`;\n\t\t\t\treturn `${key}: ${getSchemaTypeName(targetSchema)}`;\n\t\t\t}\n\n\t\t\treturn `required property: ${missingProperty}`;\n\t\t}\n\n\t\tcase \"minimum\":\n\t\t\treturn `>= ${String((schema as JSONSchema7).minimum)}`;\n\n\t\tcase \"maximum\":\n\t\t\treturn `<= ${String((schema as JSONSchema7).maximum)}`;\n\n\t\tcase \"exclusiveMinimum\":\n\t\t\treturn `> ${String((schema as JSONSchema7).exclusiveMinimum)}`;\n\n\t\tcase \"exclusiveMaximum\":\n\t\t\treturn `< ${String((schema as JSONSchema7).exclusiveMaximum)}`;\n\n\t\tcase \"multipleOf\":\n\t\t\treturn `multipleOf ${String((schema as JSONSchema7).multipleOf)}`;\n\n\t\tcase \"minLength\":\n\t\t\treturn `minLength: ${String((schema as JSONSchema7).minLength)}`;\n\n\t\tcase \"maxLength\":\n\t\t\treturn `maxLength: ${String((schema as JSONSchema7).maxLength)}`;\n\n\t\tcase \"pattern\":\n\t\t\treturn `pattern: ${String((schema as JSONSchema7).pattern)}`;\n\n\t\tcase \"format\":\n\t\t\treturn `format: ${String((schema as JSONSchema7).format)}`;\n\n\t\tcase \"minItems\":\n\t\t\treturn `minItems: ${String((schema as JSONSchema7).minItems)}`;\n\n\t\tcase \"maxItems\":\n\t\t\treturn `maxItems: ${String((schema as JSONSchema7).maxItems)}`;\n\n\t\tcase \"uniqueItems\":\n\t\t\treturn \"uniqueItems: true\";\n\n\t\tcase \"minProperties\":\n\t\t\treturn `minProperties: ${String((schema as JSONSchema7).minProperties)}`;\n\n\t\tcase \"maxProperties\":\n\t\t\treturn `maxProperties: ${String((schema as JSONSchema7).maxProperties)}`;\n\n\t\tcase \"additionalProperties\":\n\t\t\treturn \"not allowed (additionalProperties: false)\";\n\n\t\tcase \"propertyNames\":\n\t\t\treturn \"valid property names\";\n\n\t\tcase \"contains\":\n\t\t\treturn \"contains at least one matching item\";\n\n\t\tcase \"allOf\":\n\t\t\treturn \"allOf constraints\";\n\n\t\tcase \"anyOf\":\n\t\t\treturn \"anyOf constraints\";\n\n\t\tcase \"oneOf\":\n\t\t\treturn \"oneOf constraints\";\n\n\t\tcase \"not\":\n\t\t\treturn \"not matching forbidden schema\";\n\n\t\tdefault:\n\t\t\treturn error.message ?? error.keyword;\n\t}\n}\n\nfunction buildSchemaError(\n\terror: ErrorObject,\n\tschema: JSONSchema7,\n\tdata: unknown,\n): SchemaError {\n\tconst type = SchemaErrorType.RuntimeValidation;\n\tconst baseKey = normalizeInstancePath(error.instancePath);\n\n\tif (error.keyword === \"required\") {\n\t\tconst missingProperty =\n\t\t\ttypeof error.params === \"object\" &&\n\t\t\terror.params !== null &&\n\t\t\t\"missingProperty\" in error.params\n\t\t\t\t? String(error.params.missingProperty)\n\t\t\t\t: \"unknown\";\n\n\t\treturn {\n\t\t\ttype,\n\t\t\tkey:\n\t\t\t\tbaseKey === \"$root\" ? missingProperty : `${baseKey}.${missingProperty}`,\n\t\t\texpected: formatExpected(error, schema),\n\t\t\treceived: \"undefined\",\n\t\t};\n\t}\n\n\tif (error.keyword === \"additionalProperties\") {\n\t\tconst additionalProperty =\n\t\t\ttypeof error.params === \"object\" &&\n\t\t\terror.params !== null &&\n\t\t\t\"additionalProperty\" in error.params\n\t\t\t\t? String(error.params.additionalProperty)\n\t\t\t\t: \"unknown\";\n\n\t\treturn {\n\t\t\ttype,\n\t\t\tkey:\n\t\t\t\tbaseKey === \"$root\"\n\t\t\t\t\t? additionalProperty\n\t\t\t\t\t: `${baseKey}.${additionalProperty}`,\n\t\t\texpected: formatExpected(error, schema),\n\t\t\treceived: \"present\",\n\t\t};\n\t}\n\n\treturn {\n\t\ttype,\n\t\tkey: baseKey,\n\t\texpected: formatExpected(error, schema),\n\t\treceived: stringifyValue(data),\n\t};\n}\n\nfunction compileValidator(schema: JSONSchema7): ValidateFunction {\n\tif (isObjectLike(schema)) {\n\t\tconst cached = validatorCache.get(schema);\n\t\tif (cached !== undefined) return cached;\n\t}\n\n\tconst serialized = stableStringify(schema);\n\tconst cachedByString = validatorStringCache.get(serialized);\n\tif (cachedByString !== undefined) {\n\t\tif (isObjectLike(schema)) {\n\t\t\tvalidatorCache.set(schema, cachedByString);\n\t\t}\n\t\treturn cachedByString;\n\t}\n\n\tconst validate = ajv.compile(schema);\n\n\tif (isObjectLike(schema)) {\n\t\tvalidatorCache.set(schema, validate);\n\t}\n\tvalidatorStringCache.set(serialized, validate);\n\n\treturn validate;\n}\n\n/**\n * Validates runtime data against a schema using AJV.\n *\n * @param schema - The schema to validate against\n * @param data - The runtime data to validate\n * @returns true when valid, false otherwise\n */\nexport function isDataValidForSchema(\n\tschema: JSONSchema7Definition,\n\tdata: unknown,\n): boolean {\n\tif (typeof schema === \"boolean\") {\n\t\treturn schema;\n\t}\n\n\tconst validate = compileValidator(schema);\n\treturn validate(data) === true;\n}\n\n/**\n * Returns AJV validation errors converted to the library's `SchemaError` shape.\n *\n * @param schema - The schema used for validation\n * @param data - The runtime data that failed validation\n * @returns Normalized runtime validation errors\n */\nexport function getRuntimeValidationErrors(\n\tschema: JSONSchema7Definition,\n\tdata: unknown,\n): SchemaError[] {\n\tif (typeof schema === \"boolean\") {\n\t\tif (schema) return [];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: SchemaErrorType.RuntimeValidation,\n\t\t\t\tkey: \"$root\",\n\t\t\t\texpected: \"never\",\n\t\t\t\treceived: stringifyValue(data),\n\t\t\t},\n\t\t];\n\t}\n\n\tconst validate = compileValidator(schema);\n\tconst isValid = validate(data);\n\n\tif (\n\t\tisValid === true ||\n\t\tvalidate.errors === null ||\n\t\tvalidate.errors === undefined\n\t) {\n\t\treturn [];\n\t}\n\n\treturn validate.errors.map((error) => buildSchemaError(error, schema, data));\n}\n\n// ─── Partial Validation ──────────────────────────────────────────────────────\n//\n// Strips `required` and `additionalProperties` from a schema recursively so\n// that AJV only validates the properties **present** in the data — without\n// reporting missing required properties or unexpected additional properties.\n//\n// This is used by the \"partial\" runtime validation mode: the caller has\n// partial data (e.g. only some properties known at design-time) and wants to\n// validate those values against the schema without false negatives for\n// properties that will be provided later by another source.\n\n/**\n * Recursively strips `required` and `additionalProperties` from an\n * object-typed JSON Schema so that AJV validates only the properties\n * present in the data.\n *\n * Recurses into: `properties`, `items` (single + tuple), `oneOf`, `anyOf`,\n * `allOf`, `then`, `else`.\n *\n * @param schema - The schema to strip (not mutated — returns a new object)\n * @returns A new schema without `required` or `additionalProperties` at any level\n */\nexport function stripRequiredRecursive(schema: JSONSchema7): JSONSchema7 {\n\tif (!isPlainObj(schema)) return schema;\n\n\tconst result: JSONSchema7 = { ...schema };\n\tdelete result.required;\n\tdelete result.additionalProperties;\n\n\t// ── Recurse into properties ──\n\tif (isPlainObj(result.properties)) {\n\t\tconst props: Record<string, JSONSchema7Definition> = {};\n\t\tfor (const [key, value] of Object.entries(\n\t\t\tresult.properties as Record<string, JSONSchema7Definition>,\n\t\t)) {\n\t\t\tprops[key] =\n\t\t\t\ttypeof value === \"object\" && value !== null\n\t\t\t\t\t? stripRequiredRecursive(value)\n\t\t\t\t\t: value;\n\t\t}\n\t\tresult.properties = props;\n\t}\n\n\t// ── Recurse into items (single schema) ──\n\tif (isPlainObj(result.items) && !Array.isArray(result.items)) {\n\t\tresult.items = stripRequiredRecursive(result.items as JSONSchema7);\n\t}\n\n\t// ── Recurse into tuple items ──\n\tif (Array.isArray(result.items)) {\n\t\tresult.items = (result.items as JSONSchema7Definition[]).map((item) =>\n\t\t\ttypeof item === \"object\" && item !== null\n\t\t\t\t? stripRequiredRecursive(item)\n\t\t\t\t: item,\n\t\t);\n\t}\n\n\t// ── Recurse into branching keywords ──\n\tfor (const keyword of [\"oneOf\", \"anyOf\", \"allOf\"] as const) {\n\t\tif (Array.isArray(result[keyword])) {\n\t\t\tresult[keyword] = (result[keyword] as JSONSchema7Definition[]).map(\n\t\t\t\t(branch) =>\n\t\t\t\t\ttypeof branch === \"object\" && branch !== null\n\t\t\t\t\t\t? stripRequiredRecursive(branch)\n\t\t\t\t\t\t: branch,\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Recurse into conditional keywords ──\n\tif (isPlainObj(result.then)) {\n\t\tresult.then = stripRequiredRecursive(result.then as JSONSchema7);\n\t}\n\tif (isPlainObj(result.else)) {\n\t\tresult.else = stripRequiredRecursive(result.else as JSONSchema7);\n\t}\n\n\treturn result;\n}\n\n/**\n * Returns AJV validation errors for partial data — strips `required` and\n * `additionalProperties` before compilation so that only the properties\n * **present** in `data` are validated.\n *\n * @param schema - The schema to validate against (not mutated)\n * @param data - The partial runtime data\n * @returns Normalized runtime validation errors for present properties only\n */\nexport function getPartialRuntimeValidationErrors(\n\tschema: JSONSchema7Definition,\n\tdata: unknown,\n): SchemaError[] {\n\tif (typeof schema === \"boolean\") {\n\t\treturn getRuntimeValidationErrors(schema, data);\n\t}\n\n\tconst stripped = stripRequiredRecursive(schema);\n\treturn getRuntimeValidationErrors(stripped, data);\n}\n\n/**\n * Clears all compiled validator caches (WeakMap, LRU, and AJV internal).\n *\n * Useful for:\n * - Long-running processes where schemas evolve over time\n * - Test isolation (ensuring no cross-test cache pollution)\n * - Memory pressure situations where cached validators are no longer needed\n *\n * After calling this, the next validation call will recompile validators\n * from scratch — there is a one-time performance cost per unique schema.\n */\nexport function clearAllValidatorCaches(): void {\n\t// The WeakMap cannot be \"cleared\" via API — we replace the reference.\n\t// However, since it's a module-level const, we clear it by removing\n\t// AJV's internal schema cache which is the primary memory consumer.\n\t// The WeakMap entries will be garbage-collected when their schema keys\n\t// are no longer referenced.\n\n\t// Clear the LRU string-keyed cache\n\tvalidatorStringCache.clear();\n\n\t// Clear AJV's internal compiled schema cache\n\tajv.removeSchema();\n}\n"],"names":["clearAllValidatorCaches","getPartialRuntimeValidationErrors","getRuntimeValidationErrors","isDataValidForSchema","stripRequiredRecursive","ajv","Ajv","allErrors","strict","validateFormats","allowUnionTypes","messages","addFormats","validatorCache","WeakMap","LRUCache","get","key","value","cache","undefined","delete","set","has","size","max","firstKey","keys","next","clear","maxSize","Map","validatorStringCache","isObjectLike","stableStringify","JSON","stringify","Array","isArray","map","entry","join","entries","Object","sort","a","b","localeCompare","entryValue","getSchemaTypeName","schema","type","stringifyValue","normalizeInstancePath","instancePath","parts","split","filter","Boolean","length","path","rawPart","part","replace","isArrayIndex","test","formatAllowedValues","values","rendered","slice","formatExpected","error","keyword","expectedType","params","String","enum","const","missingProperty","targetSchema","properties","prefix","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems","minProperties","maxProperties","message","buildSchemaError","data","SchemaErrorType","RuntimeValidation","baseKey","expected","received","additionalProperty","compileValidator","cached","serialized","cachedByString","validate","compile","isValid","errors","isPlainObj","result","required","additionalProperties","props","items","item","branch","then","else","stripped","removeSchema"],"mappings":"mPA2iBgBA,iCAAAA,6BAvBAC,2CAAAA,uCAxHAC,oCAAAA,gCAnBAC,8BAAAA,0BAwEAC,gCAAAA,mFAjd6C,wEACtC,uCAGS,qCACL,sRAyC3B,MAAMC,IAAM,IAAIC,YAAG,CAAC,CACnBC,UAAW,KACXC,OAAQ,MACRC,gBAAiB,KACjBC,gBAAiB,KACjBC,SAAU,IACX,GAEAC,GAAAA,mBAAU,EAACP,KAQX,MAAMQ,eAAiB,IAAIC,OAQ3B,OAAM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,UAAYA,SAAW,KACtCnH,uBAAuBmH,QACvBA,OAEN,CACD,CAGA,GAAIP,GAAAA,mBAAU,EAACC,OAAOO,IAAI,EAAG,CAC5BP,OAAOO,IAAI,CAAGpH,uBAAuB6G,OAAOO,IAAI,CACjD,CACA,GAAIR,GAAAA,mBAAU,EAACC,OAAOQ,IAAI,EAAG,CAC5BR,OAAOQ,IAAI,CAAGrH,uBAAuB6G,OAAOQ,IAAI,CACjD,CAEA,OAAOR,MACR,CAWO,SAAShH,kCACfiD,MAA6B,CAC7B+C,IAAa,EAEb,GAAI,OAAO/C,SAAW,UAAW,CAChC,OAAOhD,2BAA2BgD,OAAQ+C,KAC3C,CAEA,MAAMyB,SAAWtH,uBAAuB8C,QACxC,OAAOhD,2BAA2BwH,SAAUzB,KAC7C,CAaO,SAASjG,0BAQfgC,qBAAqBH,KAAK,GAG1BxB,IAAIsH,YAAY,EACjB"}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime-validator.ts"],"sourcesContent":["import Ajv, { type ErrorObject, type ValidateFunction } from \"ajv\";\nimport addFormats from \"ajv-formats\";\nimport type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport type { SchemaError } from \"./types.ts\";\nimport { SchemaErrorType } from \"./types.ts\";\nimport { isPlainObj } from \"./utils.ts\";\n\n/**\n * ─── Runtime Validator ────────────────────────────────────────────────────────\n *\n * Centralizes runtime validation of JSON Schema Draft-07 schemas using AJV.\n *\n * Goals:\n * - Validate concrete runtime data against resolved schemas\n * - Reuse the same runtime engine for `check(..., { data })`\n * - Reuse the same runtime engine for `if/then/else` condition evaluation\n * - Keep the static subset-checking pipeline unchanged when no runtime data is provided\n *\n * Architecture — Singleton AJV instance:\n * The `ajv` constant below is a module-level singleton shared by every\n * `JsonSchemaCompatibilityChecker` instance in the same process. This is\n * intentional:\n * - Compiled validators are reused across checker instances, avoiding\n * redundant schema compilation and reducing memory usage.\n * - The WeakMap and LRU caches for `ValidateFunction` objects are valid\n * only for a single AJV instance; per-instance AJV would break caching.\n * - `ajv-formats` is registered once at module load; all standard Draft-07\n * formats are available globally.\n * - In worker-thread environments, each worker loads its own module scope\n * and gets its own AJV instance — no cross-worker sharing occurs.\n * - Custom AJV configuration or format registration is not supported\n * per-checker-instance. If needed in the future, the singleton could be\n * replaced with a factory, but this is intentionally deferred (YAGNI).\n *\n * Notes:\n * - AJV is configured in non-strict mode because this library intentionally\n * supports partially-specified / pragmatic schemas and some unsupported\n * keywords may appear in user input.\n * - Standard JSON Schema formats are enabled through `ajv-formats` so runtime\n * validation can influence condition resolution and `check(..., { data })`\n * consistently for supported formats.\n * - Unknown formats are still ignored in practice by the non-strict runtime\n * configuration instead of crashing the whole check pipeline.\n */\n\n// Singleton AJV instance — shared across all checker instances (see module JSDoc above)\nconst ajv = new Ajv({\n\tallErrors: true,\n\tstrict: false,\n\tvalidateFormats: true,\n\tallowUnionTypes: true,\n\tmessages: true,\n});\n\naddFormats(ajv);\n\n/**\n * Cache compiled validators by schema object reference.\n *\n * This mirrors the codebase's preference for WeakMap-based caching and avoids\n * recompiling validators for the same resolved schema instances.\n */\nconst validatorCache = new WeakMap<object, ValidateFunction>();\n\n/**\n * Minimal LRU cache using Map insertion-order guarantees for O(1) eviction.\n *\n * On `get`, the entry is moved to the end (most recently used).\n * On `set`, if the cache is full, the first entry (least recently used) is evicted.\n */\nclass LRUCache<K, V> {\n\tprivate readonly max: number;\n\tprivate readonly cache = new Map<K, V>();\n\n\tconstructor(maxSize: number) {\n\t\tthis.max = maxSize;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst value = this.cache.get(key);\n\t\tif (value === undefined) return undefined;\n\n\t\t// Move to end (most recently used)\n\t\tthis.cache.delete(key);\n\t\tthis.cache.set(key, value);\n\t\treturn value;\n\t}\n\n\tset(key: K, value: V): void {\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.delete(key);\n\t\t} else if (this.cache.size >= this.max) {\n\t\t\t// Evict least recently used (first key in iteration order)\n\t\t\tconst firstKey = this.cache.keys().next().value;\n\t\t\tif (firstKey !== undefined) {\n\t\t\t\tthis.cache.delete(firstKey);\n\t\t\t}\n\t\t}\n\t\tthis.cache.set(key, value);\n\t}\n\n\tclear(): void {\n\t\tthis.cache.clear();\n\t}\n}\n\n/**\n * LRU cache for compiled validators keyed by deterministic schema serialization.\n *\n * This is a fallback for schemas that are not stable object references (e.g.\n * freshly constructed schemas that are structurally identical to previously\n * seen ones). Bounded to 500 entries to prevent unbounded memory growth in\n * long-running processes. The WeakMap-based `validatorCache` remains the\n * primary cache for the hot path.\n */\nconst validatorStringCache = new LRUCache<string, ValidateFunction>(500);\n\nfunction isObjectLike(value: unknown): value is object {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction stableStringify(value: unknown): string {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn JSON.stringify(value);\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map((entry) => stableStringify(entry)).join(\",\")}]`;\n\t}\n\n\tconst entries = Object.entries(value as Record<string, unknown>).sort(\n\t\t([a], [b]) => a.localeCompare(b),\n\t);\n\n\treturn `{${entries\n\t\t.map(\n\t\t\t([key, entryValue]) =>\n\t\t\t\t`${JSON.stringify(key)}:${stableStringify(entryValue)}`,\n\t\t)\n\t\t.join(\",\")}}`;\n}\n\nfunction getSchemaTypeName(schema: JSONSchema7): string {\n\tif (schema.type === undefined) return \"value\";\n\n\tif (Array.isArray(schema.type)) {\n\t\treturn schema.type.join(\" | \");\n\t}\n\n\treturn schema.type;\n}\n\nfunction stringifyValue(value: unknown): string {\n\tif (value === undefined) return \"undefined\";\n\tif (typeof value === \"string\") return value;\n\treturn JSON.stringify(value);\n}\n\nfunction normalizeInstancePath(instancePath: string): string {\n\tif (instancePath === \"\") return \"$root\";\n\n\tconst parts = instancePath.split(\"/\").filter(Boolean);\n\tif (parts.length === 0) return \"$root\";\n\n\tlet path = \"\";\n\n\tfor (const rawPart of parts) {\n\t\tconst part = rawPart.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\t\tconst isArrayIndex = /^\\d+$/.test(part);\n\n\t\tif (isArrayIndex) {\n\t\t\tpath += \"[]\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tpath = path.length === 0 ? part : `${path}.${part}`;\n\t}\n\n\treturn path || \"$root\";\n}\n\nfunction formatAllowedValues(values: unknown[]): string {\n\tif (values.length === 0) return \"no allowed values\";\n\n\tconst rendered = values.map((value) =>\n\t\ttypeof value === \"string\" ? value : JSON.stringify(value),\n\t);\n\n\tif (rendered.length === 1) return rendered[0] ?? \"\";\n\tif (rendered.length === 2) return `${rendered[0]} or ${rendered[1]}`;\n\n\treturn `${rendered.slice(0, -1).join(\", \")}, or ${rendered[rendered.length - 1]}`;\n}\n\nfunction formatExpected(error: ErrorObject, schema: JSONSchema7): string {\n\tswitch (error.keyword) {\n\t\tcase \"type\": {\n\t\t\tconst expectedType =\n\t\t\t\ttypeof error.params === \"object\" &&\n\t\t\t\terror.params !== null &&\n\t\t\t\t\"type\" in error.params\n\t\t\t\t\t? String(error.params.type)\n\t\t\t\t\t: getSchemaTypeName(schema);\n\n\t\t\treturn expectedType;\n\t\t}\n\n\t\tcase \"enum\": {\n\t\t\treturn Array.isArray(schema.enum)\n\t\t\t\t? formatAllowedValues(schema.enum)\n\t\t\t\t: \"allowed enum value\";\n\t\t}\n\n\t\tcase \"const\": {\n\t\t\treturn stringifyValue(schema.const);\n\t\t}\n\n\t\tcase \"required\": {\n\t\t\tconst missingProperty =\n\t\t\t\ttypeof error.params === \"object\" &&\n\t\t\t\terror.params !== null &&\n\t\t\t\t\"missingProperty\" in error.params\n\t\t\t\t\t? String(error.params.missingProperty)\n\t\t\t\t\t: \"unknown\";\n\n\t\t\tconst targetSchema =\n\t\t\t\tschema.properties?.[missingProperty] &&\n\t\t\t\ttypeof schema.properties[missingProperty] !== \"boolean\"\n\t\t\t\t\t? (schema.properties[missingProperty] as JSONSchema7)\n\t\t\t\t\t: undefined;\n\n\t\t\tif (targetSchema?.type !== undefined) {\n\t\t\t\tconst prefix = normalizeInstancePath(error.instancePath);\n\t\t\t\tconst key =\n\t\t\t\t\tprefix === \"$root\" ? missingProperty : `${prefix}.${missingProperty}`;\n\t\t\t\treturn `${key}: ${getSchemaTypeName(targetSchema)}`;\n\t\t\t}\n\n\t\t\treturn `required property: ${missingProperty}`;\n\t\t}\n\n\t\tcase \"minimum\":\n\t\t\treturn `>= ${String((schema as JSONSchema7).minimum)}`;\n\n\t\tcase \"maximum\":\n\t\t\treturn `<= ${String((schema as JSONSchema7).maximum)}`;\n\n\t\tcase \"exclusiveMinimum\":\n\t\t\treturn `> ${String((schema as JSONSchema7).exclusiveMinimum)}`;\n\n\t\tcase \"exclusiveMaximum\":\n\t\t\treturn `< ${String((schema as JSONSchema7).exclusiveMaximum)}`;\n\n\t\tcase \"multipleOf\":\n\t\t\treturn `multipleOf ${String((schema as JSONSchema7).multipleOf)}`;\n\n\t\tcase \"minLength\":\n\t\t\treturn `minLength: ${String((schema as JSONSchema7).minLength)}`;\n\n\t\tcase \"maxLength\":\n\t\t\treturn `maxLength: ${String((schema as JSONSchema7).maxLength)}`;\n\n\t\tcase \"pattern\":\n\t\t\treturn `pattern: ${String((schema as JSONSchema7).pattern)}`;\n\n\t\tcase \"format\":\n\t\t\treturn `format: ${String((schema as JSONSchema7).format)}`;\n\n\t\tcase \"minItems\":\n\t\t\treturn `minItems: ${String((schema as JSONSchema7).minItems)}`;\n\n\t\tcase \"maxItems\":\n\t\t\treturn `maxItems: ${String((schema as JSONSchema7).maxItems)}`;\n\n\t\tcase \"uniqueItems\":\n\t\t\treturn \"uniqueItems: true\";\n\n\t\tcase \"minProperties\":\n\t\t\treturn `minProperties: ${String((schema as JSONSchema7).minProperties)}`;\n\n\t\tcase \"maxProperties\":\n\t\t\treturn `maxProperties: ${String((schema as JSONSchema7).maxProperties)}`;\n\n\t\tcase \"additionalProperties\":\n\t\t\treturn \"not allowed (additionalProperties: false)\";\n\n\t\tcase \"propertyNames\":\n\t\t\treturn \"valid property names\";\n\n\t\tcase \"contains\":\n\t\t\treturn \"contains at least one matching item\";\n\n\t\tcase \"allOf\":\n\t\t\treturn \"allOf constraints\";\n\n\t\tcase \"anyOf\":\n\t\t\treturn \"anyOf constraints\";\n\n\t\tcase \"oneOf\":\n\t\t\treturn \"oneOf constraints\";\n\n\t\tcase \"not\":\n\t\t\treturn \"not matching forbidden schema\";\n\n\t\tdefault:\n\t\t\treturn error.message ?? error.keyword;\n\t}\n}\n\nfunction buildSchemaError(\n\terror: ErrorObject,\n\tschema: JSONSchema7,\n\tdata: unknown,\n): SchemaError {\n\tconst type = SchemaErrorType.RuntimeValidation;\n\tconst baseKey = normalizeInstancePath(error.instancePath);\n\n\tif (error.keyword === \"required\") {\n\t\tconst missingProperty =\n\t\t\ttypeof error.params === \"object\" &&\n\t\t\terror.params !== null &&\n\t\t\t\"missingProperty\" in error.params\n\t\t\t\t? String(error.params.missingProperty)\n\t\t\t\t: \"unknown\";\n\n\t\treturn {\n\t\t\ttype,\n\t\t\tkey:\n\t\t\t\tbaseKey === \"$root\" ? missingProperty : `${baseKey}.${missingProperty}`,\n\t\t\texpected: formatExpected(error, schema),\n\t\t\treceived: \"undefined\",\n\t\t};\n\t}\n\n\tif (error.keyword === \"additionalProperties\") {\n\t\tconst additionalProperty =\n\t\t\ttypeof error.params === \"object\" &&\n\t\t\terror.params !== null &&\n\t\t\t\"additionalProperty\" in error.params\n\t\t\t\t? String(error.params.additionalProperty)\n\t\t\t\t: \"unknown\";\n\n\t\treturn {\n\t\t\ttype,\n\t\t\tkey:\n\t\t\t\tbaseKey === \"$root\"\n\t\t\t\t\t? additionalProperty\n\t\t\t\t\t: `${baseKey}.${additionalProperty}`,\n\t\t\texpected: formatExpected(error, schema),\n\t\t\treceived: \"present\",\n\t\t};\n\t}\n\n\treturn {\n\t\ttype,\n\t\tkey: baseKey,\n\t\texpected: formatExpected(error, schema),\n\t\treceived: stringifyValue(data),\n\t};\n}\n\nfunction compileValidator(schema: JSONSchema7): ValidateFunction {\n\tif (isObjectLike(schema)) {\n\t\tconst cached = validatorCache.get(schema);\n\t\tif (cached !== undefined) return cached;\n\t}\n\n\tconst serialized = stableStringify(schema);\n\tconst cachedByString = validatorStringCache.get(serialized);\n\tif (cachedByString !== undefined) {\n\t\tif (isObjectLike(schema)) {\n\t\t\tvalidatorCache.set(schema, cachedByString);\n\t\t}\n\t\treturn cachedByString;\n\t}\n\n\tconst validate = ajv.compile(schema);\n\n\tif (isObjectLike(schema)) {\n\t\tvalidatorCache.set(schema, validate);\n\t}\n\tvalidatorStringCache.set(serialized, validate);\n\n\treturn validate;\n}\n\n/**\n * Validates runtime data against a schema using AJV.\n *\n * @param schema - The schema to validate against\n * @param data - The runtime data to validate\n * @returns true when valid, false otherwise\n */\nexport function isDataValidForSchema(\n\tschema: JSONSchema7Definition,\n\tdata: unknown,\n): boolean {\n\tif (typeof schema === \"boolean\") {\n\t\treturn schema;\n\t}\n\n\tconst validate = compileValidator(schema);\n\treturn validate(data) === true;\n}\n\n/**\n * Returns AJV validation errors converted to the library's `SchemaError` shape.\n *\n * @param schema - The schema used for validation\n * @param data - The runtime data that failed validation\n * @returns Normalized runtime validation errors\n */\nexport function getRuntimeValidationErrors(\n\tschema: JSONSchema7Definition,\n\tdata: unknown,\n): SchemaError[] {\n\tif (typeof schema === \"boolean\") {\n\t\tif (schema) return [];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: SchemaErrorType.RuntimeValidation,\n\t\t\t\tkey: \"$root\",\n\t\t\t\texpected: \"never\",\n\t\t\t\treceived: stringifyValue(data),\n\t\t\t},\n\t\t];\n\t}\n\n\tconst validate = compileValidator(schema);\n\tconst isValid = validate(data);\n\n\tif (\n\t\tisValid === true ||\n\t\tvalidate.errors === null ||\n\t\tvalidate.errors === undefined\n\t) {\n\t\treturn [];\n\t}\n\n\treturn validate.errors.map((error) => buildSchemaError(error, schema, data));\n}\n\n// ─── Partial Validation ──────────────────────────────────────────────────────\n//\n// Strips `required` and `additionalProperties` from a schema recursively so\n// that AJV only validates the properties **present** in the data — without\n// reporting missing required properties, unexpected additional properties,\n// or minimum cardinality violations on truncated arrays/objects.\n//\n// This is used by the \"partial\" runtime validation mode: the caller has\n// partial data (e.g. only some properties known at design-time) and wants to\n// validate those values against the schema without false negatives for\n// properties that will be provided later by another source.\n\n/**\n * Recursively strips partial-mode constraints from a JSON Schema so that\n * AJV validates only the values present in the data without penalizing\n * absent or truncated entries.\n *\n * Stripped keywords:\n * - `required` — missing properties are not errors in partial data\n * - `additionalProperties` — extra properties are tolerated\n * - `minItems` — truncated arrays (e.g. after template filtering) are tolerated\n * - `minProperties` — objects with fewer keys than expected are tolerated\n *\n * Recurses into: `properties`, `items` (single + tuple), `oneOf`, `anyOf`,\n * `allOf`, `then`, `else`.\n *\n * @param schema - The schema to strip (not mutated — returns a new object)\n * @returns A new schema without partial-mode constraints at any level\n */\nexport function stripRequiredRecursive(schema: JSONSchema7): JSONSchema7 {\n\tif (!isPlainObj(schema)) return schema;\n\n\tconst result: JSONSchema7 = { ...schema };\n\tdelete result.required;\n\tdelete result.additionalProperties;\n\tdelete result.minItems;\n\tdelete result.minProperties;\n\n\t// ── Recurse into properties ──\n\tif (isPlainObj(result.properties)) {\n\t\tconst props: Record<string, JSONSchema7Definition> = {};\n\t\tfor (const [key, value] of Object.entries(\n\t\t\tresult.properties as Record<string, JSONSchema7Definition>,\n\t\t)) {\n\t\t\tprops[key] =\n\t\t\t\ttypeof value === \"object\" && value !== null\n\t\t\t\t\t? stripRequiredRecursive(value)\n\t\t\t\t\t: value;\n\t\t}\n\t\tresult.properties = props;\n\t}\n\n\t// ── Recurse into items (single schema) ──\n\tif (isPlainObj(result.items) && !Array.isArray(result.items)) {\n\t\tresult.items = stripRequiredRecursive(result.items as JSONSchema7);\n\t}\n\n\t// ── Recurse into tuple items ──\n\tif (Array.isArray(result.items)) {\n\t\tresult.items = (result.items as JSONSchema7Definition[]).map((item) =>\n\t\t\ttypeof item === \"object\" && item !== null\n\t\t\t\t? stripRequiredRecursive(item)\n\t\t\t\t: item,\n\t\t);\n\t}\n\n\t// ── Recurse into branching keywords ──\n\tfor (const keyword of [\"oneOf\", \"anyOf\", \"allOf\"] as const) {\n\t\tif (Array.isArray(result[keyword])) {\n\t\t\tresult[keyword] = (result[keyword] as JSONSchema7Definition[]).map(\n\t\t\t\t(branch) =>\n\t\t\t\t\ttypeof branch === \"object\" && branch !== null\n\t\t\t\t\t\t? stripRequiredRecursive(branch)\n\t\t\t\t\t\t: branch,\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Recurse into conditional keywords ──\n\tif (isPlainObj(result.then)) {\n\t\tresult.then = stripRequiredRecursive(result.then as JSONSchema7);\n\t}\n\tif (isPlainObj(result.else)) {\n\t\tresult.else = stripRequiredRecursive(result.else as JSONSchema7);\n\t}\n\n\treturn result;\n}\n\n/**\n * Returns AJV validation errors for partial data — strips `required`,\n * `additionalProperties`, `minItems`, and `minProperties` before compilation\n * so that only the values **present** in `data` are validated.\n *\n * @param schema - The schema to validate against (not mutated)\n * @param data - The partial runtime data\n * @returns Normalized runtime validation errors for present values only\n */\nexport function getPartialRuntimeValidationErrors(\n\tschema: JSONSchema7Definition,\n\tdata: unknown,\n): SchemaError[] {\n\tif (typeof schema === \"boolean\") {\n\t\treturn getRuntimeValidationErrors(schema, data);\n\t}\n\n\tconst stripped = stripRequiredRecursive(schema);\n\treturn getRuntimeValidationErrors(stripped, data);\n}\n\n/**\n * Clears all compiled validator caches (WeakMap, LRU, and AJV internal).\n *\n * Useful for:\n * - Long-running processes where schemas evolve over time\n * - Test isolation (ensuring no cross-test cache pollution)\n * - Memory pressure situations where cached validators are no longer needed\n *\n * After calling this, the next validation call will recompile validators\n * from scratch — there is a one-time performance cost per unique schema.\n */\nexport function clearAllValidatorCaches(): void {\n\t// The WeakMap cannot be \"cleared\" via API — we replace the reference.\n\t// However, since it's a module-level const, we clear it by removing\n\t// AJV's internal schema cache which is the primary memory consumer.\n\t// The WeakMap entries will be garbage-collected when their schema keys\n\t// are no longer referenced.\n\n\t// Clear the LRU string-keyed cache\n\tvalidatorStringCache.clear();\n\n\t// Clear AJV's internal compiled schema cache\n\tajv.removeSchema();\n}\n"],"names":["clearAllValidatorCaches","getPartialRuntimeValidationErrors","getRuntimeValidationErrors","isDataValidForSchema","stripRequiredRecursive","ajv","Ajv","allErrors","strict","validateFormats","allowUnionTypes","messages","addFormats","validatorCache","WeakMap","LRUCache","get","key","value","cache","undefined","delete","set","has","size","max","firstKey","keys","next","clear","maxSize","Map","validatorStringCache","isObjectLike","stableStringify","JSON","stringify","Array","isArray","map","entry","join","entries","Object","sort","a","b","localeCompare","entryValue","getSchemaTypeName","schema","type","stringifyValue","normalizeInstancePath","instancePath","parts","split","filter","Boolean","length","path","rawPart","part","replace","isArrayIndex","test","formatAllowedValues","values","rendered","slice","formatExpected","error","keyword","expectedType","params","String","enum","const","missingProperty","targetSchema","properties","prefix","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems","minProperties","maxProperties","message","buildSchemaError","data","SchemaErrorType","RuntimeValidation","baseKey","expected","received","additionalProperty","compileValidator","cached","serialized","cachedByString","validate","compile","isValid","errors","isPlainObj","result","required","additionalProperties","props","items","item","branch","then","else","stripped","removeSchema"],"mappings":"mPAojBgBA,iCAAAA,6BAvBAC,2CAAAA,uCAjIAC,oCAAAA,gCAnBAC,8BAAAA,0BA+EAC,gCAAAA,mFAxd6C,wEACtC,uCAGS,qCACL,sRAyC3B,MAAMC,IAAM,IAAIC,YAAG,CAAC,CACnBC,UAAW,KACXC,OAAQ,MACRC,gBAAiB,KACjBC,gBAAiB,KACjBC,SAAU,IACX,GAEAC,GAAAA,mBAAU,EAACP,KAQX,MAAMQ,eAAiB,IAAIC,OAQ3B,OAAMC,SAQLC,IAAIC,GAAM,CAAiB,CAC1B,MAAMC,MAAQ,IAAI,CAACC,KAAK,CAACH,GAAG,CAACC,KAC7B,GAAIC,QAAU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D,CAGA,GAAIP,GAAAA,mBAAU,EAACC,OAAOO,IAAI,EAAG,CAC5BP,OAAOO,IAAI,CAAGpH,uBAAuB6G,OAAOO,IAAI,CACjD,CACA,GAAIR,GAAAA,mBAAU,EAACC,OAAOQ,IAAI,EAAG,CAC5BR,OAAOQ,IAAI,CAAGrH,uBAAuB6G,OAAOQ,IAAI,CACjD,CAEA,OAAOR,MACR,CAWO,SAAShH,kCACfiD,MAA6B,CAC7B+C,IAAa,EAEb,GAAI,OAAO/C,SAAW,UAAW,CAChC,OAAOhD,2BAA2BgD,OAAQ+C,KAC3C,CAEA,MAAMyB,SAAWtH,uBAAuB8C,QACxC,OAAOhD,2BAA2BwH,SAAUzB,KAC7C,CAaO,SAASjG,0BAQfgC,qBAAqBH,KAAK,GAG1BxB,IAAIsH,YAAY,EACjB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get checkAtomic(){return checkAtomic},get checkBranchedSub(){return checkBranchedSub},get checkBranchedSup(){return checkBranchedSup},get getBranchesTyped(){return getBranchesTyped},get isAtomicSubsetOf(){return isAtomicSubsetOf}});const _formatvalidatorts=require("./format-validator.js");const _normalizerts=require("./normalizer.js");const _patternsubsetts=require("./pattern-subset.js");const _semanticerrorsts=require("./semantic-errors.js");const _utilsts=require("./utils.js");const BRANCH_TRUE={branches:[true],type:"none"};const BRANCH_FALSE={branches:[false],type:"none"};const atomicBranchCache=new WeakMap;function getBranchesTyped(def){if(typeof def==="boolean"){return def?BRANCH_TRUE:BRANCH_FALSE}if((0,_utilsts.hasOwn)(def,"anyOf")&&Array.isArray(def.anyOf)){return{branches:def.anyOf,type:"anyOf"}}if((0,_utilsts.hasOwn)(def,"oneOf")&&Array.isArray(def.oneOf)){return{branches:def.oneOf,type:"oneOf"}}let cached=atomicBranchCache.get(def);if(cached===undefined){cached={branches:[def],type:"none"};atomicBranchCache.set(def,cached)}return cached}function evaluateNot(sub,sup){if(typeof sub==="boolean"||typeof sup==="boolean")return null;if((0,_utilsts.hasOwn)(sup,"not")&&(0,_utilsts.isPlainObj)(sup.not)){const notSchema=sup.not;if((0,_utilsts.isPlainObj)(notSchema.properties)&&Array.isArray(notSchema.required)){const notProps=notSchema.properties;const notRequired=notSchema.required;if((0,_utilsts.isPlainObj)(sub.properties)){const subProps=sub.properties;const subRequired=Array.isArray(sub.required)?sub.required:[];const notPropKeys=Object.keys(notProps);const hasIncompatibleProp=notPropKeys.some(key=>{const notPropDef=notProps[key];if(typeof notPropDef==="boolean")return false;const notProp=notPropDef;if(notRequired.includes(key)&&!subRequired.includes(key)&&!(0,_utilsts.hasOwn)(subProps,key)){return true}if(!(0,_utilsts.hasOwn)(subProps,key))return false;const subPropDef=subProps[key];if(typeof subPropDef==="boolean")return false;const subProp=subPropDef;if((0,_utilsts.hasOwn)(notProp,"const")&&(0,_utilsts.hasOwn)(subProp,"const")){if(!(0,_utilsts.deepEqual)(notProp.const,subProp.const)){return true}}if((0,_utilsts.hasOwn)(notProp,"enum")&&Array.isArray(notProp.enum)){if((0,_utilsts.hasOwn)(subProp,"const")){const inNotEnum=notProp.enum.some(v=>(0,_utilsts.deepEqual)(v,subProp.const));if(!inNotEnum)return true}if((0,_utilsts.hasOwn)(subProp,"enum")&&Array.isArray(subProp.enum)){const noneInNotEnum=subProp.enum.every(v=>!notProp.enum?.some(nv=>(0,_utilsts.deepEqual)(v,nv)));if(noneInNotEnum)return true}}return false});if(hasIncompatibleProp)return true;const allPropsMatch=notPropKeys.every(key=>{const notPropDef=notProps[key];if(typeof notPropDef==="boolean")return true;const notProp=notPropDef;if(notRequired.includes(key)&&!subRequired.includes(key))return false;if(!(0,_utilsts.hasOwn)(subProps,key))return false;const subPropDef=subProps[key];if(typeof subPropDef==="boolean")return true;const subProp=subPropDef;if((0,_utilsts.hasOwn)(notProp,"const")&&(0,_utilsts.hasOwn)(subProp,"const")){return(0,_utilsts.deepEqual)(notProp.const,subProp.const)}if((0,_utilsts.hasOwn)(notProp,"enum")&&Array.isArray(notProp.enum)){if((0,_utilsts.hasOwn)(subProp,"const")){return notProp.enum.some(v=>(0,_utilsts.deepEqual)(v,subProp.const))}if((0,_utilsts.hasOwn)(subProp,"enum")&&Array.isArray(subProp.enum)){return subProp.enum.every(v=>notProp.enum?.some(nv=>(0,_utilsts.deepEqual)(v,nv)))}}return false});if(allPropsMatch)return false}}if((0,_utilsts.hasOwn)(notSchema,"const")&&(0,_utilsts.hasOwn)(sub,"const")){const notConst=notSchema.const;const subConst=sub.const;if((0,_utilsts.deepEqual)(subConst,notConst))return false;return true}if((0,_utilsts.hasOwn)(notSchema,"enum")&&Array.isArray(notSchema.enum)&&(0,_utilsts.hasOwn)(sub,"enum")&&Array.isArray(sub.enum)){const allExcluded=sub.enum.every(val=>!notSchema.enum?.some(notVal=>(0,_utilsts.deepEqual)(val,notVal)));if(allExcluded)return true}if((0,_utilsts.hasOwn)(notSchema,"type")&&(0,_utilsts.hasOwn)(sub,"type")){const notType=notSchema.type;const subType=sub.type;if(typeof notType==="string"&&typeof subType==="string"){if(!(0,_utilsts.hasOwn)(notSchema,"const")&&!(0,_utilsts.hasOwn)(notSchema,"enum")&&!(0,_utilsts.isPlainObj)(notSchema.properties)){if(subType===notType)return false;return true}}if(Array.isArray(notType)&&typeof subType==="string"){if(notType.includes(subType))return false;return true}}if((0,_utilsts.hasOwn)(notSchema,"anyOf")&&Array.isArray(notSchema.anyOf)){const branches=notSchema.anyOf;const allIncompatible=branches.every(branch=>{if(typeof branch==="boolean")return!branch;const result=evaluateNot(sub,{not:branch});return result===true});if(allIncompatible)return true;const anyBranchMatches=branches.some(branch=>{if(typeof branch==="boolean")return branch;const result=evaluateNot(sub,{not:branch});return result===false});if(anyBranchMatches)return false}if((0,_utilsts.hasOwn)(notSchema,"oneOf")&&Array.isArray(notSchema.oneOf)){const branches=notSchema.oneOf;const allIncompatible=branches.every(branch=>{if(typeof branch==="boolean")return!branch;const result=evaluateNot(sub,{not:branch});return result===true});if(allIncompatible)return true;const anyBranchMatches=branches.some(branch=>{if(typeof branch==="boolean")return branch;const result=evaluateNot(sub,{not:branch});return result===false});if(anyBranchMatches)return false}if((0,_utilsts.hasOwn)(notSchema,"format")&&(0,_utilsts.hasOwn)(sub,"format")){const subFormat=sub.format;const notFormat=notSchema.format;if(subFormat===notFormat)return false;return true}}if((0,_utilsts.hasOwn)(sub,"not")&&(0,_utilsts.hasOwn)(sup,"not")){if((0,_utilsts.deepEqual)(sub.not,sup.not))return true}return null}function stripNotFromSup(sub,sup,stripTopLevel=true){if(typeof sup==="boolean"||typeof sub==="boolean")return sup;let result=sup;if(stripTopLevel&&(0,_utilsts.hasOwn)(result,"not")){result=(0,_utilsts.omitKeys)(result,["not"])}if((0,_utilsts.isPlainObj)(result.properties)&&(0,_utilsts.isPlainObj)(sub.properties)){const subProps=sub.properties;const supProps=result.properties;let newProps;for(const key of Object.keys(supProps)){const supPropDef=supProps[key];const subPropDef=subProps[key];if(supPropDef!==undefined&&subPropDef!==undefined&&typeof supPropDef!=="boolean"&&typeof subPropDef!=="boolean"&&(0,_utilsts.hasOwn)(supPropDef,"not")){const propNotResult=evaluateNot(subPropDef,supPropDef);if(propNotResult===true){if(!newProps)newProps={...supProps};newProps[key]=(0,_utilsts.omitKeys)(supPropDef,["not"])}}}if(newProps){result={...result,properties:newProps}}}return result}function stripPatternFromSup(sub,sup){if(typeof sub==="boolean"||typeof sup==="boolean")return sup;const supObj=sup;let result=supObj;let copied=false;function ensureCopy(){if(!copied){result={...supObj};copied=true}return result}if((0,_utilsts.hasOwn)(result,"pattern")&&(0,_utilsts.hasOwn)(sub,"pattern")&&result.pattern!==sub.pattern){const patResult=(0,_patternsubsetts.isPatternSubset)(sub.pattern,result.pattern);if(patResult===true){result=(0,_utilsts.omitKeys)(ensureCopy(),["pattern"]);copied=true}}if((0,_utilsts.isPlainObj)(result.properties)&&(0,_utilsts.isPlainObj)(sub.properties)){const subProps=sub.properties;const supProps=result.properties;let propsModified=false;let newProps;for(const key of Object.keys(supProps)){const supPropDef=supProps[key];const subPropDef=subProps[key];if(supPropDef!==undefined&&subPropDef!==undefined&&typeof supPropDef!=="boolean"&&typeof subPropDef!=="boolean"&&(0,_utilsts.hasOwn)(supPropDef,"pattern")&&(0,_utilsts.hasOwn)(subPropDef,"pattern")&&supPropDef.pattern!==subPropDef.pattern){const propPatResult=(0,_patternsubsetts.isPatternSubset)(subPropDef.pattern,supPropDef.pattern);if(propPatResult===true){if(!newProps)newProps={...supProps};newProps[key]=(0,_utilsts.omitKeys)(supPropDef,["pattern"]);propsModified=true}}}if(propsModified&&newProps){ensureCopy().properties=newProps}}if((0,_utilsts.isPlainObj)(result.items)&&typeof result.items!=="boolean"&&(0,_utilsts.isPlainObj)(sub.items)&&typeof sub.items!=="boolean"){const subItems=sub.items;const supItems=result.items;if((0,_utilsts.hasOwn)(supItems,"pattern")&&(0,_utilsts.hasOwn)(subItems,"pattern")&&supItems.pattern!==subItems.pattern){const itemsPatResult=(0,_patternsubsetts.isPatternSubset)(subItems.pattern,supItems.pattern);if(itemsPatResult===true){ensureCopy().items=(0,_utilsts.omitKeys)(supItems,["pattern"])}}}return result}function stripVacuousFalseProperties(merged,sub){if(typeof merged==="boolean"||typeof sub==="boolean")return merged;if(!(0,_utilsts.isPlainObj)(merged.properties))return merged;const mergedProps=merged.properties;const subProps=(0,_utilsts.isPlainObj)(sub.properties)?sub.properties:{};let strippedProps=null;for(const key of Object.keys(mergedProps)){if(mergedProps[key]===false&&!(0,_utilsts.hasOwn)(subProps,key)){if(strippedProps===null){strippedProps={...mergedProps}}delete strippedProps[key]}}if(strippedProps===null)return merged;const result={...merged,properties:strippedProps};if(Object.keys(strippedProps).length===0&&!(0,_utilsts.isPlainObj)(sub.properties)){delete result.properties}return result}function hasNestedBranching(schema){if(typeof schema==="boolean")return false;if((0,_utilsts.isPlainObj)(schema.properties)){const props=schema.properties;for(const key of Object.keys(props)){const prop=props[key];if(prop===undefined||typeof prop==="boolean")continue;if((0,_utilsts.hasOwn)(prop,"oneOf")||(0,_utilsts.hasOwn)(prop,"anyOf"))return true;if(hasNestedBranching(prop))return true}}if((0,_utilsts.isPlainObj)(schema.items)&&typeof schema.items!=="boolean"){const items=schema.items;if((0,_utilsts.hasOwn)(items,"oneOf")||(0,_utilsts.hasOwn)(items,"anyOf"))return true;if(hasNestedBranching(items))return true}return false}function isPropertySubsetOf(sub,sup,engine){const{branches:subBranches}=getBranchesTyped(sub);if(subBranches.length>1||subBranches[0]!==sub){for(const branch of subBranches){if(branch===undefined)continue;if(!isAtomicSubsetOf(branch,sup,engine))return false}return true}return isAtomicSubsetOf(sub,sup,engine)}function isObjectSubsetByProperties(sub,sup,engine){const subIsObj=sub.type==="object"||(0,_utilsts.isPlainObj)(sub.properties);const supIsObj=sup.type==="object"||(0,_utilsts.isPlainObj)(sup.properties);if(!subIsObj&&!supIsObj){if(sub.type==="array"&&sup.type==="array"&&(0,_utilsts.isPlainObj)(sub.items)&&(0,_utilsts.isPlainObj)(sup.items)){return isPropertySubsetOf(sub.items,sup.items,engine)}return false}if(!subIsObj||!supIsObj)return false;if((0,_utilsts.hasOwn)(sub,"type")&&(0,_utilsts.hasOwn)(sup,"type")&&sub.type!==sup.type){return false}const subProps=(0,_utilsts.isPlainObj)(sub.properties)?sub.properties:{};const supProps=(0,_utilsts.isPlainObj)(sup.properties)?sup.properties:{};const subRequired=Array.isArray(sub.required)?sub.required:[];const supRequired=Array.isArray(sup.required)?sup.required:[];for(const key of supRequired){if(!subRequired.includes(key))return false}if(sup.additionalProperties===false){for(const key of Object.keys(subProps)){if(!(0,_utilsts.hasOwn)(supProps,key))return false}}for(const key of Object.keys(supProps)){const supProp=supProps[key];const subProp=subProps[key];if(supProp===undefined||subProp===undefined)continue;if(!isPropertySubsetOf(subProp,supProp,engine)){return false}}if((0,_utilsts.isPlainObj)(sup.additionalProperties)&&typeof sup.additionalProperties!=="boolean"){const addPropSchema=sup.additionalProperties;for(const key of Object.keys(subProps)){if((0,_utilsts.hasOwn)(supProps,key))continue;const subProp=subProps[key];if(subProp===undefined)continue;if(!isPropertySubsetOf(subProp,addPropSchema,engine)){return false}}}if((0,_utilsts.isPlainObj)(sub.items)&&(0,_utilsts.isPlainObj)(sup.items)){if(!isPropertySubsetOf(sub.items,sup.items,engine)){return false}}return true}function tryNestedBranchingFallback(sub,sup,engine){if(typeof sub==="boolean"||typeof sup==="boolean")return null;if(!hasNestedBranching(sub)&&!hasNestedBranching(sup))return null;return isObjectSubsetByProperties(sub,sup,engine)}function isAtomicSubsetOf(sub,sup,engine){const{branches:supBranches}=getBranchesTyped(sup);if(supBranches.length===1&&supBranches[0]===sup){const notResult=evaluateNot(sub,sup);if(notResult===false)return false;if(typeof sub!=="boolean"&&typeof sup!=="boolean"&&(0,_utilsts.hasOwn)(sub,"format")&&(0,_utilsts.hasOwn)(sup,"format")&&sub.format!==sup.format){const fmtResult=(0,_formatvalidatorts.isFormatSubset)(sub.format,sup.format);if(fmtResult!==true)return false}if(typeof sub!=="boolean"&&typeof sup!=="boolean"&&(0,_utilsts.hasOwn)(sub,"pattern")&&(0,_utilsts.hasOwn)(sup,"pattern")&&sub.pattern!==sup.pattern){const patResult=(0,_patternsubsetts.isPatternSubset)(sub.pattern,sup.pattern);if(patResult===false)return false}let effectiveSup=sup;if(typeof sup!=="boolean"){if(notResult===true){effectiveSup=stripNotFromSup(sub,sup,true);if(typeof effectiveSup!=="boolean"&&Object.keys(effectiveSup).length===0){return true}}else{effectiveSup=stripNotFromSup(sub,sup,false)}effectiveSup=stripPatternFromSup(sub,effectiveSup)}const merged=engine.merge(sub,effectiveSup);if(merged===null){return tryNestedBranchingFallback(sub,effectiveSup,engine)??false}if((0,_utilsts.deepEqual)(merged,sub))return true;const strippedMerged=stripVacuousFalseProperties(merged,sub);if(strippedMerged!==merged&&(0,_utilsts.deepEqual)(strippedMerged,sub)){return true}const normalizedMerged=(0,_normalizerts.normalize)(strippedMerged);if((0,_utilsts.deepEqual)(normalizedMerged,sub)||engine.isEqual(normalizedMerged,sub)){return true}return tryNestedBranchingFallback(sub,effectiveSup,engine)??false}return supBranches.some(branch=>{const notResult=evaluateNot(sub,branch);if(notResult===false)return false;if(typeof sub!=="boolean"&&typeof branch!=="boolean"&&(0,_utilsts.hasOwn)(sub,"pattern")&&(0,_utilsts.hasOwn)(branch,"pattern")&&sub.pattern!==branch.pattern){const patResult=(0,_patternsubsetts.isPatternSubset)(sub.pattern,branch.pattern);if(patResult===false)return false}let effectiveBranch=branch;if(typeof branch!=="boolean"){if(notResult===true){effectiveBranch=stripNotFromSup(sub,branch,true);if(typeof effectiveBranch!=="boolean"&&Object.keys(effectiveBranch).length===0){return true}}else{effectiveBranch=stripNotFromSup(sub,branch,false)}effectiveBranch=stripPatternFromSup(sub,effectiveBranch)}const merged=engine.merge(sub,effectiveBranch);if(merged===null){return tryNestedBranchingFallback(sub,effectiveBranch,engine)===true}if((0,_utilsts.deepEqual)(merged,sub))return true;const strippedBranch=stripVacuousFalseProperties(merged,sub);if(strippedBranch!==merged&&(0,_utilsts.deepEqual)(strippedBranch,sub)){return true}const normalizedBranch=(0,_normalizerts.normalize)(strippedBranch);if((0,_utilsts.deepEqual)(normalizedBranch,sub)||engine.isEqual(normalizedBranch,sub)){return true}return tryNestedBranchingFallback(sub,effectiveBranch,engine)===true})}function checkBranchedSub(subBranches,sup,engine,branchType="anyOf"){const allErrors=[];let allSubset=true;for(let i=0;i<subBranches.length;i++){const branch=subBranches[i];if(branch===undefined)continue;if(!isAtomicSubsetOf(branch,sup,engine)){allSubset=false;const branchErrors=(0,_semanticerrorsts.computeSemanticErrors)(branch,sup,"");allErrors.push(...branchErrors)}}return{isSubset:allSubset,merged:allSubset?branchType==="oneOf"?{oneOf:subBranches}:{anyOf:subBranches}:null,errors:allErrors}}function checkBranchedSup(sub,supBranches,engine,_branchType="anyOf"){for(const branch of supBranches){let effectiveBranch=branch;if(typeof sub!=="boolean"&&typeof branch!=="boolean"){effectiveBranch=stripPatternFromSup(sub,branch)}const merged=engine.merge(sub,effectiveBranch);if(merged!==null){if((0,_utilsts.deepEqual)(merged,sub)){return{isSubset:true,merged,errors:[]}}const normalizedMerged=(0,_normalizerts.normalize)(merged);if((0,_utilsts.deepEqual)(normalizedMerged,sub)||engine.isEqual(normalizedMerged,sub)){return{isSubset:true,merged,errors:[]}}}}const semanticErrors=(0,_semanticerrorsts.computeSemanticErrors)(sub,{anyOf:supBranches},"");return{isSubset:false,merged:null,errors:semanticErrors}}function checkAtomic(sub,sup,engine){let effectiveSup=sup;if(typeof sub!=="boolean"&&typeof sup!=="boolean"){effectiveSup=stripPatternFromSup(sub,sup)}try{const merged=engine.mergeOrThrow(sub,effectiveSup);if((0,_utilsts.deepEqual)(merged,sub)){return{isSubset:true,merged,errors:[]}}const strippedMerged=stripVacuousFalseProperties(merged,sub);if(strippedMerged!==merged&&(0,_utilsts.deepEqual)(strippedMerged,sub)){return{isSubset:true,merged:strippedMerged,errors:[]}}const normalizedMerged=(0,_normalizerts.normalize)(strippedMerged);if((0,_utilsts.deepEqual)(normalizedMerged,sub)||engine.isEqual(normalizedMerged,sub)){return{isSubset:true,merged:normalizedMerged,errors:[]}}if(tryNestedBranchingFallback(sub,effectiveSup,engine)===true){return{isSubset:true,merged:sub,errors:[]}}const errors=(0,_semanticerrorsts.computeSemanticErrors)(sub,sup,"");return{isSubset:false,merged:normalizedMerged,errors}}catch(_e){if(tryNestedBranchingFallback(sub,effectiveSup,engine)===true){return{isSubset:true,merged:sub,errors:[]}}const errors=(0,_semanticerrorsts.computeSemanticErrors)(sub,sup,"");return{isSubset:false,merged:null,errors}}}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get checkAtomic(){return checkAtomic},get checkBranchedSub(){return checkBranchedSub},get checkBranchedSup(){return checkBranchedSup},get getBranchesTyped(){return getBranchesTyped},get isAtomicSubsetOf(){return isAtomicSubsetOf}});const _formatvalidatorts=require("./format-validator.js");const _normalizerts=require("./normalizer.js");const _patternsubsetts=require("./pattern-subset.js");const _semanticerrorsts=require("./semantic-errors.js");const _utilsts=require("./utils.js");const BRANCH_TRUE={branches:[true],type:"none"};const BRANCH_FALSE={branches:[false],type:"none"};const atomicBranchCache=new WeakMap;function getBranchesTyped(def){if(typeof def==="boolean"){return def?BRANCH_TRUE:BRANCH_FALSE}if((0,_utilsts.hasOwn)(def,"anyOf")&&Array.isArray(def.anyOf)){return{branches:def.anyOf,type:"anyOf"}}if((0,_utilsts.hasOwn)(def,"oneOf")&&Array.isArray(def.oneOf)){return{branches:def.oneOf,type:"oneOf"}}let cached=atomicBranchCache.get(def);if(cached===undefined){cached={branches:[def],type:"none"};atomicBranchCache.set(def,cached)}return cached}function evaluateNot(sub,sup){if(typeof sub==="boolean"||typeof sup==="boolean")return null;if((0,_utilsts.hasOwn)(sup,"not")&&(0,_utilsts.isPlainObj)(sup.not)){const notSchema=sup.not;if((0,_utilsts.isPlainObj)(notSchema.properties)&&Array.isArray(notSchema.required)){const notProps=notSchema.properties;const notRequired=notSchema.required;if((0,_utilsts.isPlainObj)(sub.properties)){const subProps=sub.properties;const subRequired=Array.isArray(sub.required)?sub.required:[];const notPropKeys=Object.keys(notProps);const hasIncompatibleProp=notPropKeys.some(key=>{const notPropDef=notProps[key];if(typeof notPropDef==="boolean")return false;const notProp=notPropDef;if(notRequired.includes(key)&&!subRequired.includes(key)&&!(0,_utilsts.hasOwn)(subProps,key)){return true}if(!(0,_utilsts.hasOwn)(subProps,key))return false;const subPropDef=subProps[key];if(typeof subPropDef==="boolean")return false;const subProp=subPropDef;if((0,_utilsts.hasOwn)(notProp,"const")&&(0,_utilsts.hasOwn)(subProp,"const")){if(!(0,_utilsts.deepEqual)(notProp.const,subProp.const)){return true}}if((0,_utilsts.hasOwn)(notProp,"enum")&&Array.isArray(notProp.enum)){if((0,_utilsts.hasOwn)(subProp,"const")){const inNotEnum=notProp.enum.some(v=>(0,_utilsts.deepEqual)(v,subProp.const));if(!inNotEnum)return true}if((0,_utilsts.hasOwn)(subProp,"enum")&&Array.isArray(subProp.enum)){const noneInNotEnum=subProp.enum.every(v=>!notProp.enum?.some(nv=>(0,_utilsts.deepEqual)(v,nv)));if(noneInNotEnum)return true}}return false});if(hasIncompatibleProp)return true;const allPropsMatch=notPropKeys.every(key=>{const notPropDef=notProps[key];if(typeof notPropDef==="boolean")return true;const notProp=notPropDef;if(notRequired.includes(key)&&!subRequired.includes(key))return false;if(!(0,_utilsts.hasOwn)(subProps,key))return false;const subPropDef=subProps[key];if(typeof subPropDef==="boolean")return true;const subProp=subPropDef;if((0,_utilsts.hasOwn)(notProp,"const")&&(0,_utilsts.hasOwn)(subProp,"const")){return(0,_utilsts.deepEqual)(notProp.const,subProp.const)}if((0,_utilsts.hasOwn)(notProp,"enum")&&Array.isArray(notProp.enum)){if((0,_utilsts.hasOwn)(subProp,"const")){return notProp.enum.some(v=>(0,_utilsts.deepEqual)(v,subProp.const))}if((0,_utilsts.hasOwn)(subProp,"enum")&&Array.isArray(subProp.enum)){return subProp.enum.every(v=>notProp.enum?.some(nv=>(0,_utilsts.deepEqual)(v,nv)))}}return false});if(allPropsMatch)return false}}if((0,_utilsts.hasOwn)(notSchema,"const")&&(0,_utilsts.hasOwn)(sub,"const")){const notConst=notSchema.const;const subConst=sub.const;if((0,_utilsts.deepEqual)(subConst,notConst))return false;return true}if((0,_utilsts.hasOwn)(notSchema,"enum")&&Array.isArray(notSchema.enum)&&(0,_utilsts.hasOwn)(sub,"enum")&&Array.isArray(sub.enum)){const allExcluded=sub.enum.every(val=>!notSchema.enum?.some(notVal=>(0,_utilsts.deepEqual)(val,notVal)));if(allExcluded)return true}if((0,_utilsts.hasOwn)(notSchema,"type")&&(0,_utilsts.hasOwn)(sub,"type")){const notType=notSchema.type;const subType=sub.type;if(typeof notType==="string"&&typeof subType==="string"){if(!(0,_utilsts.hasOwn)(notSchema,"const")&&!(0,_utilsts.hasOwn)(notSchema,"enum")&&!(0,_utilsts.isPlainObj)(notSchema.properties)){if(subType===notType)return false;return true}}if(Array.isArray(notType)&&typeof subType==="string"){if(notType.includes(subType))return false;return true}}if((0,_utilsts.hasOwn)(notSchema,"anyOf")&&Array.isArray(notSchema.anyOf)){const branches=notSchema.anyOf;const allIncompatible=branches.every(branch=>{if(typeof branch==="boolean")return!branch;const result=evaluateNot(sub,{not:branch});return result===true});if(allIncompatible)return true;const anyBranchMatches=branches.some(branch=>{if(typeof branch==="boolean")return branch;const result=evaluateNot(sub,{not:branch});return result===false});if(anyBranchMatches)return false}if((0,_utilsts.hasOwn)(notSchema,"oneOf")&&Array.isArray(notSchema.oneOf)){const branches=notSchema.oneOf;const allIncompatible=branches.every(branch=>{if(typeof branch==="boolean")return!branch;const result=evaluateNot(sub,{not:branch});return result===true});if(allIncompatible)return true;const anyBranchMatches=branches.some(branch=>{if(typeof branch==="boolean")return branch;const result=evaluateNot(sub,{not:branch});return result===false});if(anyBranchMatches)return false}if((0,_utilsts.hasOwn)(notSchema,"format")&&(0,_utilsts.hasOwn)(sub,"format")){const subFormat=sub.format;const notFormat=notSchema.format;if(subFormat===notFormat)return false;return true}}if((0,_utilsts.hasOwn)(sub,"not")&&(0,_utilsts.hasOwn)(sup,"not")){if((0,_utilsts.deepEqual)(sub.not,sup.not))return true}return null}function stripNotFromSup(sub,sup,stripTopLevel=true){if(typeof sup==="boolean"||typeof sub==="boolean")return sup;let result=sup;if(stripTopLevel&&(0,_utilsts.hasOwn)(result,"not")){result=(0,_utilsts.omitKeys)(result,["not"])}if((0,_utilsts.isPlainObj)(result.properties)&&(0,_utilsts.isPlainObj)(sub.properties)){const subProps=sub.properties;const supProps=result.properties;let newProps;for(const key of Object.keys(supProps)){const supPropDef=supProps[key];const subPropDef=subProps[key];if(supPropDef!==undefined&&subPropDef!==undefined&&typeof supPropDef!=="boolean"&&typeof subPropDef!=="boolean"&&(0,_utilsts.hasOwn)(supPropDef,"not")){const propNotResult=evaluateNot(subPropDef,supPropDef);if(propNotResult===true){if(!newProps)newProps={...supProps};newProps[key]=(0,_utilsts.omitKeys)(supPropDef,["not"])}}}if(newProps){result={...result,properties:newProps}}}return result}function stripPatternFromSup(sub,sup){if(typeof sub==="boolean"||typeof sup==="boolean")return sup;const supObj=sup;let result=supObj;let copied=false;function ensureCopy(){if(!copied){result={...supObj};copied=true}return result}if((0,_utilsts.hasOwn)(result,"pattern")&&(0,_utilsts.hasOwn)(sub,"pattern")&&result.pattern!==sub.pattern){const patResult=(0,_patternsubsetts.isPatternSubset)(sub.pattern,result.pattern);if(patResult===true){result=(0,_utilsts.omitKeys)(ensureCopy(),["pattern"]);copied=true}}if((0,_utilsts.isPlainObj)(result.properties)&&(0,_utilsts.isPlainObj)(sub.properties)){const subProps=sub.properties;const supProps=result.properties;let propsModified=false;let newProps;for(const key of Object.keys(supProps)){const supPropDef=supProps[key];const subPropDef=subProps[key];if(supPropDef!==undefined&&subPropDef!==undefined&&typeof supPropDef!=="boolean"&&typeof subPropDef!=="boolean"&&(0,_utilsts.hasOwn)(supPropDef,"pattern")&&(0,_utilsts.hasOwn)(subPropDef,"pattern")&&supPropDef.pattern!==subPropDef.pattern){const propPatResult=(0,_patternsubsetts.isPatternSubset)(subPropDef.pattern,supPropDef.pattern);if(propPatResult===true){if(!newProps)newProps={...supProps};newProps[key]=(0,_utilsts.omitKeys)(supPropDef,["pattern"]);propsModified=true}}}if(propsModified&&newProps){ensureCopy().properties=newProps}}if((0,_utilsts.isPlainObj)(result.items)&&typeof result.items!=="boolean"&&(0,_utilsts.isPlainObj)(sub.items)&&typeof sub.items!=="boolean"){const subItems=sub.items;const supItems=result.items;if((0,_utilsts.hasOwn)(supItems,"pattern")&&(0,_utilsts.hasOwn)(subItems,"pattern")&&supItems.pattern!==subItems.pattern){const itemsPatResult=(0,_patternsubsetts.isPatternSubset)(subItems.pattern,supItems.pattern);if(itemsPatResult===true){ensureCopy().items=(0,_utilsts.omitKeys)(supItems,["pattern"])}}}return result}function stripVacuousFalseProperties(merged,sub){if(typeof merged==="boolean"||typeof sub==="boolean")return merged;if(!(0,_utilsts.isPlainObj)(merged.properties))return merged;const mergedProps=merged.properties;const subProps=(0,_utilsts.isPlainObj)(sub.properties)?sub.properties:{};let strippedProps=null;for(const key of Object.keys(mergedProps)){if(mergedProps[key]===false&&!(0,_utilsts.hasOwn)(subProps,key)){if(strippedProps===null){strippedProps={...mergedProps}}delete strippedProps[key]}}if(strippedProps===null)return merged;const result={...merged,properties:strippedProps};if(Object.keys(strippedProps).length===0&&!(0,_utilsts.isPlainObj)(sub.properties)){delete result.properties}return result}function hasNestedBranching(schema){if(typeof schema==="boolean")return false;if((0,_utilsts.isPlainObj)(schema.properties)){const props=schema.properties;for(const key of Object.keys(props)){const prop=props[key];if(prop===undefined||typeof prop==="boolean")continue;if((0,_utilsts.hasOwn)(prop,"oneOf")||(0,_utilsts.hasOwn)(prop,"anyOf"))return true;if(hasNestedBranching(prop))return true}}if((0,_utilsts.isPlainObj)(schema.items)&&typeof schema.items!=="boolean"){const items=schema.items;if((0,_utilsts.hasOwn)(items,"oneOf")||(0,_utilsts.hasOwn)(items,"anyOf"))return true;if(hasNestedBranching(items))return true}return false}function isPropertySubsetOf(sub,sup,engine){const{branches:subBranches}=getBranchesTyped(sub);if(subBranches.length>1||subBranches[0]!==sub){for(const branch of subBranches){if(branch===undefined)continue;if(!isAtomicSubsetOf(branch,sup,engine))return false}return true}return isAtomicSubsetOf(sub,sup,engine)}function isArrayConstraintsSubset(sub,sup){if(sup.minItems!==undefined){if(sub.minItems===undefined||sub.minItems<sup.minItems){return false}}if(sup.maxItems!==undefined){if(sub.maxItems===undefined||sub.maxItems>sup.maxItems){return false}}if(sup.uniqueItems===true&&sub.uniqueItems!==true){return false}return true}function isObjectSubsetByProperties(sub,sup,engine){const subIsObj=sub.type==="object"||(0,_utilsts.isPlainObj)(sub.properties);const supIsObj=sup.type==="object"||(0,_utilsts.isPlainObj)(sup.properties);if(!subIsObj&&!supIsObj){if(sub.type==="array"&&sup.type==="array"&&(0,_utilsts.isPlainObj)(sub.items)&&(0,_utilsts.isPlainObj)(sup.items)){if(!isPropertySubsetOf(sub.items,sup.items,engine)){return false}return isArrayConstraintsSubset(sub,sup)}return false}if(!subIsObj||!supIsObj)return false;if((0,_utilsts.hasOwn)(sub,"type")&&(0,_utilsts.hasOwn)(sup,"type")&&sub.type!==sup.type){return false}const subProps=(0,_utilsts.isPlainObj)(sub.properties)?sub.properties:{};const supProps=(0,_utilsts.isPlainObj)(sup.properties)?sup.properties:{};const subRequired=Array.isArray(sub.required)?sub.required:[];const supRequired=Array.isArray(sup.required)?sup.required:[];for(const key of supRequired){if(!subRequired.includes(key))return false}if(sup.additionalProperties===false){for(const key of Object.keys(subProps)){if(!(0,_utilsts.hasOwn)(supProps,key))return false}}for(const key of Object.keys(supProps)){const supProp=supProps[key];const subProp=subProps[key];if(supProp===undefined||subProp===undefined)continue;if(!isPropertySubsetOf(subProp,supProp,engine)){return false}}if((0,_utilsts.isPlainObj)(sup.additionalProperties)&&typeof sup.additionalProperties!=="boolean"){const addPropSchema=sup.additionalProperties;for(const key of Object.keys(subProps)){if((0,_utilsts.hasOwn)(supProps,key))continue;const subProp=subProps[key];if(subProp===undefined)continue;if(!isPropertySubsetOf(subProp,addPropSchema,engine)){return false}}}if((0,_utilsts.isPlainObj)(sub.items)&&(0,_utilsts.isPlainObj)(sup.items)){if(!isPropertySubsetOf(sub.items,sup.items,engine)){return false}if(!isArrayConstraintsSubset(sub,sup)){return false}}return true}function tryNestedBranchingFallback(sub,sup,engine){if(typeof sub==="boolean"||typeof sup==="boolean")return null;if(!hasNestedBranching(sub)&&!hasNestedBranching(sup))return null;return isObjectSubsetByProperties(sub,sup,engine)}function isAtomicSubsetOf(sub,sup,engine){const{branches:supBranches}=getBranchesTyped(sup);if(supBranches.length===1&&supBranches[0]===sup){const notResult=evaluateNot(sub,sup);if(notResult===false)return false;if(typeof sub!=="boolean"&&typeof sup!=="boolean"&&(0,_utilsts.hasOwn)(sub,"format")&&(0,_utilsts.hasOwn)(sup,"format")&&sub.format!==sup.format){const fmtResult=(0,_formatvalidatorts.isFormatSubset)(sub.format,sup.format);if(fmtResult!==true)return false}if(typeof sub!=="boolean"&&typeof sup!=="boolean"&&(0,_utilsts.hasOwn)(sub,"pattern")&&(0,_utilsts.hasOwn)(sup,"pattern")&&sub.pattern!==sup.pattern){const patResult=(0,_patternsubsetts.isPatternSubset)(sub.pattern,sup.pattern);if(patResult===false)return false}let effectiveSup=sup;if(typeof sup!=="boolean"){if(notResult===true){effectiveSup=stripNotFromSup(sub,sup,true);if(typeof effectiveSup!=="boolean"&&Object.keys(effectiveSup).length===0){return true}}else{effectiveSup=stripNotFromSup(sub,sup,false)}effectiveSup=stripPatternFromSup(sub,effectiveSup)}const merged=engine.merge(sub,effectiveSup);if(merged===null){return tryNestedBranchingFallback(sub,effectiveSup,engine)??false}if((0,_utilsts.deepEqual)(merged,sub))return true;const strippedMerged=stripVacuousFalseProperties(merged,sub);if(strippedMerged!==merged&&(0,_utilsts.deepEqual)(strippedMerged,sub)){return true}const normalizedMerged=(0,_normalizerts.normalize)(strippedMerged);if((0,_utilsts.deepEqual)(normalizedMerged,sub)||engine.isEqual(normalizedMerged,sub)){return true}return tryNestedBranchingFallback(sub,effectiveSup,engine)??false}return supBranches.some(branch=>{const notResult=evaluateNot(sub,branch);if(notResult===false)return false;if(typeof sub!=="boolean"&&typeof branch!=="boolean"&&(0,_utilsts.hasOwn)(sub,"pattern")&&(0,_utilsts.hasOwn)(branch,"pattern")&&sub.pattern!==branch.pattern){const patResult=(0,_patternsubsetts.isPatternSubset)(sub.pattern,branch.pattern);if(patResult===false)return false}let effectiveBranch=branch;if(typeof branch!=="boolean"){if(notResult===true){effectiveBranch=stripNotFromSup(sub,branch,true);if(typeof effectiveBranch!=="boolean"&&Object.keys(effectiveBranch).length===0){return true}}else{effectiveBranch=stripNotFromSup(sub,branch,false)}effectiveBranch=stripPatternFromSup(sub,effectiveBranch)}const merged=engine.merge(sub,effectiveBranch);if(merged===null){return tryNestedBranchingFallback(sub,effectiveBranch,engine)===true}if((0,_utilsts.deepEqual)(merged,sub))return true;const strippedBranch=stripVacuousFalseProperties(merged,sub);if(strippedBranch!==merged&&(0,_utilsts.deepEqual)(strippedBranch,sub)){return true}const normalizedBranch=(0,_normalizerts.normalize)(strippedBranch);if((0,_utilsts.deepEqual)(normalizedBranch,sub)||engine.isEqual(normalizedBranch,sub)){return true}return tryNestedBranchingFallback(sub,effectiveBranch,engine)===true})}function checkBranchedSub(subBranches,sup,engine,branchType="anyOf"){const allErrors=[];let allSubset=true;for(let i=0;i<subBranches.length;i++){const branch=subBranches[i];if(branch===undefined)continue;if(!isAtomicSubsetOf(branch,sup,engine)){allSubset=false;const branchErrors=(0,_semanticerrorsts.computeSemanticErrors)(branch,sup,"");allErrors.push(...branchErrors)}}return{isSubset:allSubset,merged:allSubset?branchType==="oneOf"?{oneOf:subBranches}:{anyOf:subBranches}:null,errors:allErrors}}function checkBranchedSup(sub,supBranches,engine,_branchType="anyOf"){for(const branch of supBranches){let effectiveBranch=branch;if(typeof sub!=="boolean"&&typeof branch!=="boolean"){effectiveBranch=stripPatternFromSup(sub,branch)}const merged=engine.merge(sub,effectiveBranch);if(merged!==null){if((0,_utilsts.deepEqual)(merged,sub)){return{isSubset:true,merged,errors:[]}}const normalizedMerged=(0,_normalizerts.normalize)(merged);if((0,_utilsts.deepEqual)(normalizedMerged,sub)||engine.isEqual(normalizedMerged,sub)){return{isSubset:true,merged,errors:[]}}}}const semanticErrors=(0,_semanticerrorsts.computeSemanticErrors)(sub,{anyOf:supBranches},"");return{isSubset:false,merged:null,errors:semanticErrors}}function checkAtomic(sub,sup,engine){let effectiveSup=sup;if(typeof sub!=="boolean"&&typeof sup!=="boolean"){effectiveSup=stripPatternFromSup(sub,sup)}try{const merged=engine.mergeOrThrow(sub,effectiveSup);if((0,_utilsts.deepEqual)(merged,sub)){return{isSubset:true,merged,errors:[]}}const strippedMerged=stripVacuousFalseProperties(merged,sub);if(strippedMerged!==merged&&(0,_utilsts.deepEqual)(strippedMerged,sub)){return{isSubset:true,merged:strippedMerged,errors:[]}}const normalizedMerged=(0,_normalizerts.normalize)(strippedMerged);if((0,_utilsts.deepEqual)(normalizedMerged,sub)||engine.isEqual(normalizedMerged,sub)){return{isSubset:true,merged:normalizedMerged,errors:[]}}if(tryNestedBranchingFallback(sub,effectiveSup,engine)===true){return{isSubset:true,merged:sub,errors:[]}}const errors=(0,_semanticerrorsts.computeSemanticErrors)(sub,sup,"");return{isSubset:false,merged:normalizedMerged,errors}}catch(_e){if(tryNestedBranchingFallback(sub,effectiveSup,engine)===true){return{isSubset:true,merged:sub,errors:[]}}const errors=(0,_semanticerrorsts.computeSemanticErrors)(sub,sup,"");return{isSubset:false,merged:null,errors}}}
|
|
2
2
|
//# sourceMappingURL=subset-checker.js.map
|