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
74 changes: 74 additions & 0 deletions src/lib/ajv-validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,77 @@ function deduplicateUnionErrors (errors: ValidationError[]): ValidationError[] {
)
}

interface SchemaNode {
type?: string | string[]
const?: unknown
enum?: unknown[]
anyOf?: SchemaNode[]
oneOf?: SchemaNode[]
$ref?: string
}

/** Follows same-document `$ref`s. External refs are left as-is. */
function derefNode (root: Record<string, unknown>, node: SchemaNode, seen: Set<string>): SchemaNode {
const ref = node.$ref
if (typeof ref !== 'string' || !ref.startsWith('#/$defs/')) return node
if (seen.has(ref)) return node
const defs = root['$defs']
if (defs == null || typeof defs !== 'object') return node
const target = (defs as Record<string, SchemaNode>)[ref.slice('#/$defs/'.length)]
if (target == null || typeof target !== 'object') return node
seen.add(ref)
return derefNode(root, target, seen)
}

/** What a schema node (and its union branches) accepts. */
function unionKinds (
root: Record<string, unknown>,
node: SchemaNode,
seen: Set<string>,
): { number: boolean, enum: boolean, freeString: boolean } {
const resolved = derefNode(root, node, seen)
const variants = resolved.anyOf ?? resolved.oneOf
if (variants != null && variants.length > 0) {
const acc = { number: false, enum: false, freeString: false }
for (const variant of variants) {
const part = unionKinds(root, variant, seen)
acc.number = acc.number || part.number
acc.enum = acc.enum || part.enum
acc.freeString = acc.freeString || part.freeString
}
return acc
}
const rawType = Array.isArray(resolved.type) ? resolved.type[0] : resolved.type
if (rawType === 'number' || rawType === 'integer' || typeof resolved.const === 'number') {
return { number: true, enum: false, freeString: false }
}
if (Array.isArray(resolved.enum) && resolved.enum.length > 0) {
return { number: false, enum: true, freeString: false }
}
if (rawType === 'string') return { number: false, enum: false, freeString: true }
return { number: false, enum: false, freeString: false }
}

// No leading zeros, no exponent. "01" and "1e2" stay strings.
const CANONICAL_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/

/**
* Turns a numeric string into a number when the property is a number-or-enum
* union (`slices`, `wait_for_active_shards`). A free string branch is left
* alone, so an index named "5" stays a string.
*/
function coerceNumericEnumUnions (schema: Record<string, unknown>, data: Record<string, unknown>): void {
const props = schema['properties']
if (props == null || typeof props !== 'object') return
for (const [key, prop] of Object.entries(props as Record<string, SchemaNode>)) {
const value = data[key]
if (typeof value !== 'string' || !CANONICAL_NUMBER.test(value)) continue
if (prop == null || typeof prop !== 'object') continue
const kinds = unionKinds(schema, prop, new Set())
if (kinds.number && kinds.enum && !kinds.freeString) data[key] = Number(value)
}
}

/**
* Validates `input` against a JSON Schema object.
*
Expand All @@ -172,6 +243,9 @@ export function validateWithJsonSchema (

// deep-clone input so defaults don't mutate the original object
const data = JSON.parse(JSON.stringify(input ?? {})) as Record<string, unknown>
if (data != null && typeof data === 'object' && !Array.isArray(data)) {
coerceNumericEnumUnions(compilable, data)
}
Comment on lines +246 to +248

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This adds a second union classifier. unionKinds/derefNode repeat what resolveType in src/lib/json-schema-args.ts already does for flags (anyOf/oneOf/$ref/const). If one of them changes, the other can drift, and the flag type and coercion rules would disagree.

I'd reuse the existing classification instead. For example, have resolveType report "number-or-enum, no free string" through a shared helper, and have coerceNumericEnumUnions call that helper rather than unionKinds.


const ajv = getAjv()
let validate: ValidateFunction
Expand Down
19 changes: 19 additions & 0 deletions test/factory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1878,6 +1878,25 @@ describe('defineCommand', () => {
assert.equal(input.size, 5)
})

it('coerces a numeric flag when the schema is a number or an enum', async () => {
const schema = jsonSchema({
slices: { anyOf: [{ type: 'number' }, { enum: ['auto'] }], 'x-found-in': 'query' },
})
const received: unknown[] = []
const cmd = defineCommand({
name: 'reindex',
description: 'Reindex',
input: schema,
handler: (parsed) => { received.push(parsed.input); return {} },
})
await invokeAsync(cmd, ['--slices', '5'])
assert.equal((received[0] as Record<string, unknown>).slices, 5)
await invokeAsync(cmd, ['--slices', 'auto'])
assert.equal((received[1] as Record<string, unknown>).slices, 'auto')
const err = await captureErrAsync(cmd, ['--slices', '../'])
assert.match(err, /input validation failed/)
})

it('accepts array-typed body fields with any valid JSON', async () => {
const schema = jsonSchema({
operations: { type: 'array', 'x-found-in': 'body' },
Expand Down
63 changes: 63 additions & 0 deletions test/lib/ajv-validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,3 +304,66 @@ describe('validateWithJsonSchema (ajv6 compile robustness) (#fix5)', () => {
}
})
})

describe('numeric string or enum unions', () => {
const slices = {
type: 'object',
properties: {
slices: {
anyOf: [{ type: 'number' }, { enum: ['auto'] }],
},
},
}

it('coerces a numeric string when the union is a number or an enum', () => {
const result = validateWithJsonSchema(slices, { slices: '5' })
assert.equal(result.success, true)
if (result.success) assert.equal(result.data['slices'], 5)
})

it('keeps the enum string', () => {
const result = validateWithJsonSchema(slices, { slices: 'auto' })
assert.equal(result.success, true)
if (result.success) assert.equal(result.data['slices'], 'auto')
})

it('follows a same-document $ref to the enum branch', () => {
const schema = {
type: 'object',
$defs: { Slices: { anyOf: [{ type: 'number' }, { $ref: '#/$defs/Auto' }] }, Auto: { enum: ['auto'] } },
properties: { slices: { $ref: '#/$defs/Slices' } },
}
const result = validateWithJsonSchema(schema, { slices: '5' })
assert.equal(result.success, true)
if (result.success) assert.equal(result.data['slices'], 5)
})

it('rejects a numeric string that is not a plain decimal', () => {
for (const value of ['5abc', '01', '1e2', '', '../', '?#']) {
const result = validateWithJsonSchema(slices, { slices: value })
assert.equal(result.success, false, value)
}
})

it('does not coerce a free string, including a numeric one', () => {
const schema = { type: 'object', properties: { index: { type: 'string' } } }
const result = validateWithJsonSchema(schema, { index: '5' })
assert.equal(result.success, true)
if (result.success) assert.equal(result.data['index'], '5')
})

it('does not coerce a duration string that also allows numeric consts', () => {
const schema = {
type: 'object',
properties: {
keep_alive: { anyOf: [{ type: 'string' }, { const: -1 }, { const: 0 }] },
},
}
const text = validateWithJsonSchema(schema, { keep_alive: '10s' })
assert.equal(text.success, true)
if (text.success) assert.equal(text.data['keep_alive'], '10s')
const numeric = validateWithJsonSchema(schema, { keep_alive: '-1' })
assert.equal(numeric.success, true)
if (numeric.success) assert.equal(numeric.data['keep_alive'], '-1')
})
})
Loading