2024/12/22 Valibot の intersect の JSON Schema が厳しすぎる
code:valibot.ts
import * as v from "valibot";
import { toJsonSchema } from "@valibot/to-json-schema";
const Intersect = v.intersect([
v.object({ foo: v.string() }),
v.object({ bar: v.number() }),
]);
console.log(v.safeParse(Intersect, { foo: "foo", bar: 42 }).success); // => true
console.log(v.safeParse(Intersect, { foo: "foo" }).success); // => false
console.log(JSON.stringify(toJsonSchema(Intersect), null, 2));
/*
{
"allOf": [
{
"type": "object",
"properties": {
"foo": {
"type": "string"
}
},
"required": [
"foo"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"bar": {
"type": "number"
}
},
"required": [
"bar"
],
"additionalProperties": false
}
]
}
*/
additonalProperties: false がそれぞれに含められて allOf だから満たしようがない
Issue 立てる
toJsonSchema generates unsatisfiable schema for intersect of objects
code:description.md
## Problem
When using toJsonSchema with intersect of objects, it generates a JSON Schema that cannot be satisfied due to conflicting additionalProperties: false constraints.
## Reproduction
`typescript
import { object, string, number, intersect } from 'valibot';
import { toJsonSchema } from '@valibot/json-schema';
const schema = intersect([
object({ foo: string() }),
object({ bar: number() }),
]);
console.log(JSON.stringify(toJsonSchema(schema), null, 2));
/*
Outputs:
{
"allOf": [
{
"type": "object",
"properties": {
"foo": {
"type": "string"
}
},
"required": [
"foo"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"bar": {
"type": "number"
}
},
"required": [
"bar"
],
"additionalProperties": false
}
]
}
*/
`
## Current Behavior
The generated JSON Schema includes additionalProperties: false for each object in allOf, making it impossible to satisfy both constraints simultaneously.
## Expected Behavior
The generated JSON Schema should allow objects that have both properties, matching Valibot's runtime validation behavior.
Possible solutions:
- Remove additionalProperties: false from individual objects in allOf
- Add additionalProperties: false only at the parent level
### versions
`
$ npm list | grep valibot
...
├── @valibot/to-json-schema@1.0.0-beta.3
└── valibot@1.0.0-beta.9
`