FromJsonSchema: add additionalProperties to Objects node (#766)

This commit is contained in:
Giulio Canti
2025-12-02 17:24:46 +01:00
committed by GitHub
parent 79cf0a0a16
commit a1bcc0d90d
2 changed files with 115 additions and 94 deletions
+88 -92
View File
@@ -179,7 +179,7 @@ export function generate(schema: Schema.JsonSchema | boolean, options: GenerateO
inlineRefs: false,
refStack: emptySet
}
return toGeneration(parse(schema, recurOptions), recurOptions)
return parse(schema, recurOptions).toGeneration(recurOptions)
}
const defaultResolver: Resolver = (ref: string) => {
@@ -196,20 +196,8 @@ function renderJsDocs(annotations: Annotations, options: RecurOptions): string {
return options.extractJsDocs(annotations)
}
function toGeneration(ast: AST, options: RecurOptions): Generation {
const out = ast.toGeneration(options)
const checks = ast.renderChecks()
const annotations = renderAnnotations(ast)
return {
runtime: out.runtime + checks + annotations,
types: out.types,
annotations: out.annotations,
importDeclarations: out.importDeclarations
}
}
function renderAnnotations(ast: AST): string {
const entries = Object.entries(ast.annotations)
function renderAnnotations(annotations: Annotations): string {
const entries = Object.entries(annotations)
if (entries.length === 0) return ""
@@ -485,15 +473,13 @@ class Unknown {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(that: AST): AST {
return that
}
toGeneration(_: RecurOptions): Generation {
const suffix = renderAnnotations(this.annotations)
return {
runtime: "Schema.Unknown",
runtime: "Schema.Unknown" + suffix,
types: makeTypes("unknown"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -513,15 +499,13 @@ class Never {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(_: RecurOptions): Generation {
const suffix = renderAnnotations(this.annotations)
return {
runtime: "Schema.Never",
runtime: "Schema.Never" + suffix,
types: makeTypes("never"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -543,14 +527,11 @@ class Not {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(options: RecurOptions): Generation {
return toGeneration(new Never(this.annotations), options)
return new Never(this.annotations).toGeneration(options)
}
}
@@ -566,15 +547,13 @@ class Null {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(_: RecurOptions): Generation {
const suffix = renderAnnotations(this.annotations)
return {
runtime: "Schema.Null",
runtime: "Schema.Null" + suffix,
types: makeTypes("null"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -650,10 +629,11 @@ class String {
}
}
toGeneration(options: RecurOptions): Generation {
const suffix = this.renderChecks() + renderAnnotations(this.annotations)
if (this.contentSchema !== undefined) {
const contentSchema = toGeneration(this.contentSchema, options)
const contentSchema = this.contentSchema.toGeneration(options)
return {
runtime: `Schema.fromJsonString(${contentSchema.runtime})`,
runtime: `Schema.fromJsonString(${contentSchema.runtime + suffix})`,
types: makeTypes(
contentSchema.types.Type,
"string",
@@ -665,7 +645,7 @@ class String {
}
}
return {
runtime: "Schema.String",
runtime: "Schema.String" + suffix,
types: makeTypes("string"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -761,8 +741,9 @@ class Number {
}
}
toGeneration(_: RecurOptions): Generation {
const suffix = this.renderChecks() + renderAnnotations(this.annotations)
return {
runtime: this.isInteger ? "Schema.Int" : "Schema.Number",
runtime: (this.isInteger ? "Schema.Int" : "Schema.Number") + suffix,
types: makeTypes("number"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -782,15 +763,13 @@ class Boolean {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(_: RecurOptions): Generation {
const suffix = renderAnnotations(this.annotations)
return {
runtime: "Schema.Boolean",
runtime: "Schema.Boolean" + suffix,
types: makeTypes("boolean"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -812,15 +791,13 @@ class Const {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(_: RecurOptions): Generation {
const suffix = renderAnnotations(this.annotations)
return {
runtime: `Schema.Literal(${format(this.value)})`,
runtime: `Schema.Literal(${format(this.value)})` + suffix,
types: makeTypes(format(this.value)),
annotations: this.annotations,
importDeclarations: emptySet
@@ -842,24 +819,22 @@ class Enum {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(_: RecurOptions): Generation {
const values = this.values.map((v) => format(v))
const suffix = renderAnnotations(this.annotations)
if (values.length === 1) {
return {
runtime: `Schema.Literal(${values[0]})`,
runtime: `Schema.Literal(${values[0]})` + suffix,
types: makeTypes(values[0]),
annotations: this.annotations,
importDeclarations: emptySet
}
} else {
return {
runtime: `Schema.Literals([${values.join(", ")}])`,
runtime: `Schema.Literals([${values.join(", ")}])` + suffix,
types: makeTypes(values.join(" | ")),
annotations: this.annotations,
importDeclarations: emptySet
@@ -970,15 +945,17 @@ class Arrays {
}
toGeneration(options: RecurOptions): Generation {
const es = this.elements.map((e): ElementIR => ({
value: toGeneration(e.ast, options),
value: e.ast.toGeneration(options),
isOptional: e.isOptional
}))
const rest = this.rest !== undefined ? toGeneration(this.rest, options) : undefined
const rest = this.rest !== undefined ? this.rest.toGeneration(options) : undefined
const el = renderElements(es)
const suffix = this.renderChecks() + renderAnnotations(this.annotations)
if (es.length === 0 && rest === undefined) {
return {
runtime: `Schema.Tuple([])`,
runtime: `Schema.Tuple([])` + suffix,
types: makeTypes("readonly []"),
annotations: this.annotations,
importDeclarations: emptySet
@@ -987,7 +964,7 @@ class Arrays {
if (es.length === 0 && rest !== undefined) {
return {
runtime: `Schema.Array(${rest.runtime})`,
runtime: `Schema.Array(${rest.runtime})` + suffix,
types: makeTypes(
`ReadonlyArray<${rest.types.Type}>`,
`ReadonlyArray<${rest.types.Encoded}>`,
@@ -1001,7 +978,7 @@ class Arrays {
if (rest === undefined) {
return {
runtime: `Schema.Tuple([${el.runtime}])`,
runtime: `Schema.Tuple([${el.runtime}])` + suffix,
types: makeTypes(
`readonly [${el.types.Type}]`,
`readonly [${el.types.Encoded}]`,
@@ -1014,7 +991,7 @@ class Arrays {
}
return {
runtime: `Schema.TupleWithRest(Schema.Tuple([${el.runtime}]), [${rest.runtime}])`,
runtime: `Schema.TupleWithRest(Schema.Tuple([${el.runtime}]), [${rest.runtime}])` + suffix,
types: makeTypes(
`readonly [${el.types.Type}, ...Array<${rest.types.Type}>]`,
`readonly [${el.types.Encoded}, ...Array<${rest.types.Encoded}>]`,
@@ -1098,16 +1075,19 @@ class Objects {
readonly _tag = "Objects"
readonly properties: ReadonlyArray<Property>
readonly indexSignatures: ReadonlyArray<IndexSignature>
readonly additionalProperties: boolean
readonly checks: ReadonlyArray<ObjectsCheck>
readonly annotations: Annotations
constructor(
properties: ReadonlyArray<Property>,
indexSignatures: ReadonlyArray<IndexSignature>,
additionalProperties: boolean,
checks: ReadonlyArray<ObjectsCheck>,
annotations: Annotations = {}
) {
this.properties = properties
this.indexSignatures = indexSignatures
this.additionalProperties = additionalProperties
this.checks = checks
this.annotations = annotations
}
@@ -1115,6 +1095,7 @@ class Objects {
return new Objects(
this.properties,
this.indexSignatures,
this.additionalProperties,
this.checks,
annotationsCombiner.combine(this.annotations, annotations)
)
@@ -1123,6 +1104,7 @@ class Objects {
return new Objects(
this.properties,
this.indexSignatures,
this.additionalProperties,
[...this.checks, ...Objects.parseChecks(f)],
this.annotations
)
@@ -1143,6 +1125,7 @@ class Objects {
return new Objects(
this.properties,
this.indexSignatures,
this.additionalProperties,
this.checks,
annotationsCombiner.combine(this.annotations, that.annotations)
)
@@ -1150,6 +1133,7 @@ class Objects {
return new Objects(
this.properties.concat(that.properties),
this.indexSignatures.concat(that.indexSignatures),
this.additionalProperties && that.additionalProperties,
[...this.checks, ...that.checks],
annotationsCombiner.combine(this.annotations, that.annotations)
)
@@ -1164,25 +1148,47 @@ class Objects {
}
}
toGeneration(options: RecurOptions): Generation {
if (this.properties.length === 0 && this.indexSignatures.length === 0) {
if (this.additionalProperties === false) {
return new Objects(
[],
[new IndexSignature(new String([], undefined), new Never())],
false,
this.checks,
this.annotations
).toGeneration(options)
} else {
return new Objects(
[],
[new IndexSignature(new String([], undefined), new Unknown())],
false,
this.checks,
this.annotations
).toGeneration(options)
}
}
const ps: ReadonlyArray<PropertyGen> = this.properties.map((p) => ({
key: p.key,
value: toGeneration(p.value, options),
value: p.value.toGeneration(options),
isOptional: p.isOptional,
annotations: p.value.annotations
}))
const iss: ReadonlyArray<IndexSignatureGen> = this.indexSignatures.map((is) => ({
key: toGeneration(is.key, options),
value: toGeneration(is.value, options)
key: is.key.toGeneration(options),
value: is.value.toGeneration(options)
}))
const p = renderProperties(ps, options)
const i = renderIndexSignatures(iss)
const suffix = this.renderChecks() + renderAnnotations(this.annotations)
// 1) Only properties -> Struct
if (iss.length === 0) {
return {
runtime: `Schema.Struct({ ${p.runtime} })`,
runtime: `Schema.Struct({ ${p.runtime} })` + suffix,
types: makeTypes(
`{ ${p.types.Type} }`,
`{ ${p.types.Encoded} }`,
@@ -1198,7 +1204,7 @@ class Objects {
if (ps.length === 0 && iss.length === 1) {
const is = iss[0]
return {
runtime: indexSignatureRuntime(is),
runtime: indexSignatureRuntime(is) + suffix,
types: makeTypes(
`{ ${renderIndexSignature(is.key.types.Type, is.value.types.Type)} }`,
`{ ${renderIndexSignature(is.key.types.Encoded, is.value.types.Encoded)} }`,
@@ -1212,7 +1218,7 @@ class Objects {
// 3) Properties + index signatures -> StructWithRest
return {
runtime: `Schema.StructWithRest(Schema.Struct({ ${p.runtime} }), [${i.runtime}])`,
runtime: `Schema.StructWithRest(Schema.Struct({ ${p.runtime} }), [${i.runtime}])` + suffix,
types: ps.length === 0
? makeTypes(
`{ ${i.types.Type} }`,
@@ -1311,9 +1317,6 @@ class Union {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(that: AST, options: RecurOptions): AST {
switch (that._tag) {
case "Unknown":
@@ -1340,13 +1343,14 @@ class Union {
}
}
toGeneration(options: RecurOptions): Generation {
const members = this.members.map((m) => toGeneration(m, options))
const members = this.members.map((m) => m.toGeneration(options))
const runtime = this.members.length === 2 && this.members[1]._tag === "Null" &&
Object.keys(this.members[1].annotations).length === 0 ?
`Schema.NullOr(${members[0].runtime})` :
`Schema.Union([${members.map((m) => m.runtime).join(", ")}]${this.mode === "oneOf" ? `, { mode: "oneOf" }` : ""})`
const suffix = renderAnnotations(this.annotations)
return {
runtime,
runtime: runtime + suffix,
types: makeTypes(
members.map((m) => m.types.Type).join(" | "),
members.map((m) => m.types.Encoded).join(" | "),
@@ -1373,19 +1377,17 @@ class Reference {
parseChecks(_: Schema.JsonSchema): AST {
return this
}
renderChecks(): string {
return ""
}
combine(_: AST): AST {
return new Never()
}
toGeneration(options: RecurOptions): Generation {
const generation = options.resolver(this.ref)
const out = options.resolver(this.ref)
const suffix = renderAnnotations(this.annotations)
return {
runtime: generation.runtime,
types: generation.types,
annotations: this.annotations,
importDeclarations: generation.importDeclarations
runtime: out.runtime + suffix,
types: out.types,
annotations: annotationsCombiner.combine(this.annotations, out.annotations),
importDeclarations: out.importDeclarations
}
}
}
@@ -1575,17 +1577,18 @@ function handleType(type: Schema.JsonSchema.Type, schema: Schema.JsonSchema, opt
case "object": {
const properties = collectProperties(schema, options)
const indexSignatures = collectIndexSignatures(schema, options)
return new Objects(properties, indexSignatures, [])
const additionalProperties = schema.additionalProperties === false ? false : true
return new Objects(properties, indexSignatures, additionalProperties, [])
}
case "array": {
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0
const elements = collectElements(schema, options)?.map((item, index): Element =>
const elements = collectElements(schema, options).map((item, index): Element =>
new Element(index + 1 > minItems, parse(item, options))
)
const rest = collectRest(schema, options)
return new Arrays(
elements ?? [],
elements,
rest !== undefined ? rest === false ? undefined : parse(rest, options) : new Unknown(),
[]
)
@@ -1604,12 +1607,12 @@ function collectProperties(schema: Schema.JsonSchema, options: RecurOptions): Ar
}
function collectIndexSignatures(schema: Schema.JsonSchema, options: RecurOptions): Array<IndexSignature> {
if (isObject(schema.propertyNames)) {
return [new IndexSignature(parse(schema.propertyNames, options), new Unknown())]
}
const out: Array<IndexSignature> = []
if (isObject(schema.propertyNames)) {
out.push(new IndexSignature(parse(schema.propertyNames, options), new Unknown()))
}
if (isObject(schema.patternProperties)) {
for (const [pattern, value] of Object.entries(schema.patternProperties)) {
out.push(
@@ -1621,30 +1624,23 @@ function collectIndexSignatures(schema: Schema.JsonSchema, options: RecurOptions
}
}
const hasNoProps = schema.properties === undefined ||
(isObject(schema.properties) && Object.keys(schema.properties).length === 0)
if (schema.additionalProperties === true || schema.additionalProperties === undefined) {
out.push(new IndexSignature(new String([], undefined), new Unknown()))
} else if (isObject(schema.additionalProperties)) {
if (isObject(schema.additionalProperties)) {
out.push(new IndexSignature(new String([], undefined), parse(schema.additionalProperties, options)))
} else if (schema.additionalProperties === false && hasNoProps && out.length === 0) {
out.push(new IndexSignature(new String([], undefined), new Never()))
}
return out
}
function collectElements(schema: Schema.JsonSchema, options: RecurOptions): ReadonlyArray<unknown> | undefined {
function collectElements(schema: Schema.JsonSchema, options: RecurOptions): ReadonlyArray<unknown> {
switch (options.source) {
case "draft-07":
return Array.isArray(schema.items) ? schema.items : undefined
return Array.isArray(schema.items) ? schema.items : []
case "draft-2020-12":
case "openapi-3.1":
return Array.isArray(schema.prefixItems) ? schema.prefixItems : undefined
return Array.isArray(schema.prefixItems) ? schema.prefixItems : []
case "openapi-3.0":
// no tuples in OpenAPI 3.0 spec, keep undefined
return undefined
return []
}
}
@@ -967,14 +967,25 @@ describe("FromJsonSchema", () => {
)
)
assertGeneration(
{ schema: { "type": "object", "properties": {} } },
{
schema: {
"type": "object",
"properties": {}
}
},
FromJsonSchema.makeGeneration(
"Schema.Record(Schema.String, Schema.Unknown)",
FromJsonSchema.makeTypes("{ readonly [x: string]: unknown }")
)
)
assertGeneration(
{ schema: { "type": "object", "properties": {}, "additionalProperties": false } },
{
schema: {
"type": "object",
"properties": {},
"additionalProperties": false
}
},
FromJsonSchema.makeGeneration(
"Schema.Record(Schema.String, Schema.Never)",
FromJsonSchema.makeTypes("{ readonly [x: string]: never }")
@@ -1625,6 +1636,20 @@ describe("FromJsonSchema", () => {
{ description: "lorem" }
)
)
assertGeneration(
{
schema: {
"type": "object",
"minProperties": 1,
"allOf": [{ "description": "lorem" }]
}
},
FromJsonSchema.makeGeneration(
`Schema.Record(Schema.String, Schema.Unknown).check(Schema.isMinProperties(1)).annotate({ "description": "lorem" })`,
FromJsonSchema.makeTypes("{ readonly [x: string]: unknown }"),
{ description: "lorem" }
)
)
})
it("struct & struct", () => {