From a15be02e9810e9d255c25d119bcd33712baf3377 Mon Sep 17 00:00:00 2001 From: David Blass Date: Tue, 13 Oct 2026 11:41:06 -0400 Subject: [PATCH] fix(schema): convert what JSON Schema can't represent in ~standard.jsonSchema instead of throwing Standard JSON Schema converters now throw if and only if an option is unsupported, like a target other than draft-2020-12 or draft-07, and convert unknown or unrepresentable data to {}. That is the contract Standard Tool builds on: a tool's input schema is what a model is shown, so a converter that throws on a narrow or a bigint key leaves a tool that can't be described at all. Where JSON Schema can't represent part of a type, ~standard.jsonSchema keeps the part it can: - a predicate, a second pattern, a Date bound or an array's non-index props is dropped from the schema it constrains - bigint, symbol, a non-JSON unit like undefined and any prototype other than Array become {} - a variadic tuple with postfix elements keeps its prefix and minItems, but not its items - a default that isn't JSON is omitted Only the default fallbacks, which throw, are replaced, so fallbacks from the scope's toJsonSchema config or from libraryOptions still win. toJsonSchema() itself still throws by default. A defaultValue fallback can now return undefined to omit the default, rather than writing default: undefined. Co-Authored-By: Claude Opus 5.5 (1M context) --- ark/schema/roots/root.ts | 34 +++++++----- ark/schema/shared/toJsonSchema.ts | 24 ++++++++- ark/schema/structure/sequence.ts | 3 +- ark/schema/structure/structure.ts | 3 +- ark/type/__tests__/standardSchema.test.ts | 64 +++++++++++++++++++++++ 5 files changed, 112 insertions(+), 16 deletions(-) diff --git a/ark/schema/roots/root.ts b/ark/schema/roots/root.ts index af07982596..fb834705ee 100644 --- a/ark/schema/roots/root.ts +++ b/ark/schema/roots/root.ts @@ -52,7 +52,7 @@ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "../shared/standardSchema.ts" -import type { ToJsonSchema } from "../shared/toJsonSchema.ts" +import { ToJsonSchema } from "../shared/toJsonSchema.ts" import { arkKind, hasArkKind } from "../shared/utils.ts" import { assertDefaultValueAssignability } from "../structure/optional.ts" import type { Prop } from "../structure/prop.ts" @@ -108,16 +108,8 @@ export abstract class BaseRoot< return { value: out } }, jsonSchema: { - input: opts => - this.rawIn.toJsonSchema({ - target: validateStandardJsonSchemaTarget(opts.target), - ...opts.libraryOptions - }) as never, - output: opts => - this.rawOut.toJsonSchema({ - target: validateStandardJsonSchemaTarget(opts.target), - ...opts.libraryOptions - }) as never + input: opts => toStandardJsonSchema(this.rawIn, opts), + output: opts => toStandardJsonSchema(this.rawOut, opts) } } } @@ -211,7 +203,7 @@ export abstract class BaseRoot< // metaJson serializes non-primitives like [5] to references like // "$ark.array1", so prefer the original value when it is valid JSON // (jsonData's object domain also allows functions, so exclude them) - result[k] = + const jsonValue = typeof v !== "function" && $ark.intrinsic.jsonData.allows(v) ? v : k === "default" ? ctx.fallback.defaultValue({ @@ -220,6 +212,7 @@ export abstract class BaseRoot< value: v as never }) : (this.metaJson as dict)[k] + if (jsonValue !== undefined) result[k] = jsonValue } return result @@ -732,6 +725,23 @@ const validateStandardJsonSchemaTarget = ( return target } +const toStandardJsonSchema = ( + node: BaseRoot, + opts: StandardJSONSchemaV1.Options +): Record => { + const ctx = mergeToJsonSchemaConfigs(node.$.resolvedConfig.toJsonSchema, { + target: validateStandardJsonSchemaTarget(opts.target), + ...opts.libraryOptions + }) + const fallback = flatMorph(ctx.fallback, (code, handler) => [ + code, + handler === ToJsonSchema.defaultConfig.fallback[code] ? + ToJsonSchema.standardFallback[code] + : handler + ]) as ToJsonSchema.HandlerByCode + return node.toJsonSchema({ ...ctx, fallback }) as never +} + export const exclusivizeRangeSchema = ( schema: schema ): schema => diff --git a/ark/schema/shared/toJsonSchema.ts b/ark/schema/shared/toJsonSchema.ts index f240a0cada..ac95763799 100644 --- a/ark/schema/shared/toJsonSchema.ts +++ b/ark/schema/shared/toJsonSchema.ts @@ -51,6 +51,24 @@ const defaultConfig: ToJsonSchema.Context = { } } +// Standard JSON Schema converters only throw for unsupported options, so +// these keep the part of a type JSON Schema can represent, or {} if none +const standardFallback: ToJsonSchema.HandlerByCode = { + arrayObject: ctx => ctx.base, + // draft-07 tuples keep their prefix in items + arrayPostfix: ({ base: { items, additionalItems, ...base } }) => + (Array.isArray(items) ? { ...base, items } : base) as never, + defaultValue: () => undefined, + domain: ctx => ctx.base, + morph: ctx => ctx.base, + patternIntersection: ctx => ctx.base, + predicate: ctx => ctx.base, + proto: ctx => ctx.base, + symbolKey: ctx => ctx.base, + unit: ctx => ctx.base, + date: ctx => ctx.base +} + export const ToJsonSchema = { Error: ToJsonSchemaError, throw: (...args: ConstructorParameters): never => { @@ -63,7 +81,8 @@ export const ToJsonSchema = { throwInternalError( `Unexpected JSON Schema input for ${kind}: ${printable(schema)}` ), - defaultConfig + defaultConfig, + standardFallback } export declare namespace ToJsonSchema { @@ -175,7 +194,8 @@ export declare namespace ToJsonSchema { { arrayObject: (ctx: ArrayObjectContext) => JsonSchema.Structure arrayPostfix: (ctx: ArrayPostfixContext) => VariadicArraySchema - defaultValue: (ctx: DefaultValueContext) => JsonSchema + // undefined omits the default + defaultValue: (ctx: DefaultValueContext) => JsonSchema | undefined domain: (ctx: DomainContext) => JsonSchema morph: (ctx: MorphContext) => JsonSchema patternIntersection: ( diff --git a/ark/schema/structure/sequence.ts b/ark/schema/structure/sequence.ts index d945854236..2a94295b24 100644 --- a/ark/schema/structure/sequence.ts +++ b/ark/schema/structure/sequence.ts @@ -535,7 +535,7 @@ export class SequenceNode extends BaseConstraint { if (el.kind === "defaultables") { const value = typeof el.default === "function" ? el.default() : el.default - valueSchema.default = + const jsonDefault = $ark.intrinsic.jsonData.allows(value) ? value : ctx.fallback.defaultValue({ @@ -543,6 +543,7 @@ export class SequenceNode extends BaseConstraint { base: valueSchema, value }) + if (jsonDefault !== undefined) valueSchema.default = jsonDefault } return valueSchema }) diff --git a/ark/schema/structure/structure.ts b/ark/schema/structure/structure.ts index f14f4e83a9..e3c57317ad 100644 --- a/ark/schema/structure/structure.ts +++ b/ark/schema/structure/structure.ts @@ -839,7 +839,7 @@ export class StructureNode extends BaseConstraint { if (prop.hasDefault()) { const value = typeof prop.default === "function" ? prop.default() : prop.default - valueSchema.default = + const jsonDefault = $ark.intrinsic.jsonData.allows(value) ? value : ctx.fallback.defaultValue({ @@ -847,6 +847,7 @@ export class StructureNode extends BaseConstraint { base: valueSchema, value }) + if (jsonDefault !== undefined) valueSchema.default = jsonDefault } schema.properties![prop.key] = valueSchema diff --git a/ark/type/__tests__/standardSchema.test.ts b/ark/type/__tests__/standardSchema.test.ts index 9dcfaf29c9..a4e344a003 100644 --- a/ark/type/__tests__/standardSchema.test.ts +++ b/ark/type/__tests__/standardSchema.test.ts @@ -127,6 +127,70 @@ contextualize(() => { ).throws(writeInvalidJsonSchemaTargetMessage("openapi-3.0")) }) + it("converts what JSON Schema can't represent to {}", () => { + const T = type({ + big: "bigint", + date: "Date", + maybe: "string | undefined", + even: type("number").narrow(n => n % 2 === 0), + ends: ["...", "string[]", "number"], + count: ["bigint", "=", () => 0n] + }) + const standard: StandardJSONSchemaV1 = T + attest( + standard["~standard"].jsonSchema.input({ target: "draft-2020-12" }) + ).snap({ + $schema: "https://json-schema.org/draft/2020-12/schema", + type: "object", + properties: { + big: {}, + date: {}, + ends: { type: "array", minItems: 1 }, + even: { type: "number" }, + maybe: { anyOf: [{ type: "string" }, {}] }, + count: {} + }, + required: ["big", "date", "ends", "even", "maybe"] + }) + }) + + it("converts the output of a transform to {}", () => { + const T = type("string").pipe(s => s.length) + const standard: StandardJSONSchemaV1 = T + attest( + standard["~standard"].jsonSchema.output({ target: "draft-2020-12" }) + ).snap({ $schema: "https://json-schema.org/draft/2020-12/schema" }) + }) + + it("keeps a postfix tuple's draft-07 prefix", () => { + const T = type(["string", "...", "number[]", "boolean"]) + const standard: StandardJSONSchemaV1 = T + attest( + standard["~standard"].jsonSchema.input({ target: "draft-07" }) + ).snap({ + $schema: "http://json-schema.org/draft-07/schema#", + type: "array", + minItems: 2, + items: [{ type: "string" }] + }) + }) + + it("uses configured fallbacks", () => { + const T = type("bigint") + const standard: StandardJSONSchemaV1 = T + attest( + standard["~standard"].jsonSchema.input({ + target: "draft-2020-12", + libraryOptions: { + fallback: { domain: () => ({ type: "integer" }) } + } + }) + ).snap({ + $schema: "https://json-schema.org/draft/2020-12/schema", + type: "integer" + }) + }) + it("generates different input/output schemas for morphs", () => { const T = type({ foo: "string.numeric.parse" }) const standard: StandardJSONSchemaV1 = T