From b525f6f71f572a6d7ed2e88d49a79389a708c1bb Mon Sep 17 00:00:00 2001 From: Vitaliy Ryaboy Date: Sat, 28 Nov 2026 17:13:01 +0100 Subject: [PATCH] perf: project scalar nullable anyOf responses Reuse ordered Ajv branch validation in the native projection. Preserve conversion output and keep the string codegen where schema merging or serialization options require it. Refs fastify/fast-json-stringify#942 --- README.md | 14 ++- index.js | 21 ++-- lib/projection.js | 83 ++++++++++--- test/object-mechanism-native.test.js | 170 +++++++++++++++++++++++++++ 4 files changed, 260 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 321921eb..bd5ce305 100644 --- a/README.md +++ b/README.md @@ -766,9 +766,17 @@ The projection covers schemas made only of: - the two-element forms `['string', 'null']`, `['number', 'null']` and `['boolean', 'null']` (in either order), with the same strict type dispatch as the default mechanism; -- `array` whose `items` is one such schema (no tuples), nested to any depth. - -Each of them can be `nullable: true` and can have an `enum`. +- `anyOf` with one `string`, `number`, `integer` or `boolean` branch (without + `const`, `$ref`, combinators or string format `unsafe`) and one `null` branch. + Branches are validated with Ajv in schema order. The only supported sibling + keyword of `anyOf` is `default`, when neither branch has its own default; +- `array` whose `items` is one such schema (no tuples), unless + `largeArrayMechanism` is set to `'json-stringify'`. + +Objects, arrays and primitive schemas can be `nullable: true` and can have an +`enum`. +Objects whose required-property order would conflict with the native ordering +of array-index keys keep the default mechanism. Each of them can also be reached through a `$ref`, to a definition of the same schema or to an external schema. Two kinds of `$ref` keep the default diff --git a/index.js b/index.js index 3f147b9f..e00e157b 100644 --- a/index.js +++ b/index.js @@ -401,6 +401,12 @@ function buildValidation (context, schemaRef, input) { return `(${name} || (${name} = validator.getSchemaValidator(${JSON.stringify(schemaRef)})))(${input})` } +function buildBranchValidation (context, location, input) { + const schemaRef = getValidatorSchemaRef(context, location) + context.validatorSchemaRefs.add(schemaRef) + return buildValidation(context, schemaRef, input) +} + function resolveValidatorSchemaRef (context, location) { let schemaRef = location.getSchemaRef() const schema = location.schema @@ -543,9 +549,8 @@ function build (schema, options) { } // objectMechanism: 'native' projects the input into shape-stable scratch - // objects and delegates to the native JSON.stringify. Only whole schemas - // made of objects, arrays and primitives qualify; anything else falls back - // to the string codegen below, so output never changes for unsupported shapes. + // objects and delegates to the native JSON.stringify. Schemas containing + // unsupported shapes fall back to the string codegen below. // The projection only pays off where V8 has the side-effect-free // JSON.stringify fast path (V8 13.8+, Node 25+): on older runtimes the // string codegen is up to 2x faster, so the option is a no-op there. @@ -557,6 +562,11 @@ function build (schema, options) { projection = buildProjection(location, { resolve: (location) => resolveRef(context, location), pointer: (location) => getSafeSchemaRef(context, location), + validate: (location, input) => { + context.validatorSchemasIds.add(location.schemaId) + return buildBranchValidation(context, location, input) + }, + projectArrays: context.largeArrayMechanism !== 'json-stringify', ignoredSiblings: IGNORED_REF_SIBLING_KEYWORDS }) } @@ -1778,11 +1788,8 @@ function buildOneOf (context, location, input) { nestedResult = buildValue(context, mergedLocation, input) } - const schemaRef = getValidatorSchemaRef(context, optionLocation) - context.validatorSchemaRefs.add(schemaRef) - code += ` - ${index === 0 ? 'if' : 'else if'}(${buildValidation(context, schemaRef, input)}) { + ${index === 0 ? 'if' : 'else if'}(${buildBranchValidation(context, optionLocation, input)}) { ${nestedResult} } ` diff --git a/lib/projection.js b/lib/projection.js index 5f3bd88f..bcec10ae 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -24,6 +24,7 @@ // with the strict no-coercion dispatch of the multi-type codegen; // ['integer', 'null'] is left to the codegen (its null handling depends // on the type order); +// - anyOf with one scalar and one null branch, validated in schema order; // - array whose `items` is a single projectable schema (not a tuple). // Any of them may be `nullable: true` (null is then written as null) and may // carry an `enum`, which the codegen does not use once the type is known. @@ -65,6 +66,7 @@ const MAX_PROPERTIES = 127 // The JSON pointer of a projected node, as the codegen writes it in its errors. const POINTER = Symbol('pointer') +const NULLABLE_ANY_OF = Symbol('nullableAnyOf') // A $ref is projected by expanding its target in place, so a schema that is // used many times is also copied many times. Past this number of expanded @@ -96,12 +98,33 @@ function resolveProjectable (location, refs, state, depth) { return node } +function resolveNullableAnyOf (location, node) { + const schema = location.schema + if (!Array.isArray(schema.anyOf) || schema.anyOf.length !== 2) return null + // The string codegen merges sibling keywords into each branch. A default + // only determines what the containing object's missing property emits. + if (Object.keys(schema).some(key => key !== 'anyOf' && key !== 'default')) return null + const anyOf = location.getPropertyLocation('anyOf') + const branches = [anyOf.getPropertyLocation(0), anyOf.getPropertyLocation(1)] + for (const { schema: branch } of branches) { + if (typeof branch !== 'object' || branch === null || branch.$ref !== undefined || hasDispatchKeyword(branch)) return null + if (branch.type === 'string' && branch.format === 'unsafe') return null + // The merge can reject conflicting defaults even if a value is present. + if (schema.default !== undefined && branch.default !== undefined) return null + } + const types = branches.map(branch => branch.schema.type) + if (!types.includes('null') || !types.some(type => PRIMITIVES.has(type))) return null + node[NULLABLE_ANY_OF] = branches + return node +} + function resolveNode (location, refs, state, depth) { const schema = location.schema if (state.open.size !== 0 && ++state.refNodes > MAX_REF_NODES) return null - if (hasDispatchKeyword(schema)) return null const node = { ...schema, [POINTER]: refs.pointer(location) } + if (schema.anyOf !== undefined) return resolveNullableAnyOf(location, node) + if (hasDispatchKeyword(schema)) return null if (Array.isArray(schema.type)) return nullableMultiType(schema) !== null ? node : null if (schema.type === 'object') { @@ -113,6 +136,13 @@ function resolveNode (location, refs, state, depth) { } const keys = Object.keys(schema.properties) if (keys.length === 0 || keys.length > MAX_PROPERTIES) return null + // JSON.stringify always emits index keys first, whereas the codegen + // emits required properties first. Keep the codegen if these disagree. + const indexKeys = keys.filter(key => String(key >>> 0) === key && key !== '4294967295') + if (indexKeys.length !== 0) { + const ordered = orderedKeys(schema) + if (indexKeys.some((key, i) => key !== ordered[i])) return null + } const propertiesLocation = location.getPropertyLocation('properties') node.properties = Object.create(null) for (const key of keys) { @@ -124,7 +154,7 @@ function resolveNode (location, refs, state, depth) { } if (schema.type === 'array') { - if (schema.items === undefined || Array.isArray(schema.items) || schema.additionalItems !== undefined) return null + if (!refs.projectArrays || schema.items === undefined || Array.isArray(schema.items) || schema.additionalItems !== undefined) return null node.items = resolveProjectable(location.getPropertyLocation('items'), refs, state, depth + 1) return node.items !== null ? node : null } @@ -175,7 +205,8 @@ function orderedKeys (schema) { } class Emitter { - constructor () { + constructor (validate) { + this.validate = validate this.uid = 0 // JSON pointers for error messages. The generated code only ever refers // to them by index into this table (emitted as a JSON literal), so no @@ -256,7 +287,17 @@ class Emitter { valueExpr (schema, src, out, indent) { if (schema.type === 'object') return this.projectObject(schema, src, out, indent) if (schema.type === 'array') return this.projectArray(schema, src, out, indent) - return primitiveExpr(schema, src, this.pointerIndex(schema[POINTER])) + const pointerIdx = this.pointerIndex(schema[POINTER]) + const branches = schema[NULLABLE_ANY_OF] + if (branches === undefined) return primitiveExpr(schema, src, pointerIdx) + + // Reuse the ordinary Ajv checks, including constraints and coercion, on + // the original value. Only project it once a branch has been selected. + const [first, second] = branches.map(branch => { + const value = branch.schema.type === 'null' ? 'null' : primitiveExpr(branch.schema, src, pointerIdx) + return `${this.validate(branch, src)} ? ${value}` + }) + return `(${first} : ${second} : typeMismatch(${pointerIdx}))` } // Pushes the statements that project `src` as an array and returns the @@ -276,7 +317,7 @@ class Emitter { out.push(`${indent} const ${n} = ${src}.length`) out.push(`${indent} ${result} = new Array(${n})`) out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`) - if (items.type === 'object' || items.type === 'array') { + if (items.type === 'object' || items.type === 'array' || items[NULLABLE_ANY_OF] !== undefined) { const el = this.id('el') out.push(`${indent} const ${el} = ${src}[${i}]`) out.push(`${indent} ${result}[${i}] = ${this.valueExpr(items, el, out, indent + ' ')}`) @@ -292,13 +333,14 @@ class Emitter { // Returns the full body of the context function (declarations + main) or null // when the schema at `location` is not projectable. `refs` is how the codegen // reads a $ref: `resolve(location)` gives the location of its target, -// `pointer(location)` the JSON pointer used in the errors, `ignoredSiblings` -// the keywords that may stand next to a $ref without changing its target. +// `pointer(location)` the JSON pointer used in the errors, `validate(location, +// input)` emits the codegen's branch check, `projectArrays` controls whether +// arrays can be projected, and `ignoredSiblings` holds the neutral $ref siblings. function buildProjection (location, refs) { const schema = resolveProjectable(location, refs, { open: new Set(), refNodes: 0 }, 0) if (schema === null) return null if (schema.type !== 'object' && schema.type !== 'array') return null // primitive roots gain nothing - const em = new Emitter() + const em = new Emitter(refs.validate) const body = [] const rootExpr = em.valueExpr(schema, 'input', body, ' ') // A BigInt outside the safe integer range has no exact Number, so it is @@ -330,12 +372,12 @@ function buildProjection (location, refs) { ${body.join('\n')} if (hasBigInt) { hasBigInt = false - return stringifyWithBigInt(${rootExpr}) + return stringifyProjectedFallback(${rootExpr}) } try { return JSON.stringify(${rootExpr}) } catch { - return stringifyWithBigInt(${rootExpr}) + return stringifyProjectedFallback(${rootExpr}) } } return main @@ -345,12 +387,19 @@ ${body.join('\n')} // Runtime helpers mirroring lib/serializer.js, returning values (not JSON text) // to be placed into the projected objects. const projectionHelpers = ` + // Preserve the codegen's exact output when a custom toString() returns + // something other than a string. Only these values need the fallback walker. + class SerializedValue { + constructor (json) { this.json = json } + toJSON () { throw new TypeError('Serialized value requires the projection fallback') } + } const asStringValue = (v) => { if (typeof v === 'string') return v if (v === null) return '' if (v instanceof Date) return serializer.asDateTimeValue(v) if (v instanceof RegExp) return v.source - return v.toString() + const str = v.toString() + return typeof str === 'string' ? str : new SerializedValue(serializer.asString(str)) } const asDateTimeValue = (v) => { if (v === null) return '' @@ -370,24 +419,22 @@ const projectionHelpers = ` } const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER) const MIN_SAFE_BIGINT = -MAX_SAFE_BIGINT - // Serializes a projected value that holds a BigInt, the one value the native - // JSON.stringify rejects. A projected value is made of plain objects, arrays, - // strings, numbers, booleans, null and undefined, so nothing else needs - // handling. - const stringifyWithBigInt = (v) => { + // Writes values that cannot be handed directly to JSON.stringify. + const stringifyProjectedFallback = (v) => { if (typeof v === 'bigint') return v.toString() if (v === null || typeof v !== 'object') return JSON.stringify(v) + if (v instanceof SerializedValue) return v.json let json = '' if (Array.isArray(v)) { for (let i = 0; i < v.length; i++) { - json += (i === 0 ? '[' : ',') + stringifyWithBigInt(v[i]) + json += (i === 0 ? '[' : ',') + stringifyProjectedFallback(v[i]) } return json === '' ? '[]' : json + ']' } for (const key of Object.keys(v)) { const value = v[key] if (value !== undefined) { - json += (json === '' ? '{' : ',') + JSON.stringify(key) + ':' + stringifyWithBigInt(value) + json += (json === '' ? '{' : ',') + JSON.stringify(key) + ':' + stringifyProjectedFallback(value) } } return json === '' ? '{}' : json + '}' diff --git a/test/object-mechanism-native.test.js b/test/object-mechanism-native.test.js index 00567a22..60ab4011 100644 --- a/test/object-mechanism-native.test.js +++ b/test/object-mechanism-native.test.js @@ -142,6 +142,153 @@ test('native mechanism: array root of primitives', t => { } }) +test('native mechanism projects nullable anyOf using the original branch validators', t => { + const schema = { + type: 'object', + additionalProperties: false, + required: ['name'], + properties: { + name: { anyOf: [{ type: 'string', pattern: '^[A-Z]+$' }, { type: 'null' }] }, + day: { anyOf: [{ type: 'null' }, { type: 'string', format: 'date' }] }, + count: { anyOf: [{ type: 'integer', minimum: 1 }, { type: 'null' }] }, + score: { anyOf: [{ type: 'number' }, { type: 'null' }], default: 0 }, + flags: { type: 'array', items: { anyOf: [{ type: 'null' }, { type: 'boolean', enum: [true] }] } } + } + } + const snapshot = structuredClone(schema) + const def = build(schema) + const debug = build(schema, { objectMechanism: 'native', mode: 'debug', compileValidators: true }) + const nat = fjs.restore(debug) + const inputs = [ + { name: 'ABC', day: '2026-02-01', count: 2, flags: [true, null], extra: 'removed' }, + { name: null, day: null, count: null, score: null }, + { name: 'ABC', day: new Date(0), score: 2.5, flags: [] }, + { name: new Date(0) }, + { name: { toJSON: () => 'ignored', toString: () => 'serialized' } }, + { name: 'a' }, + { name: 3 }, + { name: /ABC/ }, + { name: 'ABC', day: '2026-02-31' }, + { name: 'ABC', count: 1.2 }, + { name: 'ABC', count: 0 }, + { name: 'ABC', score: Infinity }, + { name: 'ABC', flags: [false] }, + { name: 'ABC', flags: [undefined] }, + {} + ] + t.plan(inputs.length + 3) + t.assert.match(debug.code, /asStringValue/) + for (const input of inputs) { + t.assert.deepStrictEqual(run(nat, input), run(def, input)) + } + t.assert.deepStrictEqual(schema, snapshot) + t.assert.throws(() => nat({ name: 'a' }), { + name: 'TypeError', + message: "The value of '#/properties/name' does not match schema definition." + }) +}) + +test('native mechanism preserves nullable anyOf order with Ajv coercion', t => { + const scalar = { type: 'boolean' } + const nil = { type: 'null' } + const options = { ajv: { coerceTypes: true } } + const input = { value: false } + t.plan(6) + for (const [branches, expected] of [ + [[scalar, nil], '{"value":false}'], + [[nil, scalar], '{"value":null}'] + ]) { + const schema = { type: 'object', properties: { value: { anyOf: branches } } } + const debug = build(schema, { ...options, objectMechanism: 'native', mode: 'debug' }) + t.assert.match(debug.code, /asStringValue/) + t.assert.equal(fjs.restore(debug)(input), expected) + t.assert.equal(fjs.restore(debug)(input), build(schema, options)(input)) + } +}) + +test('native mechanism reads nullable anyOf array items only once', t => { + const schema = { type: 'array', items: { anyOf: [{ type: 'null' }, { type: 'string' }] } } + const native = build(schema, { objectMechanism: 'native' }) + const input = [] + let reads = 0 + const get = () => (++reads === 1 ? 'value' : false) + Object.defineProperty(input, '0', { get }) + t.plan(2) + t.assert.equal(native(input), '["value"]') + t.assert.equal(reads, 1) +}) + +test('native mechanism preserves string branch conversion on unusual toString results', t => { + const schema = { + type: 'object', + properties: { value: { anyOf: [{ type: 'string' }, { type: 'null' }] } } + } + const def = build(schema) + const nat = build(schema, { objectMechanism: 'native' }) + const values = [null, undefined, [1], [], 123, { answer: 42 }] + t.plan(values.length) + for (const value of values) { + const input = { value: { toJSON: () => 'ignored', toString: () => value } } + t.assert.deepStrictEqual(run(nat, input), run(def, input)) + } +}) + +test('native mechanism preserves conflicting anyOf default errors at build time', t => { + const schema = { + type: 'object', + properties: { + value: { anyOf: [{ type: 'integer', default: 2 }, { type: 'null' }], default: 1 } + } + } + t.plan(2) + const expected = run(() => build(schema)) + t.assert.match(expected.err, /Failed to merge "default" keyword schemas/) + t.assert.deepStrictEqual(run(() => build(schema, { objectMechanism: 'native' })), expected) +}) + +test('native mechanism falls back when nullable anyOf cannot be projected faithfully', t => { + const nullable = { anyOf: [{ type: 'null' }, { type: 'string' }] } + const cases = [ + [{ anyOf: [{ type: 'null' }, { type: 'string' }, { type: 'boolean' }] }, true], + [{ anyOf: [true, { type: 'null' }] }, true], + [{ anyOf: [{ type: 'number' }, { type: 'string' }] }, 4], + [{ anyOf: [{ type: 'null' }, { type: 'object', properties: { name: { type: 'string' } } }] }, { name: 'A' }], + [{ anyOf: [{ type: 'null' }, { type: 'string', const: 'A' }] }, 'A'], + [{ anyOf: [{ type: 'null' }, { type: 'string', format: 'unsafe' }] }, 'unsafe'], + [{ anyOf: [{ type: 'null' }, { type: 'string', anyOf: [{ type: 'string' }] }] }, 'A'], + [{ anyOf: [{ type: 'null' }, { $ref: '#/definitions/text' }] }, 'A'], + [{ ...nullable, title: 'Has siblings' }, 'A'] + ] + t.plan(cases.length * 2 + 8) + for (const [valueSchema, value] of cases) { + const schema = { + type: 'object', + definitions: { text: { type: 'string' } }, + properties: { value: valueSchema } + } + const debug = build(schema, { objectMechanism: 'native', mode: 'debug' }) + t.assert.doesNotMatch(debug.code, /asStringValue/) + t.assert.deepStrictEqual(run(fjs.restore(debug), { value }), run(build(schema), { value })) + } + + for (const value of [nullable, { type: 'string' }]) { + const array = { type: 'array', items: value } + const debugArray = build(array, { + objectMechanism: 'native', + mode: 'debug', + largeArrayMechanism: 'json-stringify', + largeArraySize: 1 + }) + t.assert.doesNotMatch(debugArray.code, /asStringValue/) + t.assert.equal(fjs.restore(debugArray)([true]), '[true]') + + const indexed = { type: 'object', properties: { 0: { type: 'integer' }, value }, required: ['value'] } + const debugIndexed = build(indexed, { objectMechanism: 'native', mode: 'debug' }) + t.assert.doesNotMatch(debugIndexed.code, /asStringValue/) + t.assert.equal(fjs.restore(debugIndexed)({ 0: 1, value: 'A' }), '{"value":"A","0":1}') + } +}) + test('native mechanism: Date values match the default mechanism', t => { const schema = { type: 'object', @@ -635,6 +782,29 @@ test('native mechanism works in standalone mode', t => { t.assert.equal(stringify({ a: 'x', n: 1.5, extra: true }), '{"a":"x","n":1.5}') }) +test('native mechanism restores standalone nullable anyOf through a reference', t => { + const fs = require('node:fs') + const path = require('node:path') + const schema = { + type: 'object', + definitions: { value: { anyOf: [{ type: 'string', pattern: '^[A-Z]+$' }, { type: 'null' }] } }, + properties: { value: { $ref: '#/definitions/value' } } + } + const dir = fs.mkdtempSync(path.resolve('test/fixtures', 'nullable-anyof-')) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + t.plan(8) + for (const inlineValidators of [true, false]) { + const file = path.join(dir, `standalone-${inlineValidators}.js`) + const code = build(schema, { objectMechanism: 'native', mode: 'standalone', inlineValidators }) + fs.writeFileSync(file, code) + const stringify = require(file) + t.assert.match(code, /asStringValue/) + t.assert.equal(stringify({ value: 'ABC' }), '{"value":"ABC"}') + t.assert.equal(stringify({ value: null }), '{"value":null}') + t.assert.deepStrictEqual(run(stringify, { value: 'a' }), run(build(schema), { value: 'a' })) + } +}) + test('native mechanism: required keys not declared in properties still throw', t => { const schema = { type: 'object', required: ['id', 'token'], properties: { id: { type: 'integer' } } } const def = build(schema)