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