From 1339578ae22abb1126af788227cd855fa9869f1e Mon Sep 17 00:00:00 2001 From: Luigi Bifulco Date: Wed, 7 Oct 2026 18:52:40 +0200 Subject: [PATCH 1/4] fix(core): store the new Ajv instance when handling setAjv The SET_AJV reducer compiled the schema with the new Ajv instance but never wrote it to state, so every later setSchema or re-enabled validation silently went back to the previous instance. Part of #1498 Co-Authored-By: Claude Fable 5.1 --- packages/core/src/reducers/core.ts | 1 + packages/core/test/reducers/core.test.ts | 71 ++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/packages/core/src/reducers/core.ts b/packages/core/src/reducers/core.ts index 940c9d3f1..efb3fbda0 100644 --- a/packages/core/src/reducers/core.ts +++ b/packages/core/src/reducers/core.ts @@ -200,6 +200,7 @@ export const coreReducer: Reducer = ( const errors = validate(validator, state.data); return { ...state, + ajv: currentAjv, validator, errors, }; diff --git a/packages/core/test/reducers/core.test.ts b/packages/core/test/reducers/core.test.ts index 1df87b84b..7ba5d74aa 100644 --- a/packages/core/test/reducers/core.test.ts +++ b/packages/core/test/reducers/core.test.ts @@ -27,6 +27,7 @@ import Ajv, { ErrorObject } from 'ajv'; import { coreReducer } from '../../src/reducers'; import { init, + setAjv, setSchema, setValidationMode, update, @@ -2147,6 +2148,76 @@ test('core reducer - setSchema - schema with id', (t) => { t.is(after.schema.properties.animal.minLength, 5); }); +test('core reducer - setAjv - stores the new ajv instance in state', (t) => { + const schema: JsonSchema = { + type: 'object', + properties: { + foo: { type: 'string' }, + }, + }; + const before: JsonFormsCore = coreReducer( + undefined, + init({ foo: 'bar' }, schema, undefined, undefined) + ); + const newAjv = createAjv(); + t.not(before.ajv, newAjv); + + const after: JsonFormsCore = coreReducer(before, setAjv(newAjv)); + t.is(after.ajv, newAjv); + t.not(after.validator, before.validator); +}); + +test('core reducer - setAjv - later setSchema compiles with the new ajv instance', (t) => { + // Two violated constraints: the default ajv (allErrors: true) reports both, + // an ajv with allErrors: false reports only the first one. + const schema: JsonSchema = { + type: 'object', + properties: { + foo: { type: 'string', minLength: 5, pattern: '^a' }, + }, + }; + const before: JsonFormsCore = coreReducer( + undefined, + init({ foo: 'b' }, schema, undefined, undefined) + ); + t.is(before.errors.length, 2); + + const firstErrorOnlyAjv = createAjv({ allErrors: false }); + const afterSetAjv: JsonFormsCore = coreReducer( + before, + setAjv(firstErrorOnlyAjv) + ); + t.is(afterSetAjv.errors.length, 1); + + const updatedSchema = cloneDeep(schema); + updatedSchema.properties.foo.minLength = 6; + const afterSetSchema: JsonFormsCore = coreReducer( + afterSetAjv, + setSchema(updatedSchema) + ); + t.is(afterSetSchema.errors.length, 1); +}); + +test('core reducer - setAjv - re-enabling validation compiles with the new ajv instance', (t) => { + const schema: JsonSchema = { + type: 'object', + properties: { + foo: { type: 'string', minLength: 5, pattern: '^a' }, + }, + }; + const before: JsonFormsCore = coreReducer( + undefined, + init({ foo: 'b' }, schema, undefined, undefined) + ); + const firstErrorOnlyAjv = createAjv({ allErrors: false }); + const afterSetAjv = coreReducer(before, setAjv(firstErrorOnlyAjv)); + const hidden = coreReducer(afterSetAjv, setValidationMode('NoValidation')); + t.is(hidden.errors.length, 0); + + const shown = coreReducer(hidden, setValidationMode('ValidateAndShow')); + t.is(shown.errors.length, 1); +}); + test('core reducer helpers - getControlPath - converts JSON Pointer notation to dot notation', (t) => { const errorObject = { instancePath: '/group/name' } as ErrorObject; const controlPath = getControlPath(errorObject); From ea98a3cb8cdf71720cbd52ed9d9347ee561a02d7 Mon Sep 17 00:00:00 2001 From: Luigi Bifulco Date: Wed, 7 Oct 2026 19:01:16 +0200 Subject: [PATCH 2/4] feat(core): select combinator branches structurally instead of compiling them with Ajv Combinator tab selection compiled every oneOf/anyOf/allOf branch with Ajv and then ignored all errors except the structural keywords required, additionalProperties, type, enum and const. The new isStructuralMatch evaluates exactly those keywords itself, recursively through properties, patternProperties, items, $ref, nested combinators and if/then/else. Tab selection therefore no longer depends on an Ajv instance or on code generation, so it also works under a Content Security Policy without unsafe-eval. Equivalence with the previous filtered-Ajv behaviour is covered by tests comparing both approaches keyword by keyword. Part of #1498 Co-Authored-By: Claude Fable 5.1 --- packages/core/src/mappers/renderer.ts | 40 +-- packages/core/src/util/index.ts | 1 + packages/core/src/util/structural.ts | 248 +++++++++++++++ packages/core/test/mappers/renderer.test.ts | 166 ++++++++++ packages/core/test/util/structural.test.ts | 331 ++++++++++++++++++++ 5 files changed, 753 insertions(+), 33 deletions(-) create mode 100644 packages/core/src/util/structural.ts create mode 100644 packages/core/test/util/structural.test.ts diff --git a/packages/core/src/mappers/renderer.ts b/packages/core/src/mappers/renderer.ts index d80392c85..08d65ec4b 100644 --- a/packages/core/src/mappers/renderer.ts +++ b/packages/core/src/mappers/renderer.ts @@ -84,6 +84,7 @@ import { getUiSchema, } from '../store'; import { isInherentlyEnabled, isInherentlyReadonly } from './util'; +import { isStructuralMatch } from '../util/structural'; import { CombinatorKeyword } from './combinators'; import isEqual from 'lodash/isEqual'; @@ -1163,41 +1164,14 @@ export const mapStateToCombinatorRendererProps = ( const { data, schema, rootSchema, i18nKeyPrefix, label, ...props } = mapStateToControlProps(state, ownProps); - const ajv = state.jsonforms.core.ajv; - const structuralKeywords = [ - 'required', - 'additionalProperties', - 'type', - 'enum', - 'const', - ]; - const dataIsValid = (errors: ErrorObject[]): boolean => { - return ( - !errors || - errors.length === 0 || - !errors.find((e) => structuralKeywords.indexOf(e.keyword) !== -1) - ); - }; + // Pick the first branch whose structural keywords fit the data. This is a + // pure structural check (see isStructuralMatch): no validator instance and + // no code generation are involved, so it also works under a strict CSP. let indexOfFittingSchema: number; - // TODO instead of compiling the combinator subschemas we can compile the original schema - // without the combinator alternatives and then revalidate and check the errors for the - // element for (let i = 0; i < schema[keyword]?.length; i++) { - try { - let _schema = schema[keyword][i]; - if (_schema.$ref) { - _schema = Resolve.schema(rootSchema, _schema.$ref, rootSchema); - } - const valFn = ajv.compile(_schema); - valFn(data); - if (dataIsValid(valFn.errors)) { - indexOfFittingSchema = i; - break; - } - } catch (error) { - console.debug( - "Combinator subschema is not self contained, can't hand it over to AJV" - ); + if (isStructuralMatch(schema[keyword][i], data, rootSchema)) { + indexOfFittingSchema = i; + break; } } diff --git a/packages/core/src/util/index.ts b/packages/core/src/util/index.ts index 0d4ec3564..0987ee61e 100644 --- a/packages/core/src/util/index.ts +++ b/packages/core/src/util/index.ts @@ -34,6 +34,7 @@ export * from './schema'; export * from './uischema'; export * from './util'; export * from './validator'; +export * from './structural'; export * from './defaultDateFormat'; export * from './errors'; export * from './helpers'; diff --git a/packages/core/src/util/structural.ts b/packages/core/src/util/structural.ts new file mode 100644 index 000000000..e3575f68c --- /dev/null +++ b/packages/core/src/util/structural.ts @@ -0,0 +1,248 @@ +/* + The MIT License + + Copyright (c) 2017-2019 EclipseSource Munich + https://github.com/eclipsesource/jsonforms + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ +import isEqual from 'lodash/isEqual'; +import type { JsonSchema } from '../models'; +import { resolveSchema } from './resolvers'; + +/** + * The JSON Schema keywords the Structural Matcher evaluates. + * Combinator tab selection has always ignored every other keyword. + */ +export const structuralKeywords = [ + 'required', + 'additionalProperties', + 'type', + 'enum', + 'const', +] as const; + +type SchemaLike = JsonSchema & { + nullable?: boolean; + prefixItems?: JsonSchema[]; + if?: JsonSchema; + then?: JsonSchema; + else?: JsonSchema; +}; + +/** Schema/data pairs already being evaluated on the current path. */ +type Visited = ReadonlyArray; + +const isPlainObject = (data: unknown): data is Record => + typeof data === 'object' && data !== null && !Array.isArray(data); + +const matchesType = (type: string, data: unknown): boolean => { + switch (type) { + case 'null': + return data === null; + case 'boolean': + return typeof data === 'boolean'; + case 'string': + return typeof data === 'string'; + case 'number': + return typeof data === 'number'; + case 'integer': + return typeof data === 'number' && Number.isInteger(data); + case 'array': + return Array.isArray(data); + case 'object': + return isPlainObject(data); + default: + // Unknown type names cannot be decided structurally. + return true; + } +}; + +const compilePattern = (pattern: string): RegExp | undefined => { + try { + return new RegExp(pattern, 'u'); + } catch { + return undefined; + } +}; + +/** + * Structural Matcher: decides whether `data` fits `schema` by evaluating only + * the structural keywords `type`, `enum`, `const`, `required` and + * `additionalProperties`, recursively through `properties`, + * `patternProperties`, `items`, `$ref`, nested combinators and + * `if`/`then`/`else`. It needs no validator instance and generates no code, + * so it works under a Content Security Policy without `unsafe-eval`. + * + * Keywords outside that set (`format`, `pattern`, `minimum`, ...) are ignored, + * matching what combinator tab selection has always done. A `$ref` that + * cannot be resolved against `rootSchema` is treated as not matching. + * + * @param schema the schema to match against + * @param data the data to check + * @param rootSchema the root schema used to resolve `$ref`s; defaults to `schema` + * @returns `true` when no structural keyword rejects the data + */ +export const isStructuralMatch = ( + schema: JsonSchema | boolean | undefined, + data: unknown, + rootSchema?: JsonSchema +): boolean => { + const root = rootSchema ?? (typeof schema === 'object' ? schema : {}); + return match(schema, data, root, []); +}; + +const match = ( + schema: JsonSchema | boolean | undefined, + data: unknown, + rootSchema: JsonSchema, + visited: Visited +): boolean => { + if (schema === undefined || schema === null) { + return true; + } + if (typeof schema === 'boolean') { + return schema; + } + if (visited.some(([s, d]) => s === schema && d === data)) { + // The same schema applied to the same data again on this path: a + // recursive schema that cannot be decided any further structurally. + return true; + } + const nextVisited: Visited = [...visited, [schema, data]]; + + if (typeof schema.$ref === 'string') { + const resolved = resolveSchema(rootSchema, schema.$ref, rootSchema); + if (resolved === undefined) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { $ref, ...siblings } = schema; + return ( + match(resolved, data, rootSchema, nextVisited) && + matchKeywords(siblings, data, rootSchema, nextVisited) + ); + } + return matchKeywords(schema, data, rootSchema, nextVisited); +}; + +const matchKeywords = ( + schema: SchemaLike, + data: unknown, + rootSchema: JsonSchema, + visited: Visited +): boolean => { + const sub = (s: JsonSchema | boolean | undefined, d: unknown): boolean => + match(s, d, rootSchema, visited); + + if (schema.nullable === true && data === null) { + return true; + } + if (schema.type !== undefined) { + const types = Array.isArray(schema.type) ? schema.type : [schema.type]; + if (!types.some((type) => matchesType(type, data))) { + return false; + } + } + if ( + Array.isArray(schema.enum) && + !schema.enum.some((value) => isEqual(value, data)) + ) { + return false; + } + if ('const' in schema && !isEqual(schema.const, data)) { + return false; + } + if (Array.isArray(schema.allOf) && !schema.allOf.every((s) => sub(s, data))) { + return false; + } + if (Array.isArray(schema.anyOf) && !schema.anyOf.some((s) => sub(s, data))) { + return false; + } + // When several oneOf branches match, AJV reports only a `oneOf` error, which + // tab selection ignores. "At least one branch" is therefore the structural + // reading of oneOf. + if (Array.isArray(schema.oneOf) && !schema.oneOf.some((s) => sub(s, data))) { + return false; + } + if (schema.if !== undefined) { + const branch = sub(schema.if, data) ? schema.then : schema.else; + if (!sub(branch, data)) { + return false; + } + } + + if (isPlainObject(data)) { + if ( + Array.isArray(schema.required) && + !schema.required.every((key) => data[key] !== undefined) + ) { + return false; + } + const properties = schema.properties ?? {}; + const patterns = Object.entries(schema.patternProperties ?? {}) + .map(([pattern, s]) => ({ regex: compilePattern(pattern), schema: s })) + .filter( + (p): p is { regex: RegExp; schema: JsonSchema } => p.regex !== undefined + ); + for (const [key, value] of Object.entries(data)) { + if (value === undefined) { + continue; + } + const matchingPatterns = patterns.filter((p) => p.regex.test(key)); + const isDeclared = key in properties || matchingPatterns.length > 0; + if (key in properties && !sub(properties[key], value)) { + return false; + } + if (!matchingPatterns.every((p) => sub(p.schema, value))) { + return false; + } + if (!isDeclared && schema.additionalProperties !== undefined) { + if (schema.additionalProperties === false) { + return false; + } + if ( + typeof schema.additionalProperties === 'object' && + !sub(schema.additionalProperties, value) + ) { + return false; + } + } + } + } + + if (Array.isArray(data)) { + const tuple = Array.isArray(schema.prefixItems) + ? schema.prefixItems + : Array.isArray(schema.items) + ? schema.items + : undefined; + if (tuple !== undefined) { + if (!data.every((item, i) => i >= tuple.length || sub(tuple[i], item))) { + return false; + } + } else if ( + typeof schema.items === 'object' && + !data.every((item) => sub(schema.items as JsonSchema, item)) + ) { + return false; + } + } + return true; +}; diff --git a/packages/core/test/mappers/renderer.test.ts b/packages/core/test/mappers/renderer.test.ts index 9d0dd516c..c46626086 100644 --- a/packages/core/test/mappers/renderer.test.ts +++ b/packages/core/test/mappers/renderer.test.ts @@ -1741,6 +1741,172 @@ test('mapStateToAnyOfProps - const constraint in anyOf schema should return corr t.is(props.indexOfFittingSchema, 2); }); +test('mapStateToOneOfProps - indexOfFittingSchema selects the branch whose required properties are present', (t) => { + const uischema: ControlElement = { type: 'Control', scope: '#' }; + const schema: JsonSchema7 = { + oneOf: [ + { + type: 'object', + properties: { iban: { type: 'string' } }, + required: ['iban'], + }, + { + type: 'object', + properties: { cardNumber: { type: 'string' } }, + required: ['cardNumber'], + }, + ], + }; + const state = { + jsonforms: { + core: { + ajv: createAjv(), + schema, + data: { cardNumber: '4111' }, + uischema, + errors: [] as ErrorObject[], + }, + }, + }; + const props = mapStateToOneOfProps(state, { uischema }); + t.is(props.indexOfFittingSchema, 1); +}); + +test('mapStateToOneOfProps - indexOfFittingSchema honours additionalProperties: false', (t) => { + const uischema: ControlElement = { type: 'Control', scope: '#' }; + const schema: JsonSchema7 = { + oneOf: [ + { + type: 'object', + properties: { name: { type: 'string' } }, + additionalProperties: false, + }, + { + type: 'object', + properties: { name: { type: 'string' }, age: { type: 'integer' } }, + }, + ], + }; + const state = { + jsonforms: { + core: { + ajv: createAjv(), + schema, + data: { name: 'Ada', age: 36 }, + uischema, + errors: [] as ErrorObject[], + }, + }, + }; + const props = mapStateToOneOfProps(state, { uischema }); + t.is(props.indexOfFittingSchema, 1); +}); + +test('mapStateToAnyOfProps - indexOfFittingSchema selects by primitive type', (t) => { + const uischema: ControlElement = { type: 'Control', scope: '#' }; + const schema: JsonSchema7 = { + anyOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }], + }; + const state = { + jsonforms: { + core: { + ajv: createAjv(), + schema, + data: true, + uischema, + errors: [] as ErrorObject[], + }, + }, + }; + const props = mapStateToAnyOfProps(state, { uischema }); + t.is(props.indexOfFittingSchema, 2); +}); + +test('mapStateToOneOfProps - indexOfFittingSchema resolves $ref branches against the root schema', (t) => { + const uischema: ControlElement = { + type: 'Control', + scope: '#/properties/pet', + }; + const schema: JsonSchema7 = { + type: 'object', + properties: { + pet: { + oneOf: [{ $ref: '#/definitions/cat' }, { $ref: '#/definitions/dog' }], + }, + }, + definitions: { + cat: { + type: 'object', + properties: { kind: { const: 'cat' } }, + required: ['kind'], + }, + dog: { + type: 'object', + properties: { kind: { const: 'dog' } }, + required: ['kind'], + }, + }, + }; + const state = { + jsonforms: { + core: { + ajv: createAjv(), + schema, + data: { pet: { kind: 'dog' } }, + uischema, + errors: [] as ErrorObject[], + }, + }, + }; + const props = mapStateToOneOfProps(state, { uischema }); + t.is(props.indexOfFittingSchema, 1); +}); + +test('mapStateToOneOfProps - indexOfFittingSchema works without an ajv instance in state', (t) => { + const uischema: ControlElement = { type: 'Control', scope: '#' }; + const schema: JsonSchema7 = { + oneOf: [ + { type: 'object', properties: { kind: { const: 'a' } } }, + { type: 'object', properties: { kind: { const: 'b' } } }, + ], + }; + const state = { + jsonforms: { + core: { + schema, + data: { kind: 'b' }, + uischema, + errors: [] as ErrorObject[], + }, + }, + }; + const props = mapStateToOneOfProps(state, { uischema }); + t.is(props.indexOfFittingSchema, 1); +}); + +test('mapStateToOneOfProps - indexOfFittingSchema is undefined when no branch fits', (t) => { + const uischema: ControlElement = { type: 'Control', scope: '#' }; + const schema: JsonSchema7 = { + oneOf: [ + { type: 'object', properties: { kind: { const: 'a' } } }, + { type: 'object', properties: { kind: { const: 'b' } } }, + ], + }; + const state = { + jsonforms: { + core: { + ajv: createAjv(), + schema, + data: { kind: 'c' }, + uischema, + errors: [] as ErrorObject[], + }, + }, + }; + const props = mapStateToOneOfProps(state, { uischema }); + t.is(props.indexOfFittingSchema, undefined); +}); + test('mapStateToControlProps - i18n - mapStateToControlProps should not crash without i18n', (t) => { const ownProps = { uischema: coreUISchema, diff --git a/packages/core/test/util/structural.test.ts b/packages/core/test/util/structural.test.ts new file mode 100644 index 000000000..9b375d6d1 --- /dev/null +++ b/packages/core/test/util/structural.test.ts @@ -0,0 +1,331 @@ +/* + The MIT License + + Copyright (c) 2017-2019 EclipseSource Munich + https://github.com/eclipsesource/jsonforms + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ +import test from 'ava'; +import type { ErrorObject } from 'ajv'; +import { JsonSchema } from '../../src/models'; +import { + isStructuralMatch, + structuralKeywords, +} from '../../src/util/structural'; +import { createAjv } from '../../src/util/validator'; + +/** + * The behaviour the Structural Matcher replaces: compile the branch with AJV, + * validate, and ignore every error whose keyword is not structural. + */ +const ajvStructuralMatch = (schema: JsonSchema, data: unknown): boolean => { + const validate = createAjv().compile(schema); + validate(data); + const errors: ErrorObject[] = validate.errors ?? []; + return !errors.some((e) => + (structuralKeywords as readonly string[]).includes(e.keyword) + ); +}; + +const cases: Array<{ name: string; schema: JsonSchema; data: unknown }> = [ + { name: 'type string ok', schema: { type: 'string' }, data: 'a' }, + { name: 'type string fail', schema: { type: 'string' }, data: 1 }, + { name: 'type integer ok', schema: { type: 'integer' }, data: 2 }, + { name: 'type integer fail', schema: { type: 'integer' }, data: 2.5 }, + { name: 'type number ok', schema: { type: 'number' }, data: 2.5 }, + { name: 'type null ok', schema: { type: 'null' }, data: null }, + { name: 'type object fail on array', schema: { type: 'object' }, data: [] }, + { name: 'type array ok', schema: { type: 'array' }, data: [] }, + { + name: 'type union ok', + schema: { type: ['string', 'null'] }, + data: null, + }, + { + name: 'type union fail', + schema: { type: ['string', 'null'] }, + data: 1, + }, + { name: 'enum ok', schema: { enum: ['a', 'b'] }, data: 'b' }, + { name: 'enum fail', schema: { enum: ['a', 'b'] }, data: 'c' }, + { + name: 'enum deep equal ok', + schema: { enum: [{ x: 1 }] }, + data: { x: 1 }, + }, + { name: 'const ok', schema: { const: 5 }, data: 5 }, + { name: 'const fail', schema: { const: 5 }, data: 6 }, + { name: 'const null ok', schema: { const: null }, data: null }, + { + name: 'required ok', + schema: { type: 'object', required: ['a'] }, + data: { a: 1 }, + }, + { + name: 'required fail', + schema: { type: 'object', required: ['a'] }, + data: { b: 1 }, + }, + { + name: 'required ignored on non-object', + schema: { required: ['a'] }, + data: 'str', + }, + { + name: 'nested properties type fail', + schema: { + type: 'object', + properties: { + a: { type: 'object', properties: { b: { type: 'string' } } }, + }, + }, + data: { a: { b: 1 } }, + }, + { + name: 'nested properties ok', + schema: { + type: 'object', + properties: { + a: { type: 'object', properties: { b: { type: 'string' } } }, + }, + }, + data: { a: { b: 'x' } }, + }, + { + name: 'additionalProperties false fail', + schema: { + type: 'object', + properties: { a: { type: 'string' } }, + additionalProperties: false, + }, + data: { a: 'x', b: 1 }, + }, + { + name: 'additionalProperties false ok', + schema: { + type: 'object', + properties: { a: { type: 'string' } }, + additionalProperties: false, + }, + data: { a: 'x' }, + }, + { + name: 'additionalProperties schema fail', + schema: { + type: 'object', + properties: { a: { type: 'string' } }, + additionalProperties: { type: 'number' }, + }, + data: { a: 'x', b: 'not a number' }, + }, + { + name: 'additionalProperties with patternProperties ok', + schema: { + type: 'object', + patternProperties: { '^x-': { type: 'string' } }, + additionalProperties: false, + }, + data: { 'x-a': 'ok' }, + }, + { + name: 'patternProperties type fail', + schema: { + type: 'object', + patternProperties: { '^x-': { type: 'string' } }, + }, + data: { 'x-a': 1 }, + }, + { + name: 'items type fail', + schema: { type: 'array', items: { type: 'string' } }, + data: ['a', 1], + }, + { + name: 'items type ok', + schema: { type: 'array', items: { type: 'string' } }, + data: ['a', 'b'], + }, + { + name: 'tuple items fail', + schema: { type: 'array', items: [{ type: 'string' }, { type: 'number' }] }, + data: ['a', 'b'], + }, + { + name: 'nested anyOf ok', + schema: { + type: 'object', + properties: { v: { anyOf: [{ type: 'string' }, { type: 'number' }] } }, + }, + data: { v: 1 }, + }, + { + name: 'nested anyOf fail', + schema: { + type: 'object', + properties: { v: { anyOf: [{ type: 'string' }, { type: 'number' }] } }, + }, + data: { v: true }, + }, + { + name: 'nested allOf fail', + schema: { allOf: [{ type: 'object' }, { required: ['a'] }] }, + data: { b: 1 }, + }, + { + name: 'nested oneOf none fail', + schema: { oneOf: [{ const: 'a' }, { const: 'b' }] }, + data: 'c', + }, + { + name: 'nested oneOf several match is structurally fine', + schema: { oneOf: [{ type: 'string' }, { const: 'a' }] }, + data: 'a', + }, + { + name: 'not is ignored like AJV filtering does', + schema: { not: { type: 'string' } }, + data: 'a', + }, + { + name: 'non-structural keywords are ignored (pattern, minLength, format)', + schema: { + type: 'string', + pattern: '^a', + minLength: 10, + format: 'email', + }, + data: 'b', + }, + { + name: 'if then else uses then branch', + schema: { + type: 'object', + if: { properties: { kind: { const: 'a' } } }, + then: { required: ['aValue'] }, + else: { required: ['bValue'] }, + }, + data: { kind: 'a', bValue: 1 }, + }, + { + name: 'if then else uses else branch', + schema: { + type: 'object', + if: { properties: { kind: { const: 'a' } } }, + then: { required: ['aValue'] }, + else: { required: ['bValue'] }, + }, + data: { kind: 'b', bValue: 1 }, + }, + { + name: '$ref resolved against root', + schema: { + type: 'object', + properties: { pet: { $ref: '#/definitions/cat' } }, + definitions: { + cat: { type: 'object', required: ['meow'] }, + }, + }, + data: { pet: { bark: true } }, + }, + { + name: 'nullable with type allows null', + schema: { type: 'string', nullable: true } as JsonSchema, + data: null, + }, +]; + +for (const c of cases) { + test(`isStructuralMatch agrees with filtered AJV: ${c.name}`, (t) => { + t.is( + isStructuralMatch(c.schema, c.data), + ajvStructuralMatch(c.schema, c.data) + ); + }); +} + +test('isStructuralMatch - boolean schemas', (t) => { + t.true(isStructuralMatch(true, 'anything')); + t.false(isStructuralMatch(false, 'anything')); + t.true(isStructuralMatch(undefined, 'anything')); +}); + +test('isStructuralMatch - unresolvable $ref does not match', (t) => { + const root: JsonSchema = { definitions: {} }; + t.false(isStructuralMatch({ $ref: '#/definitions/missing' }, {}, root)); +}); + +test('isStructuralMatch - $ref branch resolved via explicit root schema', (t) => { + const root: JsonSchema = { + definitions: { + dog: { + type: 'object', + properties: { kind: { const: 'dog' } }, + required: ['kind'], + }, + }, + }; + t.true( + isStructuralMatch({ $ref: '#/definitions/dog' }, { kind: 'dog' }, root) + ); + t.false( + isStructuralMatch({ $ref: '#/definitions/dog' }, { kind: 'cat' }, root) + ); +}); + +test('isStructuralMatch - recursive schema terminates', (t) => { + const root: JsonSchema = { + definitions: { + node: { + type: 'object', + properties: { + children: { type: 'array', items: { $ref: '#/definitions/node' } }, + }, + }, + }, + }; + const data: unknown = { children: [{ children: [{ children: [] }] }] }; + t.true(isStructuralMatch({ $ref: '#/definitions/node' }, data, root)); + t.false( + isStructuralMatch( + { $ref: '#/definitions/node' }, + { children: [{ children: 'not an array' }] }, + root + ) + ); +}); + +test('isStructuralMatch - invalid patternProperties regex is ignored', (t) => { + const schema: JsonSchema = { + type: 'object', + patternProperties: { '(': { type: 'string' } }, + }; + t.true(isStructuralMatch(schema, { a: 1 })); +}); + +test('isStructuralMatch - undefined property values do not count as present', (t) => { + const schema: JsonSchema = { + type: 'object', + required: ['a'], + properties: { a: { type: 'string' } }, + additionalProperties: false, + }; + t.false(isStructuralMatch(schema, { a: undefined })); + t.true(isStructuralMatch(schema, { a: 'x', b: undefined })); +}); From bb5d28c015eededdaf99d6ffa815b679bbfa1251 Mon Sep 17 00:00:00 2001 From: Luigi Bifulco Date: Wed, 7 Oct 2026 19:10:18 +0200 Subject: [PATCH 3/4] feat(core): add a pluggable Form Validator next to Ajv Adds the validation seam from issue #1498 as a non-breaking addition: the `validator` init/updateCore option takes a FormValidatorFactory `(schema) => FormValidator` or a FormValidator already bound to the schema. The types mirror the FormValidator / ValidationIssue of the 4.x presentation-model branch, restricted to synchronous results. - The core reducer creates the Form Validator through the factory whenever the schema changes and caches it in `state.formValidator`; `state.validator` keeps holding the compiled Ajv function when Ajv validates, so existing consumers are unaffected. - Issues from custom validators are converted to the Ajv error shape the rest of core and the renderers read (`issuesToErrors`): missing `key` becomes `custom`, `required` issues addressed to the missing property are split into parent path plus `params.missingProperty`, non-error severities are dropped and a missing `parentSchema` is resolved from the form schema. - `createAjvValidator(ajv?)` is the built-in adapter; `compiledAjvValidator(validateFn)` wraps Ajv standalone code for CSP setups without unsafe-eval. - `getValidator(state)` exposes the bound Form Validator. - Switching to NoValidation via setValidationMode now also drops the cached validator, as init and updateCore already did. Precedence: `validator` wins, otherwise `ajv`, otherwise the default Ajv instance. Existing users notice nothing. Part of #1498 Co-Authored-By: Claude Fable 5.1 --- packages/core/src/actions/actions.ts | 9 + packages/core/src/reducers/core.ts | 193 ++++++++--- packages/core/src/store/jsonFormsCore.ts | 8 + packages/core/src/store/store.ts | 10 + packages/core/src/util/formValidator.ts | 300 ++++++++++++++++++ packages/core/src/util/index.ts | 1 + packages/core/test/reducers/core.test.ts | 246 +++++++++++++- packages/core/test/util/formValidator.test.ts | 223 +++++++++++++ 8 files changed, 953 insertions(+), 37 deletions(-) create mode 100644 packages/core/src/util/formValidator.ts create mode 100644 packages/core/test/util/formValidator.test.ts diff --git a/packages/core/src/actions/actions.ts b/packages/core/src/actions/actions.ts index c02aece59..1ff517f38 100644 --- a/packages/core/src/actions/actions.ts +++ b/packages/core/src/actions/actions.ts @@ -25,6 +25,7 @@ import type AJV from 'ajv'; import type { ErrorObject } from 'ajv'; +import type { ValidatorOption } from '../util/formValidator'; import { JsonSchema, UISchemaElement } from '../models'; import { generateDefaultUISchema, generateJsonSchema } from '../generators'; @@ -145,7 +146,15 @@ export interface UpdateCoreAction { } export interface InitActionOptions { + /** The AJV instance to validate with. Ignored for form validation when `validator` is set. */ ajv?: AJV; + /** + * A custom Form Validator: a factory producing one per schema, or a + * validator already bound to the schema. Takes precedence over `ajv`. + * Passing `undefined` explicitly switches back to AJV; leaving the key out + * keeps the validator currently in use. + */ + validator?: ValidatorOption; validationMode?: ValidationMode; additionalErrors?: ErrorObject[]; } diff --git a/packages/core/src/reducers/core.ts b/packages/core/src/reducers/core.ts index 940c9d3f1..0f2181f3b 100644 --- a/packages/core/src/reducers/core.ts +++ b/packages/core/src/reducers/core.ts @@ -42,10 +42,20 @@ import { UpdateCoreAction, } from '../actions'; import { JsonFormsCore, Reducer, ValidationMode } from '../store'; +import type { JsonSchema } from '../models'; import type Ajv from 'ajv'; import type { ErrorObject } from 'ajv'; import isFunction from 'lodash/isFunction'; -import { createAjv, validate } from '../util'; +import { createAjv, validate } from '../util/validator'; +import { + compiledAjvValidator, + createAjvValidator, + FormValidator, + isAjvFormValidator, + issuesToErrors, + toFormValidatorFactory, + ValidatorOption, +} from '../util/formValidator'; export const initState: JsonFormsCore = { data: {}, @@ -56,6 +66,8 @@ export const initState: JsonFormsCore = { ajv: undefined, validationMode: 'ValidateAndShow', additionalErrors: [], + formValidator: undefined, + validatorOption: undefined, }; export const getValidationMode = ( @@ -119,6 +131,75 @@ const hasAjvOption = (option: any): option is InitActionOptions => { return false; }; +const hasValidatorOption = (option: any): option is InitActionOptions => + !!option && !isFunction(option.compile) && 'validator' in option; + +/** + * The custom `validator` option in effect for an action: the one given in the + * action's options (an explicit `validator: undefined` switches back to AJV), + * or the one already stored in state when the options do not mention a + * validator at all. Returns `undefined` when AJV performs the validation. + */ +export const getValidatorOption = ( + state: JsonFormsCore, + action?: InitAction | UpdateCoreAction +): ValidatorOption | undefined => { + if (action && hasValidatorOption(action.options)) { + return action.options.validator; + } + return state.validatorOption; +}; + +/** + * Creates the Form Validator for `schema`: through the custom option when one + * is configured, otherwise through the built-in AJV adapter. + */ +const createFormValidator = ( + option: ValidatorOption | undefined, + ajv: Ajv | undefined, + schema: JsonSchema, + validationMode: ValidationMode +): FormValidator | undefined => { + if (validationMode === 'NoValidation') { + return undefined; + } + const factory = + option === undefined + ? createAjvValidator(ajv) + : toFormValidatorFactory(option); + return factory(schema); +}; + +/** + * The Form Validator to validate with: the cached one, or, for states that + * only carry a compiled AJV function (e.g. constructed by hand), that + * function wrapped as a Form Validator. + */ +const currentFormValidator = ( + state: JsonFormsCore +): FormValidator | undefined => + state.formValidator ?? + (state.validator ? compiledAjvValidator(state.validator) : undefined); + +const runValidation = ( + formValidator: FormValidator | undefined, + data: any, + schema: JsonSchema +): ErrorObject[] => { + if (formValidator === undefined) { + return []; + } + if (isAjvFormValidator(formValidator)) { + // AJV errors already have the stored shape; hand them over untouched. + return validate(formValidator.validateFn, data); + } + return issuesToErrors(formValidator.validate(data), schema); +}; + +/** The compiled AJV function behind a Form Validator, for `state.validator`. */ +const legacyValidateFn = (formValidator: FormValidator | undefined) => + isAjvFormValidator(formValidator) ? formValidator.validateFn : undefined; + export const coreReducer: Reducer = ( state = initState, action @@ -126,13 +207,15 @@ export const coreReducer: Reducer = ( switch (action.type) { case INIT: { const thisAjv = getOrCreateAjv(state, action); - + const validatorOption = getValidatorOption(state, action); const validationMode = getValidationMode(state, action); - const v = - validationMode === 'NoValidation' - ? undefined - : thisAjv.compile(action.schema); - const e = validate(v, action.data); + const formValidator = createFormValidator( + validatorOption, + thisAjv, + action.schema, + validationMode + ); + const e = runValidation(formValidator, action.data, action.schema); const additionalErrors = getAdditionalErrors(state, action); return { @@ -142,30 +225,37 @@ export const coreReducer: Reducer = ( uischema: action.uischema, additionalErrors, errors: e, - validator: v, + validator: legacyValidateFn(formValidator), + formValidator, + validatorOption, ajv: thisAjv, validationMode, }; } case UPDATE_CORE: { const thisAjv = getOrCreateAjv(state, action); + const validatorOption = getValidatorOption(state, action); const validationMode = getValidationMode(state, action); - let validator = state.validator; + let formValidator = currentFormValidator(state); let errors = state.errors; if ( state.schema !== action.schema || state.validationMode !== validationMode || - state.ajv !== thisAjv + state.ajv !== thisAjv || + state.validatorOption !== validatorOption ) { // revalidate only if necessary - validator = - validationMode === 'NoValidation' - ? undefined - : thisAjv.compile(action.schema); - errors = validate(validator, action.data); + formValidator = createFormValidator( + validatorOption, + thisAjv, + action.schema, + validationMode + ); + errors = runValidation(formValidator, action.data, action.schema); } else if (state.data !== action.data) { - errors = validate(validator, action.data); + errors = runValidation(formValidator, action.data, action.schema); } + const validator = legacyValidateFn(formValidator); const additionalErrors = getAdditionalErrors(state, action); const stateChanged = @@ -175,6 +265,8 @@ export const coreReducer: Reducer = ( state.ajv !== thisAjv || state.errors !== errors || state.validator !== validator || + state.formValidator !== formValidator || + state.validatorOption !== validatorOption || state.validationMode !== validationMode || state.additionalErrors !== additionalErrors; return stateChanged @@ -185,7 +277,9 @@ export const coreReducer: Reducer = ( uischema: action.uischema, ajv: thisAjv, errors: isEqual(errors, state.errors) ? state.errors : errors, - validator: validator, + validator, + formValidator, + validatorOption, validationMode: validationMode, additionalErrors, } @@ -193,27 +287,39 @@ export const coreReducer: Reducer = ( } case SET_AJV: { const currentAjv = action.ajv; - const validator = - state.validationMode === 'NoValidation' - ? undefined - : currentAjv.compile(state.schema); - const errors = validate(validator, state.data); + const formValidator = createFormValidator( + state.validatorOption, + currentAjv, + state.schema, + state.validationMode + ); + const errors = runValidation(formValidator, state.data, state.schema); return { ...state, - validator, + ajv: currentAjv, + validator: legacyValidateFn(formValidator), + formValidator, errors, }; } case SET_SCHEMA: { const needsNewValidator = - action.schema && state.ajv && state.validationMode !== 'NoValidation'; - const v = needsNewValidator - ? state.ajv.compile(action.schema) - : state.validator; - const errors = validate(v, state.data); + action.schema && + (state.ajv || state.validatorOption) && + state.validationMode !== 'NoValidation'; + const formValidator = needsNewValidator + ? createFormValidator( + state.validatorOption, + state.ajv, + action.schema, + state.validationMode + ) + : currentFormValidator(state); + const errors = runValidation(formValidator, state.data, action.schema); return { ...state, - validator: v, + validator: legacyValidateFn(formValidator), + formValidator, schema: action.schema, errors, }; @@ -230,7 +336,11 @@ export const coreReducer: Reducer = ( } else if (action.path === '') { // empty path is ok const result = action.updater(cloneDeep(state.data)); - const errors = validate(state.validator, result); + const errors = runValidation( + currentFormValidator(state), + result, + state.schema + ); return { ...state, data: result, @@ -253,7 +363,11 @@ export const coreReducer: Reducer = ( action.path ); } - const errors = validate(state.validator, newState); + const errors = runValidation( + currentFormValidator(state), + newState, + state.schema + ); return { ...state, data: newState, @@ -272,19 +386,26 @@ export const coreReducer: Reducer = ( return state; } if (action.validationMode === 'NoValidation') { - const errors = validate(undefined, state.data); return { ...state, - errors, + errors: [], + validator: undefined, + formValidator: undefined, validationMode: action.validationMode, }; } if (state.validationMode === 'NoValidation') { - const validator = state.ajv.compile(state.schema); - const errors = validate(validator, state.data); + const formValidator = createFormValidator( + state.validatorOption, + state.ajv, + state.schema, + action.validationMode + ); + const errors = runValidation(formValidator, state.data, state.schema); return { ...state, - validator, + validator: legacyValidateFn(formValidator), + formValidator, errors, validationMode: action.validationMode, }; diff --git a/packages/core/src/store/jsonFormsCore.ts b/packages/core/src/store/jsonFormsCore.ts index 596f76c92..ba88ac6b2 100644 --- a/packages/core/src/store/jsonFormsCore.ts +++ b/packages/core/src/store/jsonFormsCore.ts @@ -3,6 +3,7 @@ import type { ErrorObject } from 'ajv'; import { JsonSchema, UISchemaElement } from '../models'; import get from 'lodash/get'; import { errorsAt } from '../util'; +import type { FormValidator } from '../util/formValidator'; import { JsonFormsCellRendererRegistryEntry, JsonFormsCore, @@ -55,6 +56,10 @@ export const getUiSchema = (state: JsonFormsState): UISchemaElement => extractUiSchema(get(state, 'jsonforms.core')); export const getAjv = (state: JsonFormsState): Ajv => extractAjv(get(state, 'jsonforms.core')); +/** The Form Validator currently bound to the form schema, if validation is on. */ +export const getValidator = ( + state: JsonFormsState +): FormValidator | undefined => extractValidator(get(state, 'jsonforms.core')); export const getRenderers = ( state: JsonFormsState ): JsonFormsRendererRegistryEntry[] => get(state, 'jsonforms.renderers'); @@ -69,5 +74,8 @@ export const extractData = (state: JsonFormsCore) => get(state, 'data'); export const extractSchema = (state: JsonFormsCore) => get(state, 'schema'); export const extractUiSchema = (state: JsonFormsCore) => get(state, 'uischema'); export const extractAjv = (state: JsonFormsCore) => get(state, 'ajv'); +export const extractValidator = ( + state: JsonFormsCore +): FormValidator | undefined => get(state, 'formValidator'); export const getConfig = (state: JsonFormsState) => state.jsonforms.config; diff --git a/packages/core/src/store/store.ts b/packages/core/src/store/store.ts index 7415b69de..b5d136191 100644 --- a/packages/core/src/store/store.ts +++ b/packages/core/src/store/store.ts @@ -28,6 +28,7 @@ import { RankedTester, UISchemaTester } from '../testers'; import { JsonSchema, UISchemaElement } from '../models'; import type Ajv from 'ajv'; import type { ErrorObject, ValidateFunction } from 'ajv'; +import type { FormValidator, ValidatorOption } from '../util/formValidator'; import { JsonFormsI18nState } from './i18nTypes'; /** @@ -89,9 +90,18 @@ export interface JsonFormsCore { uischema: UISchemaElement; errors?: ErrorObject[]; additionalErrors?: ErrorObject[]; + /** + * The compiled AJV validate function behind the current Form Validator. + * Only set while AJV performs the validation; kept for backwards + * compatibility, prefer `formValidator`. + */ validator?: ValidateFunction; ajv?: Ajv; validationMode?: ValidationMode; + /** The Form Validator bound to `schema`. Not consulted while validation is off. */ + formValidator?: FormValidator; + /** The `validator` option in effect when a custom Form Validator is configured. */ + validatorOption?: ValidatorOption; } export interface JsonFormsRendererRegistryEntry { diff --git a/packages/core/src/util/formValidator.ts b/packages/core/src/util/formValidator.ts new file mode 100644 index 000000000..b9cb37039 --- /dev/null +++ b/packages/core/src/util/formValidator.ts @@ -0,0 +1,300 @@ +/* + The MIT License + + Copyright (c) 2017-2019 EclipseSource Munich + https://github.com/eclipsesource/jsonforms + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ +import type Ajv from 'ajv'; +import type { ErrorObject, ValidateFunction } from 'ajv'; +import type { JsonSchema } from '../models'; +import { createAjv } from './validator'; +import { resolveSchema } from './resolvers'; +import { decode } from './path'; + +/** + * One finding reported by a {@link FormValidator}, addressed to a data + * location by JSON Pointer. + * + * The required fields mirror the `ValidationIssue` of JSON Forms 4.x so a + * Form Validator written for either version works with both. The optional + * `params` and `parentSchema` carry the extra information JSON Forms 3.x + * uses for error placement and translation; core fills them in as far as it + * can when an adapter leaves them out. + */ +export interface ValidationIssue { + /** JSON Pointer of the value this issue belongs to, e.g. `/address/street`. */ + path: string; + /** + * Stable key identifying the kind of issue, usually the JSON Schema keyword + * (`required`, `minLength`, ...). It drives the `error.` translation + * lookups. Defaults to `custom` when left out. + */ + key?: string; + /** Human readable message, used when no translation is registered. */ + message: string; + /** + * JSON Forms 3.x stores errors only; issues with any other severity are + * dropped. + */ + severity?: 'error'; + /** + * Keyword parameters in AJV's shape, e.g. `{ missingProperty: 'name' }` for + * `required` or `{ additionalProperty: 'x' }` for `additionalProperties`. + */ + params?: Record; + /** + * The schema the issue was raised against. Resolved from the form schema by + * `path` when left out. + */ + parentSchema?: JsonSchema; +} + +/** + * Validates form data against one schema. This is the pluggable seam between + * JSON Forms and a validation library; AJV is the built-in implementation, + * see {@link createAjvValidator}. + * + * The shape mirrors the `FormValidator` of JSON Forms 4.x, restricted to + * synchronous results. Asynchronous validation stays with middleware and + * `updateErrors`. + */ +export interface FormValidator { + /** Validates `data` and returns every issue found, or an empty array. */ + validate: (data: unknown) => readonly ValidationIssue[]; + /** + * Optional fast path for rule conditions: whether `data` satisfies the + * (usually small) `schema`. When absent, core creates a Form Validator for + * the condition schema through the factory instead. + */ + matches?: (schema: JsonSchema, data: unknown) => boolean; +} + +/** + * Produces the {@link FormValidator} for one schema. Core calls it whenever + * the form schema changes and caches the result in its state. + */ +export type FormValidatorFactory = (schema: JsonSchema) => FormValidator; + +/** + * What adopters pass as the `validator` option: a {@link FormValidatorFactory}, + * or a {@link FormValidator} already bound to the form schema. A bound + * validator is reused for every schema, so the adopter owns swapping it when + * the schema changes. + */ +export type ValidatorOption = FormValidatorFactory | FormValidator; + +/** Whether `candidate` is a {@link FormValidator} object. */ +export const isFormValidator = ( + candidate: unknown +): candidate is FormValidator => + typeof candidate === 'object' && + candidate !== null && + typeof (candidate as FormValidator).validate === 'function'; + +/** Whether `candidate` is a {@link FormValidatorFactory}. */ +export const isFormValidatorFactory = ( + candidate: unknown +): candidate is FormValidatorFactory => typeof candidate === 'function'; + +/** Normalizes a {@link ValidatorOption} to a factory. */ +export const toFormValidatorFactory = ( + option: ValidatorOption +): FormValidatorFactory => + isFormValidatorFactory(option) ? option : () => option; + +/** + * Issue produced by the built-in AJV adapter. It carries every field of the + * original AJV error so that converting it back with {@link issuesToErrors} + * loses nothing. + */ +export interface AjvValidationIssue extends ValidationIssue { + schemaPath: string; + schema?: unknown; + data?: unknown; + propertyName?: string; +} + +/** Maps AJV errors to {@link AjvValidationIssue}s. */ +export const ajvErrorsToIssues = ( + errors: readonly ErrorObject[] | null | undefined +): AjvValidationIssue[] => + (errors ?? []).map((error) => { + const { instancePath, keyword, message, params, parentSchema, ...rest } = + error; + return { + ...rest, + path: instancePath, + key: keyword, + message: message ?? '', + severity: 'error', + params, + parentSchema: parentSchema as JsonSchema | undefined, + }; + }); + +/** A {@link FormValidator} backed by an AJV compiled validate function. */ +export interface AjvFormValidator extends FormValidator { + /** The compiled AJV validate function this Form Validator wraps. */ + readonly validateFn: ValidateFunction; +} + +/** Whether `validator` is an {@link AjvFormValidator}. */ +export const isAjvFormValidator = ( + validator: FormValidator | undefined +): validator is AjvFormValidator => + validator !== undefined && + typeof (validator as AjvFormValidator).validateFn === 'function'; + +/** + * Wraps an already compiled AJV validate function as a {@link FormValidator}, + * for example one generated ahead of time with AJV's standalone code + * generation for Content Security Policy setups without `unsafe-eval`. + * No AJV instance is involved at runtime. + * + * Standalone code generated without the `verbose` option carries no + * `parentSchema`; core then resolves it from the form schema. + */ +export const compiledAjvValidator = ( + validateFn: ValidateFunction, + matches?: FormValidator['matches'] +): AjvFormValidator => ({ + validateFn, + matches, + validate: (data) => { + validateFn(data); + return ajvErrorsToIssues(validateFn.errors); + }, +}); + +/** + * The built-in adapter: a {@link FormValidatorFactory} that compiles each + * schema with the given AJV instance, or with {@link createAjv} when none is + * given. This is what core uses when no `validator` option is configured. + */ +export const createAjvValidator = ( + ajv: Ajv = createAjv() +): FormValidatorFactory => { + const matches = (schema: JsonSchema, data: unknown): boolean => + ajv.validate(schema, data) as boolean; + return (schema) => compiledAjvValidator(ajv.compile(schema), matches); +}; + +const decodePointer = (pointer: string): string[] => + pointer === '' ? [] : pointer.split('/').slice(1).map(decode); + +const dereference = ( + schema: JsonSchema | undefined, + rootSchema: JsonSchema +): JsonSchema | undefined => + schema !== undefined && typeof schema.$ref === 'string' + ? resolveSchema(rootSchema, schema.$ref, rootSchema) + : schema; + +/** + * Best-effort lookup of the schema that describes the value at + * `instancePath`, walking `properties`, `items` and `additionalProperties` + * and following `$ref`s. Returns `undefined` when the path cannot be + * followed. + */ +export const resolveParentSchema = ( + rootSchema: JsonSchema | undefined, + instancePath: string +): JsonSchema | undefined => { + if (rootSchema === undefined) { + return undefined; + } + let current = dereference(rootSchema, rootSchema); + for (const segment of decodePointer(instancePath)) { + if (current === undefined) { + return undefined; + } + let next: JsonSchema | undefined; + if (current.properties && segment in current.properties) { + next = current.properties[segment]; + } else if (/^\d+$/.test(segment) && current.items !== undefined) { + next = Array.isArray(current.items) + ? current.items[Number(segment)] + : current.items; + } else if (typeof current.additionalProperties === 'object') { + next = current.additionalProperties; + } + current = dereference(next, rootSchema); + } + return current; +}; + +/** + * Converts {@link ValidationIssue}s to the AJV-shaped error objects JSON + * Forms 3.x stores in its state and hands to renderers, so that error + * placement, translation and every existing consumer keep working with any + * Form Validator. + * + * Normalization: issues whose severity is not `error` are dropped; a missing + * `key` becomes `custom`; a `required` issue addressed to the missing property + * itself is split into the parent's `instancePath` plus + * `params.missingProperty`; a missing `parentSchema` is resolved from + * `rootSchema` by path. Fields beyond the issue type (e.g. AJV's + * `schemaPath`) are passed through untouched. + * + * @param issues the issues reported by a Form Validator + * @param rootSchema the form schema, used to resolve a missing `parentSchema` + */ +export const issuesToErrors = ( + issues: readonly ValidationIssue[] | null | undefined, + rootSchema?: JsonSchema +): ErrorObject[] => + (issues ?? []) + .filter( + (issue) => issue.severity === undefined || issue.severity === 'error' + ) + .map((issue) => { + const { + path, + key, + severity: _severity, + message, + params, + parentSchema, + ...rest + } = issue as ValidationIssue & Record; + let instancePath = path ?? ''; + const keyword = key ?? 'custom'; + const errorParams: Record = { ...(params ?? {}) }; + if ( + keyword === 'required' && + errorParams.missingProperty === undefined && + instancePath.length > 0 + ) { + const cut = instancePath.lastIndexOf('/'); + errorParams.missingProperty = decode(instancePath.slice(cut + 1)); + instancePath = instancePath.slice(0, cut); + } + return { + schemaPath: '', + ...rest, + instancePath, + keyword, + params: errorParams, + message, + parentSchema: + parentSchema ?? resolveParentSchema(rootSchema, instancePath), + } as ErrorObject; + }); diff --git a/packages/core/src/util/index.ts b/packages/core/src/util/index.ts index 0d4ec3564..beab6700b 100644 --- a/packages/core/src/util/index.ts +++ b/packages/core/src/util/index.ts @@ -34,6 +34,7 @@ export * from './schema'; export * from './uischema'; export * from './util'; export * from './validator'; +export * from './formValidator'; export * from './defaultDateFormat'; export * from './errors'; export * from './helpers'; diff --git a/packages/core/test/reducers/core.test.ts b/packages/core/test/reducers/core.test.ts index 1df87b84b..35b54cfa1 100644 --- a/packages/core/test/reducers/core.test.ts +++ b/packages/core/test/reducers/core.test.ts @@ -27,6 +27,7 @@ import Ajv, { ErrorObject } from 'ajv'; import { coreReducer } from '../../src/reducers'; import { init, + setAjv, setSchema, setValidationMode, update, @@ -37,7 +38,13 @@ import { JsonSchema } from '../../src/models/jsonSchema'; import { cloneDeep } from 'lodash'; import { createAjv, validate } from '../../src/util/validator'; -import { JsonFormsCore, errorAt, subErrorsAt } from '../../src/store'; +import { + JsonFormsCore, + errorAt, + getValidator, + subErrorsAt, +} from '../../src/store'; +import type { FormValidator } from '../../src/util/formValidator'; import { getControlPath } from '../../src/util'; test('core reducer should support v7', (t) => { @@ -2147,6 +2154,243 @@ test('core reducer - setSchema - schema with id', (t) => { t.is(after.schema.properties.animal.minLength, 5); }); +const fakeValidator = (badValue = 'bad') => { + const calls = { compile: [] as JsonSchema[], validate: [] as unknown[] }; + const factory = (schema: JsonSchema) => { + calls.compile.push(schema); + return { + validate: (data: unknown) => { + calls.validate.push(data); + const value = (data as { foo?: string } | undefined)?.foo; + return value === badValue + ? [{ path: '/foo', key: 'const', message: 'must be good' }] + : []; + }, + }; + }; + return { factory, calls }; +}; + +const fooSchema: JsonSchema = { + type: 'object', + properties: { foo: { type: 'string' } }, +}; + +const explodingAjv = { + compile: () => { + throw new Error('AJV must not compile when a validator is given'); + }, +} as unknown as Ajv; + +test('core reducer - validator option - factory is called with the schema and validates the data', (t) => { + const { factory, calls } = fakeValidator(); + const after = coreReducer( + undefined, + init({ foo: 'bad' }, fooSchema, undefined, { + ajv: explodingAjv, + validator: factory, + }) + ); + t.deepEqual(calls.compile, [fooSchema]); + t.deepEqual(calls.validate, [{ foo: 'bad' }]); + t.is(after.errors.length, 1); + t.is(after.errors[0].instancePath, '/foo'); + t.is(after.errors[0].keyword, 'const'); + t.is(after.errors[0].message, 'must be good'); + t.deepEqual(after.errors[0].parentSchema, fooSchema.properties.foo); + t.is(after.validator, undefined); + t.truthy(after.formValidator); + t.is(after.validatorOption, factory); + t.is(after.ajv, explodingAjv); +}); + +test('core reducer - validator option - a bound FormValidator object is accepted', (t) => { + const bound = { + validate: () => [ + { + path: '', + key: 'required', + message: 'is required', + params: { missingProperty: 'foo' }, + }, + ], + }; + const after = coreReducer( + undefined, + init({}, fooSchema, undefined, { validator: bound }) + ); + t.is(after.formValidator, bound); + t.is(after.errors.length, 1); + t.deepEqual(after.errors[0].params, { missingProperty: 'foo' }); + t.deepEqual(after.errors[0].parentSchema, fooSchema); +}); + +test('core reducer - validator option - updateCore recompiles only when the schema changes', (t) => { + const { factory, calls } = fakeValidator(); + const before = coreReducer( + undefined, + init({ foo: 'ok' }, fooSchema, undefined, { validator: factory }) + ); + t.is(calls.compile.length, 1); + + const sameSchema = coreReducer( + before, + updateCore({ foo: 'bad' }, fooSchema, undefined, { validator: factory }) + ); + t.is(calls.compile.length, 1); + t.is(calls.validate.length, 2); + t.is(sameSchema.errors.length, 1); + + const newSchema = cloneDeep(fooSchema); + const after = coreReducer( + sameSchema, + updateCore({ foo: 'bad' }, newSchema, undefined, { validator: factory }) + ); + t.is(calls.compile.length, 2); + t.is(calls.compile[1], newSchema); + t.is(after.errors.length, 1); +}); + +test('core reducer - validator option - options without a validator key keep the current validator', (t) => { + const { factory, calls } = fakeValidator(); + const before = coreReducer( + undefined, + init({ foo: 'ok' }, fooSchema, undefined, { validator: factory }) + ); + const after = coreReducer( + before, + updateCore({ foo: 'bad' }, fooSchema, undefined, { + validationMode: 'ValidateAndShow', + }) + ); + t.is(after.validatorOption, factory); + t.is(calls.validate.length, 2); + t.is(after.errors.length, 1); +}); + +test('core reducer - validator option - an explicit undefined validator switches back to AJV', (t) => { + const { factory } = fakeValidator(); + const schema: JsonSchema = { + type: 'object', + properties: { foo: { type: 'string', const: 'bar' } }, + }; + const before = coreReducer( + undefined, + init({ foo: 'baz' }, schema, undefined, { validator: factory }) + ); + t.is(before.errors.length, 0); + const after = coreReducer( + before, + updateCore({ foo: 'baz' }, schema, undefined, { validator: undefined }) + ); + t.is(after.validatorOption, undefined); + t.is(after.errors.length, 1); + t.is(after.errors[0].keyword, 'const'); + t.truthy(after.validator); +}); + +test('core reducer - validator option - update revalidates through the validator', (t) => { + const { factory, calls } = fakeValidator(); + const before = coreReducer( + undefined, + init({ foo: 'ok' }, fooSchema, undefined, { validator: factory }) + ); + const after = coreReducer( + before, + update('foo', () => 'bad') + ); + t.is(calls.compile.length, 1); + t.is(calls.validate.length, 2); + t.is(after.errors.length, 1); +}); + +test('core reducer - validator option - setSchema compiles the new schema through the validator', (t) => { + const { factory, calls } = fakeValidator(); + const before = coreReducer( + undefined, + init({ foo: 'ok' }, fooSchema, undefined, { validator: factory }) + ); + const newSchema = cloneDeep(fooSchema); + const after = coreReducer(before, setSchema(newSchema)); + t.is(calls.compile.length, 2); + t.is(calls.compile[1], newSchema); + t.is(after.schema, newSchema); +}); + +test('core reducer - validator option - NoValidation skips the validator and re-enabling recompiles', (t) => { + const { factory, calls } = fakeValidator(); + const before = coreReducer( + undefined, + init({ foo: 'bad' }, fooSchema, undefined, { validator: factory }) + ); + t.is(before.errors.length, 1); + const hidden = coreReducer(before, setValidationMode('NoValidation')); + t.is(hidden.errors.length, 0); + t.is(hidden.formValidator, undefined); + t.is(hidden.validator, undefined); + const validateCalls = calls.validate.length; + const updated = coreReducer( + hidden, + update('foo', () => 'still bad') + ); + t.is(calls.validate.length, validateCalls); + t.is(updated.errors.length, 0); + const shown = coreReducer(updated, setValidationMode('ValidateAndShow')); + t.is(calls.compile.length, 2); + t.is(shown.errors.length, 0); +}); + +test('core reducer - validator option - setAjv does not override a custom validator', (t) => { + const { factory, calls } = fakeValidator(); + const before = coreReducer( + undefined, + init({ foo: 'bad' }, fooSchema, undefined, { validator: factory }) + ); + const after = coreReducer(before, setAjv(explodingAjv)); + t.is(after.ajv, explodingAjv); + t.is(calls.compile.length, 2); + t.is(after.errors.length, 1); + t.is(after.errors[0].keyword, 'const'); +}); + +test('core reducer - validator option - issues are normalized to the AJV error shape', (t) => { + const bound = { + validate: () => [ + { path: '/foo', message: 'no key' }, + { path: '/foo', key: 'required', message: 'is required' }, + { path: '/foo', key: 'x', message: 'warn', severity: 'warning' }, + ], + } as unknown as FormValidator; + const after = coreReducer( + undefined, + init({}, fooSchema, undefined, { validator: bound }) + ); + t.is(after.errors.length, 2); + t.is(after.errors[0].keyword, 'custom'); + t.is(after.errors[1].keyword, 'required'); + t.is(after.errors[1].instancePath, ''); + t.deepEqual(after.errors[1].params, { missingProperty: 'foo' }); + t.deepEqual(errorAt('foo', fooSchema)(after).length, 2); +}); + +test('core reducer - ajv path - formValidator is an AJV-backed validator and state.validator is kept', (t) => { + const after = coreReducer(undefined, init({ foo: 'bar' }, fooSchema)); + t.truthy(after.formValidator); + t.truthy(after.validator); + t.is(after.validatorOption, undefined); + t.is(after.formValidator.validate({ foo: 1 }).length, 1); +}); + +test('core reducer - validator option - getValidator selector exposes the bound validator', (t) => { + const { factory } = fakeValidator(); + const core = coreReducer( + undefined, + init({ foo: 'ok' }, fooSchema, undefined, { validator: factory }) + ); + t.is(getValidator({ jsonforms: { core } } as any), core.formValidator); + t.is(getValidator({ jsonforms: {} } as any), undefined); +}); + test('core reducer helpers - getControlPath - converts JSON Pointer notation to dot notation', (t) => { const errorObject = { instancePath: '/group/name' } as ErrorObject; const controlPath = getControlPath(errorObject); diff --git a/packages/core/test/util/formValidator.test.ts b/packages/core/test/util/formValidator.test.ts new file mode 100644 index 000000000..a94b6e4b4 --- /dev/null +++ b/packages/core/test/util/formValidator.test.ts @@ -0,0 +1,223 @@ +/* + The MIT License + + Copyright (c) 2017-2019 EclipseSource Munich + https://github.com/eclipsesource/jsonforms + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ +import test from 'ava'; +import type { ErrorObject } from 'ajv'; +import { JsonSchema } from '../../src/models'; +import { + ajvErrorsToIssues, + compiledAjvValidator, + createAjvValidator, + isFormValidator, + isFormValidatorFactory, + issuesToErrors, + resolveParentSchema, + toFormValidatorFactory, + ValidationIssue, +} from '../../src/util/formValidator'; +import { createAjv } from '../../src/util/validator'; + +const schema: JsonSchema = { + type: 'object', + properties: { + name: { type: 'string', minLength: 3 }, + tags: { type: 'array', items: { type: 'string' } }, + address: { + type: 'object', + properties: { street: { type: 'string' } }, + required: ['street'], + }, + pet: { $ref: '#/definitions/pet' }, + extra: { type: 'object', additionalProperties: { type: 'number' } }, + }, + required: ['name'], + definitions: { + pet: { type: 'object', properties: { kind: { type: 'string' } } }, + }, +}; + +test('ajvErrorsToIssues - maps AJV fields and keeps the rest', (t) => { + const validateFn = createAjv().compile(schema); + validateFn({ name: 'ab', tags: [1] }); + const issues = ajvErrorsToIssues(validateFn.errors); + t.is(issues.length, 2); + const [minLength, type] = issues; + t.is(minLength.path, '/name'); + t.is(minLength.key, 'minLength'); + t.is(minLength.severity, 'error'); + t.deepEqual(minLength.params, { limit: 3 }); + t.deepEqual(minLength.parentSchema, schema.properties.name); + t.is(minLength.schemaPath, '#/properties/name/minLength'); + t.is(type.path, '/tags/0'); + t.is(type.key, 'type'); + t.is(ajvErrorsToIssues(null).length, 0); +}); + +test('issuesToErrors - round trip of AJV errors is lossless', (t) => { + const validateFn = createAjv().compile(schema); + validateFn({ tags: ['ok', 2], address: {} }); + const original = validateFn.errors; + const roundTripped = issuesToErrors(ajvErrorsToIssues(original), schema); + t.deepEqual(roundTripped, original); +}); + +test('issuesToErrors - missing key becomes custom', (t) => { + const [error] = issuesToErrors([{ path: '/name', message: 'nope' }], schema); + t.is(error.keyword, 'custom'); + t.is(error.instancePath, '/name'); + t.is(error.message, 'nope'); + t.deepEqual(error.params, {}); + t.is(error.schemaPath, ''); + t.deepEqual(error.parentSchema, schema.properties.name); +}); + +test('issuesToErrors - required issue addressed to the missing property is split', (t) => { + const [error] = issuesToErrors( + [{ path: '/address/street', key: 'required', message: 'is required' }], + schema + ); + t.is(error.instancePath, '/address'); + t.deepEqual(error.params, { missingProperty: 'street' }); + t.deepEqual(error.parentSchema, schema.properties.address); +}); + +test('issuesToErrors - required split decodes JSON Pointer escapes', (t) => { + const [error] = issuesToErrors([ + { path: '/a~1b', key: 'required', message: 'is required' }, + ]); + t.is(error.instancePath, ''); + t.deepEqual(error.params, { missingProperty: 'a/b' }); +}); + +test('issuesToErrors - required issue with params is left alone', (t) => { + const issue: ValidationIssue = { + path: '', + key: 'required', + message: 'is required', + params: { missingProperty: 'name' }, + }; + const [error] = issuesToErrors([issue], schema); + t.is(error.instancePath, ''); + t.deepEqual(error.params, { missingProperty: 'name' }); + t.deepEqual(error.parentSchema, schema); +}); + +test('issuesToErrors - non-error severities are dropped', (t) => { + const issues = [ + { path: '/name', key: 'x', message: 'warn', severity: 'warning' }, + { path: '/name', key: 'y', message: 'err', severity: 'error' }, + { path: '/name', key: 'z', message: 'none' }, + ] as unknown as ValidationIssue[]; + const errors = issuesToErrors(issues, schema); + t.deepEqual( + errors.map((e) => e.keyword), + ['y', 'z'] + ); +}); + +test('issuesToErrors - explicit parentSchema wins over resolution', (t) => { + const parentSchema: JsonSchema = { type: 'string' }; + const [error] = issuesToErrors( + [{ path: '/name', key: 'type', message: 'm', parentSchema }], + schema + ); + t.is(error.parentSchema, parentSchema); +}); + +test('issuesToErrors - tolerates null and undefined', (t) => { + t.deepEqual(issuesToErrors(null), []); + t.deepEqual(issuesToErrors(undefined), []); +}); + +test('resolveParentSchema - walks properties, items, additionalProperties and $ref', (t) => { + t.deepEqual(resolveParentSchema(schema, ''), schema); + t.deepEqual(resolveParentSchema(schema, '/name'), schema.properties.name); + t.deepEqual(resolveParentSchema(schema, '/tags/3'), { type: 'string' }); + t.deepEqual( + resolveParentSchema(schema, '/address/street'), + schema.properties.address.properties.street + ); + t.deepEqual(resolveParentSchema(schema, '/pet'), schema.definitions.pet); + t.deepEqual(resolveParentSchema(schema, '/pet/kind'), { type: 'string' }); + t.deepEqual(resolveParentSchema(schema, '/extra/anything'), { + type: 'number', + }); + t.is(resolveParentSchema(schema, '/unknown/deeper'), undefined); + t.is(resolveParentSchema(undefined, '/name'), undefined); +}); + +test('compiledAjvValidator - wraps a compiled validate function', (t) => { + const validateFn = createAjv().compile(schema); + const validator = compiledAjvValidator(validateFn); + t.is(validator.validateFn, validateFn); + t.deepEqual(validator.validate({ name: 'Ada' }), []); + const issues = validator.validate({}); + t.is(issues.length, 1); + t.is(issues[0].key, 'required'); + t.deepEqual(issues[0].params, { missingProperty: 'name' }); + t.is(validator.matches, undefined); +}); + +test('createAjvValidator - compiles with the given instance and offers matches', (t) => { + const ajv = createAjv(); + let compiled = 0; + const originalCompile = ajv.compile.bind(ajv); + ajv.compile = ((s: JsonSchema) => { + compiled++; + return originalCompile(s); + }) as typeof ajv.compile; + const factory = createAjvValidator(ajv); + const validator = factory(schema); + t.is(compiled, 1); + t.is(validator.validate({ name: 'Ada' }).length, 0); + t.true(validator.matches({ const: 'a' }, 'a')); + t.false(validator.matches({ const: 'a' }, 'b')); +}); + +test('createAjvValidator - falls back to a default instance', (t) => { + const validator = createAjvValidator()(schema); + t.is(validator.validate({ name: 'Ada' }).length, 0); + t.is(validator.validate({ name: 'A' }).length, 1); +}); + +test('toFormValidatorFactory and guards', (t) => { + const bound = { validate: () => [] as ValidationIssue[] }; + const factory = () => bound; + t.true(isFormValidator(bound)); + t.false(isFormValidator(factory)); + t.false(isFormValidator(null)); + t.true(isFormValidatorFactory(factory)); + t.false(isFormValidatorFactory(bound)); + t.is(toFormValidatorFactory(factory), factory); + t.is(toFormValidatorFactory(bound)(schema), bound); +}); + +test('issuesToErrors - result satisfies the ErrorObject contract', (t) => { + const errors: ErrorObject[] = issuesToErrors([ + { path: '/name', key: 'minLength', message: 'short', params: { limit: 3 } }, + ]); + t.is(errors[0].keyword, 'minLength'); + t.is(errors[0].instancePath, '/name'); + t.is(typeof errors[0].schemaPath, 'string'); +}); From fb54f126cd5f5c3567349713d6b985193ae0a1f9 Mon Sep 17 00:00:00 2001 From: Luigi Bifulco Date: Wed, 7 Oct 2026 19:39:07 +0200 Subject: [PATCH 4/4] feat(core): evaluate rule conditions through the Form Validator Schema based rule conditions were always evaluated with ajv.validate(condition.schema, value), the last place where a custom Form Validator did not apply. - Widen the `ajv` parameter of isVisible, isEnabled, isReadonly, the eval* functions and Runtime.isVisible/isEnabled to RuleValidator: an Ajv instance (unchanged behaviour), a FormValidator (its `matches`, or the Structural Matcher when it has none), a FormValidatorFactory (one Form Validator per condition schema, cached) or undefined (the Structural Matcher alone). - Add matchesConditionSchema and the getRuleValidator selector; core's own mappers pass getRuleValidator(state) instead of getAjv(state). Part of #1498 Co-Authored-By: Claude Fable 5.1 --- packages/core/src/mappers/cell.ts | 10 +- packages/core/src/mappers/renderer.ts | 14 +- packages/core/src/mappers/util.ts | 12 +- packages/core/src/store/jsonFormsCore.ts | 16 + packages/core/src/util/runtime.ts | 112 +++++-- packages/core/src/util/util.ts | 10 +- packages/core/test/util/runtime.test.ts | 369 ++++++++++++++++++++++- 7 files changed, 508 insertions(+), 35 deletions(-) diff --git a/packages/core/src/mappers/cell.ts b/packages/core/src/mappers/cell.ts index 7934c38cb..352196878 100644 --- a/packages/core/src/mappers/cell.ts +++ b/packages/core/src/mappers/cell.ts @@ -45,7 +45,7 @@ import type { JsonSchema } from '../models'; import { AnyAction, Dispatch, - getAjv, + getRuleValidator, getConfig, getData, getErrorAt, @@ -116,7 +116,13 @@ export const mapStateToCellProps = ( const visible = ownProps.visible !== undefined ? ownProps.visible - : isVisible(uischema, rootData, undefined, getAjv(state), config); + : isVisible( + uischema, + rootData, + undefined, + getRuleValidator(state), + config + ); const rootSchema = getSchema(state); diff --git a/packages/core/src/mappers/renderer.ts b/packages/core/src/mappers/renderer.ts index 08d65ec4b..5944abf98 100644 --- a/packages/core/src/mappers/renderer.ts +++ b/packages/core/src/mappers/renderer.ts @@ -72,7 +72,7 @@ import { } from '../util'; import { Translator, - getAjv, + getRuleValidator, getCells, getConfig, getData, @@ -597,7 +597,13 @@ export const mapStateToControlProps = ( const visible: boolean = ownProps.visible === undefined || hasShowRule(uischema) - ? isVisible(uischema, rootData, ownProps.path, getAjv(state), config) + ? isVisible( + uischema, + rootData, + ownProps.path, + getRuleValidator(state), + config + ) : ownProps.visible; const controlElement = uischema as ControlElement; const id = ownProps.id; @@ -1067,7 +1073,7 @@ export const mapStateToLayoutProps = ( ownProps.uischema, rootData, ownProps.path, - getAjv(state), + getRuleValidator(state), getConfig(state) ) : ownProps.visible; @@ -1293,7 +1299,7 @@ export const mapStateToLabelProps = ( props.uischema, getData(state), props.path, - getAjv(state), + getRuleValidator(state), getConfig(state) ) : props.visible; diff --git a/packages/core/src/mappers/util.ts b/packages/core/src/mappers/util.ts index bd87bd2ab..b6c403efd 100644 --- a/packages/core/src/mappers/util.ts +++ b/packages/core/src/mappers/util.ts @@ -1,5 +1,5 @@ import { JsonSchema, UISchemaElement } from '../models'; -import { JsonFormsState, getAjv } from '../store'; +import { JsonFormsState, getRuleValidator } from '../store'; import { hasEnableRule, hasReadonlyRule, isEnabled, isReadonly } from '../util'; /** @@ -19,7 +19,13 @@ export const isInherentlyEnabled = ( return false; } if (uischema && hasEnableRule(uischema)) { - return isEnabled(uischema, rootData, ownProps?.path, getAjv(state), config); + return isEnabled( + uischema, + rootData, + ownProps?.path, + getRuleValidator(state), + config + ); } if (!config?.separateReadonlyFromDisabled) { if (typeof uischema?.options?.readonly === 'boolean') { @@ -66,7 +72,7 @@ export const isInherentlyReadonly = ( uischema, rootData, ownProps?.path, - getAjv(state), + getRuleValidator(state), config ); } diff --git a/packages/core/src/store/jsonFormsCore.ts b/packages/core/src/store/jsonFormsCore.ts index ba88ac6b2..ba129d4bd 100644 --- a/packages/core/src/store/jsonFormsCore.ts +++ b/packages/core/src/store/jsonFormsCore.ts @@ -4,6 +4,7 @@ import { JsonSchema, UISchemaElement } from '../models'; import get from 'lodash/get'; import { errorsAt } from '../util'; import type { FormValidator } from '../util/formValidator'; +import type { RuleValidator } from '../util/runtime'; import { JsonFormsCellRendererRegistryEntry, JsonFormsCore, @@ -74,6 +75,21 @@ export const extractData = (state: JsonFormsCore) => get(state, 'data'); export const extractSchema = (state: JsonFormsCore) => get(state, 'schema'); export const extractUiSchema = (state: JsonFormsCore) => get(state, 'uischema'); export const extractAjv = (state: JsonFormsCore) => get(state, 'ajv'); +/** + * What rule conditions are evaluated with: the configured Form Validator when + * a custom one is set (the bound one, or the option itself while validation is + * off), otherwise the AJV instance. + */ +export const getRuleValidator = (state: JsonFormsState): RuleValidator => { + const core: JsonFormsCore | undefined = get(state, 'jsonforms.core'); + if (core === undefined) { + return undefined; + } + if (core.validatorOption !== undefined) { + return core.formValidator ?? core.validatorOption; + } + return core.ajv; +}; export const extractValidator = ( state: JsonFormsCore ): FormValidator | undefined => get(state, 'formValidator'); diff --git a/packages/core/src/util/runtime.ts b/packages/core/src/util/runtime.ts index d4fb4ff10..898d70641 100644 --- a/packages/core/src/util/runtime.ts +++ b/packages/core/src/util/runtime.ts @@ -38,6 +38,82 @@ import { import { resolveData } from './resolvers'; import type Ajv from 'ajv'; import { composeWithUi } from './uischema'; +import isFunction from 'lodash/isFunction'; +import type { JsonSchema } from '../models'; +import { + FormValidator, + FormValidatorFactory, + isFormValidator, + isFormValidatorFactory, +} from './formValidator'; +import { isStructuralMatch } from './structural'; + +/** + * What rule conditions are evaluated with: + * - an AJV instance (the historical argument): `ajv.validate(schema, data)`; + * - a Form Validator: its `matches`, or the Structural Matcher when it has none; + * - a Form Validator Factory: one Form Validator per condition schema, cached; + * - `undefined`: the Structural Matcher alone. + */ +export type RuleValidator = + | Ajv + | FormValidator + | FormValidatorFactory + | undefined; + +const isAjvInstance = (candidate: unknown): candidate is Ajv => + typeof candidate === 'object' && + candidate !== null && + isFunction((candidate as Ajv).compile) && + isFunction((candidate as Ajv).validate); + +const conditionValidators = new WeakMap< + FormValidatorFactory, + WeakMap +>(); + +const conditionValidatorFor = ( + factory: FormValidatorFactory, + schema: JsonSchema +): FormValidator => { + if (typeof schema !== 'object' || schema === null) { + return factory(schema); + } + let perSchema = conditionValidators.get(factory); + if (perSchema === undefined) { + perSchema = new WeakMap(); + conditionValidators.set(factory, perSchema); + } + let validator = perSchema.get(schema); + if (validator === undefined) { + validator = factory(schema); + perSchema.set(schema, validator); + } + return validator; +}; + +/** + * Whether `data` satisfies the rule condition `schema`, evaluated with the + * given {@link RuleValidator}. + */ +export const matchesConditionSchema = ( + schema: JsonSchema, + data: unknown, + validator: RuleValidator +): boolean => { + if (isAjvInstance(validator)) { + return validator.validate(schema, data) as boolean; + } + if (isFormValidatorFactory(validator)) { + return conditionValidatorFor(validator, schema).validate(data).length === 0; + } + if (isFormValidator(validator)) { + return validator.matches + ? validator.matches(schema, data) + : isStructuralMatch(schema, data); + } + return isStructuralMatch(schema, data); +}; const isOrCondition = (condition: Condition): condition is OrCondition => condition.type === 'OR'; @@ -67,19 +143,19 @@ const evaluateCondition = ( uischema: UISchemaElement, condition: Condition, path: string, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { if (isAndCondition(condition)) { return condition.conditions.reduce( (acc, cur) => - acc && evaluateCondition(data, uischema, cur, path, ajv, config), + acc && evaluateCondition(data, uischema, cur, path, validator, config), true ); } else if (isOrCondition(condition)) { return condition.conditions.reduce( (acc, cur) => - acc || evaluateCondition(data, uischema, cur, path, ajv, config), + acc || evaluateCondition(data, uischema, cur, path, validator, config), false ); } else if (isLeafCondition(condition)) { @@ -90,7 +166,7 @@ const evaluateCondition = ( if (condition.failWhenUndefined && value === undefined) { return false; } - return ajv.validate(condition.schema, value) as boolean; + return matchesConditionSchema(condition.schema, value, validator); } else if (isValidateFunctionCondition(condition)) { const value = resolveData(data, getConditionScope(condition, path)); const context = { @@ -111,21 +187,21 @@ const isRuleFulfilled = ( uischema: UISchemaElement, data: any, path: string, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { const condition = uischema.rule.condition; - return evaluateCondition(data, uischema, condition, path, ajv, config); + return evaluateCondition(data, uischema, condition, path, validator, config); }; export const evalVisibility = ( uischema: UISchemaElement, data: any, path: string = undefined, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { - const fulfilled = isRuleFulfilled(uischema, data, path, ajv, config); + const fulfilled = isRuleFulfilled(uischema, data, path, validator, config); switch (uischema.rule.effect) { case RuleEffect.HIDE: @@ -142,10 +218,10 @@ export const evalEnablement = ( uischema: UISchemaElement, data: any, path: string = undefined, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { - const fulfilled = isRuleFulfilled(uischema, data, path, ajv, config); + const fulfilled = isRuleFulfilled(uischema, data, path, validator, config); switch (uischema.rule.effect) { case RuleEffect.DISABLE: @@ -162,10 +238,10 @@ export const evalReadonly = ( uischema: UISchemaElement, data: any, path: string = undefined, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { - const fulfilled = isRuleFulfilled(uischema, data, path, ajv, config); + const fulfilled = isRuleFulfilled(uischema, data, path, validator, config); switch (uischema.rule.effect) { case RuleEffect.WRITABLE: @@ -215,11 +291,11 @@ export const isVisible = ( uischema: UISchemaElement, data: any, path: string = undefined, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { if (uischema.rule) { - return evalVisibility(uischema, data, path, ajv, config); + return evalVisibility(uischema, data, path, validator, config); } return true; @@ -229,11 +305,11 @@ export const isEnabled = ( uischema: UISchemaElement, data: any, path: string = undefined, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { if (uischema.rule) { - return evalEnablement(uischema, data, path, ajv, config); + return evalEnablement(uischema, data, path, validator, config); } return true; @@ -243,11 +319,11 @@ export const isReadonly = ( uischema: UISchemaElement, data: any, path: string = undefined, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean => { if (uischema.rule) { - return evalReadonly(uischema, data, path, ajv, config); + return evalReadonly(uischema, data, path, validator, config); } return false; diff --git a/packages/core/src/util/util.ts b/packages/core/src/util/util.ts index ed4eae93d..7bf2c4c8e 100644 --- a/packages/core/src/util/util.ts +++ b/packages/core/src/util/util.ts @@ -29,7 +29,7 @@ import find from 'lodash/find'; import { resolveData, resolveSchema } from './resolvers'; import { composePaths, toDataPathSegments } from './path'; import { isEnabled, isVisible } from './runtime'; -import type Ajv from 'ajv'; +import type { RuleValidator } from './runtime'; import type { JsonSchema, Scoped, UISchemaElement } from '../models'; /** @@ -165,17 +165,17 @@ export const Runtime = { isEnabled( uischema: UISchemaElement, data: any, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean { - return isEnabled(uischema, data, undefined, ajv, config); + return isEnabled(uischema, data, undefined, validator, config); }, isVisible( uischema: UISchemaElement, data: any, - ajv: Ajv, + validator: RuleValidator, config: unknown ): boolean { - return isVisible(uischema, data, undefined, ajv, config); + return isVisible(uischema, data, undefined, validator, config); }, }; diff --git a/packages/core/test/util/runtime.test.ts b/packages/core/test/util/runtime.test.ts index c72e45f98..a8ddf466f 100644 --- a/packages/core/test/util/runtime.test.ts +++ b/packages/core/test/util/runtime.test.ts @@ -43,7 +43,12 @@ import { evalEnablement, evalReadonly, evalVisibility, + isVisible, + matchesConditionSchema, } from '../../src/util/runtime'; +import type { FormValidator } from '../../src/util/formValidator'; +import { getRuleValidator } from '../../src/store'; +import { JsonSchema } from '../../src/models'; test('evalVisibility show valid case', (t) => { const leafCondition: LeafCondition = { @@ -1115,7 +1120,7 @@ test('isInherentlyEnabled disabled by rule', (t) => { t.false( isInherentlyEnabled( - { jsonforms: { core: { ajv: createAjv() } as JsonFormsCore } }, + { jsonforms: { core: { ajv: createAjv() } as unknown as JsonFormsCore } }, null, uischema, undefined, @@ -1148,7 +1153,7 @@ test('isInherentlyEnabled disabled by global over rule ', (t) => { { jsonforms: { readonly: true, - core: { ajv: createAjv() } as JsonFormsCore, + core: { ajv: createAjv() } as unknown as JsonFormsCore, }, }, null, @@ -1344,7 +1349,7 @@ test('isInherentlyReadonly evaluates readonly and writable rules', (t) => { }; const state = { jsonforms: { - core: { ajv: createAjv() } as JsonFormsCore, + core: { ajv: createAjv() } as unknown as JsonFormsCore, }, }; const data = { @@ -1369,3 +1374,361 @@ test('isInherentlyReadonly evaluates readonly and writable rules', (t) => { ) ); }); + +const ruleUischema = ( + condition: SchemaBasedCondition | AndCondition | OrCondition +): ControlElement => ({ + type: 'Control', + scope: '#/properties/value', + rule: { effect: RuleEffect.SHOW, condition }, +}); + +const barCondition: SchemaBasedCondition = { + scope: '#/properties/ruleValue', + schema: { const: 'bar' }, +}; + +test('rules - schema condition uses the Form Validator matches when present', (t) => { + const calls: Array<[JsonSchema, unknown]> = []; + const validator: FormValidator = { + validate: () => [], + matches: (schema, data) => { + calls.push([schema, data]); + return data === 'bar'; + }, + }; + const uischema = ruleUischema(barCondition); + t.true( + evalVisibility( + uischema, + { ruleValue: 'bar' }, + undefined, + validator, + undefined + ) + ); + t.false( + evalVisibility( + uischema, + { ruleValue: 'baz' }, + undefined, + validator, + undefined + ) + ); + t.deepEqual(calls, [ + [barCondition.schema, 'bar'], + [barCondition.schema, 'baz'], + ]); +}); + +test('rules - a Form Validator without matches falls back to the Structural Matcher', (t) => { + const validator: FormValidator = { validate: () => [] }; + const uischema = ruleUischema(barCondition); + t.true( + evalVisibility( + uischema, + { ruleValue: 'bar' }, + undefined, + validator, + undefined + ) + ); + t.false( + evalVisibility( + uischema, + { ruleValue: 'baz' }, + undefined, + validator, + undefined + ) + ); +}); + +test('rules - no validator at all uses the Structural Matcher', (t) => { + const uischema = ruleUischema({ + scope: '#/properties/ruleValue', + schema: { type: 'string', enum: ['a', 'b'] }, + }); + t.true( + evalVisibility( + uischema, + { ruleValue: 'a' }, + undefined, + undefined, + undefined + ) + ); + t.false( + evalVisibility( + uischema, + { ruleValue: 'c' }, + undefined, + undefined, + undefined + ) + ); + t.false( + evalVisibility(uischema, { ruleValue: 1 }, undefined, undefined, undefined) + ); +}); + +test('rules - a Form Validator Factory is called once per condition schema', (t) => { + const compiled: JsonSchema[] = []; + const factory = (schema: JsonSchema): FormValidator => { + compiled.push(schema); + return { + validate: (data) => + data === (schema as { const: unknown }).const + ? [] + : [{ path: '', key: 'const', message: 'mismatch' }], + }; + }; + const uischema = ruleUischema(barCondition); + t.true( + evalVisibility( + uischema, + { ruleValue: 'bar' }, + undefined, + factory, + undefined + ) + ); + t.false( + evalVisibility( + uischema, + { ruleValue: 'baz' }, + undefined, + factory, + undefined + ) + ); + t.true( + evalVisibility( + uischema, + { ruleValue: 'bar' }, + undefined, + factory, + undefined + ) + ); + t.is(compiled.length, 1); + t.is(compiled[0], barCondition.schema); + + const other = ruleUischema({ + scope: '#/properties/ruleValue', + schema: { const: 'other' }, + }); + t.true( + evalVisibility(other, { ruleValue: 'other' }, undefined, factory, undefined) + ); + t.is(compiled.length, 2); +}); + +test('rules - AND and OR compose with a Form Validator', (t) => { + const validator: FormValidator = { + validate: () => [], + matches: (schema, data) => data === (schema as { const: unknown }).const, + }; + const and: AndCondition = { + type: 'AND', + conditions: [ + barCondition, + { scope: '#/properties/other', schema: { const: 1 } }, + ], + }; + const or: OrCondition = { type: 'OR', conditions: and.conditions }; + t.true( + evalVisibility( + ruleUischema(and), + { ruleValue: 'bar', other: 1 }, + undefined, + validator, + undefined + ) + ); + t.false( + evalVisibility( + ruleUischema(and), + { ruleValue: 'bar', other: 2 }, + undefined, + validator, + undefined + ) + ); + t.true( + evalVisibility( + ruleUischema(or), + { ruleValue: 'x', other: 1 }, + undefined, + validator, + undefined + ) + ); + t.false( + evalVisibility( + ruleUischema(or), + { ruleValue: 'x', other: 2 }, + undefined, + validator, + undefined + ) + ); +}); + +test('rules - an AJV instance keeps working as the rule validator', (t) => { + const uischema = ruleUischema({ + scope: '#/properties/ruleValue', + schema: { type: 'string', minLength: 3 }, + }); + t.true( + evalVisibility( + uischema, + { ruleValue: 'long' }, + undefined, + createAjv(), + undefined + ) + ); + t.false( + evalVisibility( + uischema, + { ruleValue: 'no' }, + undefined, + createAjv(), + undefined + ) + ); +}); + +test('rules - enablement and readonly go through the Form Validator too', (t) => { + const validator: FormValidator = { + validate: () => [], + matches: (_schema, data) => data === 'bar', + }; + const enable: ControlElement = { + type: 'Control', + scope: '#/properties/value', + rule: { effect: RuleEffect.ENABLE, condition: barCondition }, + }; + const readonly: ControlElement = { + type: 'Control', + scope: '#/properties/value', + rule: { effect: RuleEffect.READONLY, condition: barCondition }, + }; + t.true( + evalEnablement( + enable, + { ruleValue: 'bar' }, + undefined, + validator, + undefined + ) + ); + t.false( + evalEnablement(enable, { ruleValue: 'x' }, undefined, validator, undefined) + ); + t.true( + evalReadonly( + readonly, + { ruleValue: 'bar' }, + undefined, + validator, + undefined + ) + ); + t.false( + evalReadonly(readonly, { ruleValue: 'x' }, undefined, validator, undefined) + ); +}); + +test('matchesConditionSchema - dispatches on the validator kind', (t) => { + const schema: JsonSchema = { const: 'a' }; + t.true(matchesConditionSchema(schema, 'a', undefined)); + t.true(matchesConditionSchema(schema, 'a', createAjv())); + t.false(matchesConditionSchema(schema, 'b', createAjv())); + t.true(matchesConditionSchema(schema, 'a', { validate: () => [] })); + t.false( + matchesConditionSchema(schema, 'a', { + validate: () => [], + matches: () => false, + }) + ); + t.false( + matchesConditionSchema(schema, 'a', () => ({ + validate: () => [{ path: '', message: 'nope' }], + })) + ); +}); + +test('getRuleValidator - AJV instance when no custom validator is configured', (t) => { + const ajv = createAjv(); + const state = { jsonforms: { core: { ajv } as unknown as JsonFormsCore } }; + t.is(getRuleValidator(state as any), ajv); + t.is(getRuleValidator({ jsonforms: {} } as any), undefined); +}); + +test('getRuleValidator - the bound Form Validator when a custom one is configured', (t) => { + const ajv = createAjv(); + const bound: FormValidator = { validate: () => [] }; + const factory = () => bound; + const state = { + jsonforms: { + core: { + ajv, + validatorOption: factory, + formValidator: bound, + } as unknown as JsonFormsCore, + }, + }; + t.is(getRuleValidator(state as any), bound); + const off = { + jsonforms: { + core: { + ajv, + validatorOption: factory, + formValidator: undefined, + } as unknown as JsonFormsCore, + }, + }; + t.is(getRuleValidator(off as any), factory); +}); + +test('isVisible - integrates with getRuleValidator for a custom validator', (t) => { + const bound: FormValidator = { + validate: () => [], + matches: (_schema, data) => data === 'bar', + }; + const core = { + ajv: { + validate: () => { + throw new Error('AJV must not evaluate rules when a validator is set'); + }, + compile: () => { + throw new Error('no compile'); + }, + }, + validatorOption: bound, + formValidator: bound, + } as unknown as JsonFormsCore; + const state = { jsonforms: { core } } as any; + const uischema = ruleUischema(barCondition); + t.true( + isVisible( + uischema, + { ruleValue: 'bar' }, + undefined, + getRuleValidator(state), + undefined + ) + ); + t.false( + isVisible( + uischema, + { ruleValue: 'x' }, + undefined, + getRuleValidator(state), + undefined + ) + ); +});