Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 14 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
})
}
Expand Down Expand Up @@ -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}
}
`
Expand Down
83 changes: 65 additions & 18 deletions lib/projection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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') {
Expand All @@ -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) {
Expand All @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 + ' ')}`)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 ''
Expand All @@ -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 + '}'
Expand Down
Loading