|
| 1 | +import { isRecordLike, toRecord } from '@sim/utils/object' |
| 2 | +import { z } from 'zod' |
| 3 | + |
| 4 | +/** |
| 5 | + * TypeScript types for the JSON Schema `z.toJSONSchema` produces from the route |
| 6 | + * contracts. The Sim CLI generator and the MCP server's `describe_operation` |
| 7 | + * both render contract types through this one emitter, so the terminal and an |
| 8 | + * agent read the same shape for the same operation. |
| 9 | + * |
| 10 | + * Imports no `@/` paths: the root CLI generator imports it by relative path. |
| 11 | + */ |
| 12 | + |
| 13 | +type JsonSchema = Record<string, unknown> |
| 14 | + |
| 15 | +const ANNOTATION_KEYS: ReadonlySet<string> = new Set([ |
| 16 | + '$schema', |
| 17 | + 'description', |
| 18 | + 'title', |
| 19 | + 'default', |
| 20 | + 'examples', |
| 21 | +]) |
| 22 | + |
| 23 | +function schemaList(value: unknown): JsonSchema[] | undefined { |
| 24 | + return Array.isArray(value) ? value.filter(isRecordLike) : undefined |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Hand-rolled rather than pulled from `json-schema-to-typescript`: the input is |
| 29 | + * a known, narrow subset (no `patternProperties`, no draft-04 quirks), and the |
| 30 | + * output is read by humans and models, so controlling the formatting is worth |
| 31 | + * more than covering spec corners that never appear. An unhandled construct |
| 32 | + * throws rather than degrading to `any`: silence is how a generated client |
| 33 | + * drifts from its server. |
| 34 | + * |
| 35 | + * `refs` maps a `$defs` key to the alias hoisted for it. Zod factors a schema |
| 36 | + * out into `$defs` when it is recursive, which the table filter grammar is. |
| 37 | + */ |
| 38 | +function toTypeScript(schema: JsonSchema, indent: number, refs?: Map<string, string>): string { |
| 39 | + if (typeof schema.$ref === 'string') { |
| 40 | + const name = refs?.get(schema.$ref.replace('#/$defs/', '')) |
| 41 | + if (!name) throw new Error(`Unresolved $ref: ${schema.$ref}`) |
| 42 | + return name |
| 43 | + } |
| 44 | + |
| 45 | + const pad = ' '.repeat(indent + 1) |
| 46 | + const closePad = ' '.repeat(indent) |
| 47 | + |
| 48 | + if (schema.const !== undefined) return JSON.stringify(schema.const) |
| 49 | + if (Array.isArray(schema.enum)) return schema.enum.map((v) => JSON.stringify(v)).join(' | ') |
| 50 | + |
| 51 | + const variants = schemaList(schema.anyOf) ?? schemaList(schema.oneOf) |
| 52 | + if (variants) return variants.map((v) => toTypeScript(v, indent, refs)).join(' | ') |
| 53 | + |
| 54 | + const parts = schemaList(schema.allOf) |
| 55 | + if (parts) { |
| 56 | + return parts |
| 57 | + .map((part) => { |
| 58 | + const type = toTypeScript(part, indent, refs) |
| 59 | + return schemaList(part.anyOf) || schemaList(part.oneOf) || Array.isArray(part.enum) |
| 60 | + ? `(${type})` |
| 61 | + : type |
| 62 | + }) |
| 63 | + .join(' & ') |
| 64 | + } |
| 65 | + |
| 66 | + switch (schema.type) { |
| 67 | + case 'string': |
| 68 | + return 'string' |
| 69 | + case 'number': |
| 70 | + case 'integer': |
| 71 | + return 'number' |
| 72 | + case 'boolean': |
| 73 | + return 'boolean' |
| 74 | + case 'null': |
| 75 | + return 'null' |
| 76 | + case 'array': { |
| 77 | + const tuple = schemaList(schema.prefixItems) |
| 78 | + const rest = isRecordLike(schema.items) ? toTypeScript(schema.items, indent, refs) : null |
| 79 | + if (tuple) { |
| 80 | + const elements = tuple.map((item) => toTypeScript(item, indent, refs)) |
| 81 | + if (rest) elements.push(`...Array<${rest}>`) |
| 82 | + return `[${elements.join(', ')}]` |
| 83 | + } |
| 84 | + return rest ? `Array<${rest}>` : 'unknown[]' |
| 85 | + } |
| 86 | + case 'object': { |
| 87 | + const properties = toRecord(schema.properties) |
| 88 | + const required = Array.isArray(schema.required) ? schema.required : [] |
| 89 | + const keys = Object.keys(properties) |
| 90 | + |
| 91 | + if (keys.length === 0) { |
| 92 | + if (schema.additionalProperties === false) return 'Record<string, never>' |
| 93 | + const value = isRecordLike(schema.additionalProperties) |
| 94 | + ? toTypeScript(schema.additionalProperties, indent, refs) |
| 95 | + : 'unknown' |
| 96 | + return `Record<string, ${value}>` |
| 97 | + } |
| 98 | + |
| 99 | + const types: string[] = [] |
| 100 | + const lines = keys.map((key) => { |
| 101 | + const property = properties[key] |
| 102 | + const optional = required.includes(key) ? '' : '?' |
| 103 | + const safeKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key) |
| 104 | + const type = isRecordLike(property) ? toTypeScript(property, indent + 1, refs) : 'unknown' |
| 105 | + types.push(optional ? `${type} | undefined` : type) |
| 106 | + return `${pad}${safeKey}${optional}: ${type}` |
| 107 | + }) |
| 108 | + // Extra keys are allowed; an index signature must also cover the named properties' types. |
| 109 | + if (isRecordLike(schema.additionalProperties)) { |
| 110 | + const extra = toTypeScript(schema.additionalProperties, indent + 1, refs) |
| 111 | + const value = extra === 'unknown' ? extra : [...new Set([extra, ...types])].join(' | ') |
| 112 | + lines.push(`${pad}[key: string]: ${value}`) |
| 113 | + } |
| 114 | + return `{\n${lines.join('\n')}\n${closePad}}` |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // `z.unknown()` renders as a schema with no constraints; `.describe()` adds |
| 119 | + // annotation keys without narrowing the type. |
| 120 | + if (Object.keys(schema).every((key) => ANNOTATION_KEYS.has(key))) return 'unknown' |
| 121 | + |
| 122 | + throw new Error(`Unhandled JSON Schema construct: ${JSON.stringify(schema).slice(0, 200)}`) |
| 123 | +} |
| 124 | + |
| 125 | +/** `listTables` → `ListTables`: how generated type aliases are named after an operation or slot. */ |
| 126 | +export function pascal(name: string): string { |
| 127 | + return name.charAt(0).toUpperCase() + name.slice(1) |
| 128 | +} |
| 129 | + |
| 130 | +/** A type plus the aliases that must be declared before it. */ |
| 131 | +interface GeneratedType { |
| 132 | + type: string |
| 133 | + declarations: string[] |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Renders JSON Schema as a TypeScript type. A recursive schema cannot be |
| 138 | + * written inline, so its `$defs` become aliases named `${name}Ref<n>`, after |
| 139 | + * the owning type so two operations' aliases cannot collide. |
| 140 | + */ |
| 141 | +export function jsonSchemaToTypeScript(schema: JsonSchema, name: string): GeneratedType { |
| 142 | + const { $defs, ...root } = schema |
| 143 | + if (!isRecordLike($defs)) return { type: toTypeScript(root, 0), declarations: [] } |
| 144 | + |
| 145 | + const refs = new Map(Object.keys($defs).map((key, index) => [key, `${name}Ref${index}`])) |
| 146 | + const declarations = Object.entries($defs).map( |
| 147 | + ([key, def]) => |
| 148 | + `type ${refs.get(key)} = ${isRecordLike(def) ? toTypeScript(def, 0, refs) : 'unknown'}\n` |
| 149 | + ) |
| 150 | + return { type: toTypeScript(root, 0, refs), declarations } |
| 151 | +} |
| 152 | + |
| 153 | +/** |
| 154 | + * A contract schema as JSON Schema, the way it crosses the wire: a date is the |
| 155 | + * ISO string JSON carries, rather than the unconstrained schema Zod falls back |
| 156 | + * to for a type JSON Schema cannot represent. |
| 157 | + */ |
| 158 | +export function contractJsonSchema(schema: z.ZodType, io: 'input' | 'output'): JsonSchema { |
| 159 | + return z.toJSONSchema(schema, { |
| 160 | + io, |
| 161 | + unrepresentable: 'any', |
| 162 | + override: ({ zodSchema, jsonSchema }) => { |
| 163 | + if (zodSchema._zod.def.type === 'date') { |
| 164 | + jsonSchema.type = 'string' |
| 165 | + jsonSchema.format = 'date-time' |
| 166 | + } |
| 167 | + }, |
| 168 | + }) as JsonSchema |
| 169 | +} |
| 170 | + |
| 171 | +/** Renders a contract schema as a TypeScript type; see {@link jsonSchemaToTypeScript}. */ |
| 172 | +export function schemaToTypeScript( |
| 173 | + schema: z.ZodType, |
| 174 | + io: 'input' | 'output', |
| 175 | + name: string |
| 176 | +): GeneratedType { |
| 177 | + return jsonSchemaToTypeScript(contractJsonSchema(schema, io), name) |
| 178 | +} |
| 179 | + |
| 180 | +/** |
| 181 | + * Whether a request part must be sent: its object requires a field, or every |
| 182 | + * branch of its union does. |
| 183 | + */ |
| 184 | +export function isJsonSchemaRequired(schema: JsonSchema, defs = toRecord(schema.$defs)): boolean { |
| 185 | + if (typeof schema.$ref === 'string') { |
| 186 | + const target = defs[schema.$ref.replace('#/$defs/', '')] |
| 187 | + return isRecordLike(target) && isJsonSchemaRequired(target, defs) |
| 188 | + } |
| 189 | + if (Array.isArray(schema.required) && schema.required.length > 0) return true |
| 190 | + const variants = schemaList(schema.anyOf) ?? schemaList(schema.oneOf) |
| 191 | + if (variants) return variants.every((variant) => isJsonSchemaRequired(variant, defs)) |
| 192 | + const parts = schemaList(schema.allOf) |
| 193 | + return parts ? parts.some((part) => isJsonSchemaRequired(part, defs)) : false |
| 194 | +} |
0 commit comments