Open History to see the last commit
1/**
2 * Dependency-free JSON Schema → TypeScript emitter (PLAN.md task 12.1).
3 * Produces the self-contained module served by `?format=types` and written
4 * into user projects by the pull tooling: banner + exported `JsonSchema`
5 * alias + schema const + named type declarations ($defs become exported
6 * declarations, so circular refs are naturally legal).
7 *
8 * Output contract:
9 * - Deterministic — no timestamps; ETag is contentHash × TYPEGEN_VERSION ×
10 * optionalStyle × optional live-model-list key (overlay does not change
11 * the schema const or schema hash).
12 * - tsconfig-agnostic — declaration-only types, zero imports, zero runtime
13 * side effects beyond the pure schema const; `unknown` wherever `any`
14 * would appear.
15 * - Tree-shakeable — no barrel; every export is a pure const or a type.
16 */
17
18export const TYPEGEN_VERSION = 1
19
20export type OptionalStyle = 'exact' | 'undefined'
21
22export interface EmitInput {
23 provider: string
24 /** Public endpoint id, e.g. `v1/messages` or `chat/completions`. */
25 endpointId: string
26 kind: 'input' | 'output'
27 contentHash: string
28 schema: Record<string, unknown>
29 optionalStyle?: OptionalStyle
30 /** Canonical URL the schema was fetched from — printed in the banner. */
31 sourceUrl?: string
32 /**
33 * Live catalog ids. Input-only: when passed (even as `[]`), replaces
34 * the root `model` type with `"id" | … | ListedModelId<P>`. An empty
35 * list still emits `ListedModelId<P>` so arbitrary strings do not
36 * assign. The schema const stays the bundled schema. Omit (or pass on
37 * output) to keep the schema's own type.
38 */
39 modelIds?: Array<string>
40}
41
42type SchemaNode = Record<string, unknown>
43
44interface EmitCtx {
45 optionalStyle: OptionalStyle
46 /** `$ref` string (e.g. `#/$defs/Tool`) → emitted type name. */
47 refs: Map<string, string>
48 provider: string
49 modelIds: Array<string>
50 /** When true, the root `model` property is emitted as Known | ListedModelId. */
51 overlayModel: boolean
52}
53
54function isObject(value: unknown): value is SchemaNode {
55 return typeof value === 'object' && value !== null && !Array.isArray(value)
56}
57
58const IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/
59
60function pascal(text: string): string {
61 const name = text
62 .split(/[^A-Za-z0-9]+/)
63 .filter(Boolean)
64 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
65 .join('')
66 if (name === '') return 'Schema'
67 return /^[0-9]/.test(name) ? `_${name}` : name
68}
69
70function lowerFirst(name: string): string {
71 return name.charAt(0).toLowerCase() + name.slice(1)
72}
73
74/** JSDoc block from `description`/`deprecated`; empty string when neither. */
75function jsdoc(node: SchemaNode, indent: string): string {
76 const lines: Array<string> = []
77 if (typeof node.description === 'string' && node.description.trim() !== '') {
78 lines.push(...node.description.trim().split('\n'))
79 }
80 if (node.deprecated === true) lines.push('@deprecated')
81 if (lines.length === 0) return ''
82 const safe = lines.map((line) => line.replaceAll('*/', '*\\/'))
83 if (safe.length === 1) return `${indent}/** ${safe[0]} */\n`
84 const body = safe.map((line) => `${indent} * ${line}`.trimEnd()).join('\n')
85 return `${indent}/**\n${body}\n${indent} */\n`
86}
87
88function literalType(value: unknown): string {
89 switch (typeof value) {
90 case 'string':
91 return JSON.stringify(value)
92 case 'number':
93 case 'boolean':
94 return String(value)
95 default:
96 return value === null ? 'null' : 'unknown'
97 }
98}
99
100function union(members: Array<string>): string {
101 const unique = [...new Set(members)]
102 return unique.length === 0 ? 'unknown' : unique.join(' | ')
103}
104
105/** Parenthesize compound expressions before joining into a larger one. */
106function paren(expr: string): string {
107 return expr.includes(' | ') || expr.includes(' & ') ? `(${expr})` : expr
108}
109
110function typeExpr(node: unknown, ctx: EmitCtx, indent: string): string {
111 if (node === true || node === undefined) return 'unknown'
112 if (node === false) return 'never'
113 if (!isObject(node)) return 'unknown'
114
115 if (typeof node.$ref === 'string') {
116 return ctx.refs.get(node.$ref) ?? 'unknown'
117 }
118
119 let expr = coreExpr(node, ctx, indent)
120 // OpenAPI 3.0-style nullability.
121 if (node.nullable === true && expr !== 'null') {
122 expr = union([expr, 'null'])
123 }
124 return expr
125}
126
127function coreExpr(node: SchemaNode, ctx: EmitCtx, indent: string): string {
128 if (Array.isArray(node.enum) && node.enum.length > 0) {
129 return union(node.enum.map(literalType))
130 }
131 if ('const' in node) return literalType(node.const)
132
133 const parts: Array<string> = []
134 if (Array.isArray(node.allOf) && node.allOf.length > 0) {
135 parts.push(
136 ...node.allOf.map((branch) => paren(typeExpr(branch, ctx, indent))),
137 )
138 }
139 const variants = Array.isArray(node.anyOf)
140 ? node.anyOf
141 : Array.isArray(node.oneOf)
142 ? node.oneOf
143 : null
144 if (variants !== null && variants.length > 0) {
145 parts.push(
146 paren(union(variants.map((branch) => typeExpr(branch, ctx, indent)))),
147 )
148 }
149 const own = ownExpr(node, ctx, indent)
150 if (own !== null) parts.push(parts.length > 0 ? paren(own) : own)
151
152 const [first] = parts
153 if (first === undefined) return 'unknown'
154 return parts.length === 1 && first.startsWith('(')
155 ? first.slice(1, -1)
156 : parts.join(' & ')
157}
158
159/** The schema's own shape from `type`/`properties`/`items`; null if none. */
160function ownExpr(
161 node: SchemaNode,
162 ctx: EmitCtx,
163 indent: string,
164): string | null {
165 const type = node.type
166 if (Array.isArray(type)) {
167 return union(
168 type.map((member) => typeForName(node, String(member), ctx, indent)),
169 )
170 }
171 if (typeof type === 'string') return typeForName(node, type, ctx, indent)
172 if (isObject(node.properties) || 'additionalProperties' in node) {
173 return objectExpr(node, ctx, indent)
174 }
175 if ('items' in node || 'prefixItems' in node) {
176 return arrayExpr(node, ctx, indent)
177 }
178 return null
179}
180
181function typeForName(
182 node: SchemaNode,
183 type: string,
184 ctx: EmitCtx,
185 indent: string,
186): string {
187 switch (type) {
188 case 'string':
189 return 'string'
190 case 'number':
191 case 'integer':
192 return 'number'
193 case 'boolean':
194 return 'boolean'
195 case 'null':
196 return 'null'
197 case 'array':
198 return arrayExpr(node, ctx, indent)
199 case 'object':
200 return objectExpr(node, ctx, indent)
201 default:
202 return 'unknown'
203 }
204}
205
206function arrayExpr(node: SchemaNode, ctx: EmitCtx, indent: string): string {
207 const prefix = Array.isArray(node.prefixItems)
208 ? node.prefixItems
209 : Array.isArray(node.items)
210 ? node.items
211 : null
212 if (prefix !== null) {
213 const members = prefix.map((item) => typeExpr(item, ctx, indent))
214 const restSchema = Array.isArray(node.items)
215 ? node.additionalItems
216 : node.items
217 const closed = restSchema === false
218 const rest = closed
219 ? ''
220 : `, ...Array<${typeExpr(restSchema === true ? undefined : restSchema, ctx, indent)}>`
221 return `[${members.join(', ')}${rest}]`
222 }
223 return `Array<${typeExpr(node.items, ctx, indent)}>`
224}
225
226function objectExpr(node: SchemaNode, ctx: EmitCtx, indent: string): string {
227 const props = isObject(node.properties) ? node.properties : {}
228 const required = new Set(
229 Array.isArray(node.required)
230 ? node.required.filter((name) => typeof name === 'string')
231 : [],
232 )
233 const keys = Object.keys(props)
234 const additional = node.additionalProperties
235
236 if (keys.length === 0) {
237 if (isObject(additional)) {
238 return `Record<string, ${typeExpr(additional, ctx, indent)}>`
239 }
240 if (additional === false) return 'Record<string, never>'
241 return 'Record<string, unknown>'
242 }
243
244 const inner = `${indent} `
245 const members: Array<string> = []
246 for (const key of keys) {
247 const propSchema = props[key]
248 const docs = isObject(propSchema) ? jsdoc(propSchema, inner) : ''
249 const name = IDENT_RE.test(key) ? key : JSON.stringify(key)
250 const optional = !required.has(key)
251 const nested: EmitCtx = { ...ctx, overlayModel: false }
252 let expr =
253 ctx.overlayModel && key === 'model'
254 ? union([
255 ...ctx.modelIds.map((id) => JSON.stringify(id)),
256 `ListedModelId<${JSON.stringify(ctx.provider)}>`,
257 ])
258 : typeExpr(propSchema, nested, inner)
259 if (optional && ctx.optionalStyle === 'undefined') {
260 expr = union([expr, 'undefined'])
261 }
262 members.push(`${docs}${inner}${name}${optional ? '?' : ''}: ${expr}`)
263 }
264 // A named-property type can't carry a sound typed index signature, so an
265 // open object degrades to an unknown-valued one.
266 if (additional === true || isObject(additional)) {
267 members.push(`${inner}[key: string]: unknown`)
268 }
269 return `{\n${members.join('\n')}\n${indent}}`
270}
271
272/** Interface when the schema is a plain object with named properties (nicer
273 * hovers/extends); type alias for everything else. */
274function declaration(name: string, node: unknown, ctx: EmitCtx): string {
275 if (isObject(node)) {
276 const docs = jsdoc(node, '')
277 const isPlainObject =
278 !('$ref' in node) &&
279 !('enum' in node) &&
280 !('const' in node) &&
281 !('anyOf' in node) &&
282 !('oneOf' in node) &&
283 !('allOf' in node) &&
284 node.nullable !== true &&
285 (node.type === 'object' || node.type === undefined) &&
286 isObject(node.properties) &&
287 Object.keys(node.properties).length > 0
288 if (isPlainObject) {
289 return `${docs}export interface ${name} ${objectExpr(node, ctx, '')}\n`
290 }
291 return `${docs}export type ${name} = ${typeExpr(node, ctx, '')}\n`
292 }
293 return `export type ${name} = ${typeExpr(node, ctx, '')}\n`
294}
295
296export interface EmittedNames {
297 /** e.g. `anthropicV1MessagesRequestSchema` */
298 schemaConst: string
299 /** e.g. `AnthropicV1MessagesRequest` */
300 rootType: string
301}
302
303export function moduleNames(
304 provider: string,
305 endpointId: string,
306 kind: 'input' | 'output',
307): EmittedNames {
308 const kindLabel = kind === 'input' ? 'Request' : 'Response'
309 const rootType = pascal(provider) + pascal(endpointId) + kindLabel
310 return { rootType, schemaConst: `${lowerFirst(rootType)}Schema` }
311}
312
313/** ETag for a types response: schema hash × emitter version × optionalStyle
314 * × optional model-list key. */
315export function typesEtag(
316 contentHash: string,
317 optionalStyle: OptionalStyle,
318 modelKey?: string,
319): string {
320 const base = `${contentHash}-types-v${TYPEGEN_VERSION}-${optionalStyle}`
321 return modelKey !== undefined ? `${base}-m${modelKey}` : base
322}
323
324/** Short stable key of a live model-id list (ETag only; not the schema hash). */
325export function modelIdsKey(modelIds: Array<string>): string {
326 let hash = 2166136261
327 const text = [...modelIds].sort().join('\0')
328 for (let i = 0; i < text.length; i++) {
329 hash ^= text.charCodeAt(i)
330 hash = Math.imul(hash, 16777619)
331 }
332 return (hash >>> 0).toString(16).padStart(8, '0')
333}
334
335const LISTED_MODEL_ID_DECL = `export type ListedModelId<TProvider extends string = string> = string & {
336 readonly __modelschemasListed: TProvider
337}`
338
339/** Emit the full module text for one endpoint+kind schema. */
340export function emitTypesModule(input: EmitInput): string {
341 const optionalStyle = input.optionalStyle ?? 'exact'
342 const { rootType, schemaConst } = moduleNames(
343 input.provider,
344 input.endpointId,
345 input.kind,
346 )
347
348 const modelIds = [...(input.modelIds ?? [])].sort()
349 const overlayModel =
350 input.kind === 'input' &&
351 input.modelIds !== undefined &&
352 isObject(input.schema.properties) &&
353 'model' in input.schema.properties
354 const taken = new Set([
355 'JsonSchema',
356 rootType,
357 schemaConst,
358 ...(overlayModel ? ['ListedModelId'] : []),
359 ])
360 const refs = new Map<string, string>()
361 const defs: Array<{ name: string; node: unknown }> = []
362 for (const container of ['$defs', 'definitions'] as const) {
363 const block = input.schema[container]
364 if (!isObject(block)) continue
365 for (const key of Object.keys(block)) {
366 let name = pascal(key)
367 for (let suffix = 2; taken.has(name); suffix++) {
368 name = `${pascal(key)}${suffix}`
369 }
370 taken.add(name)
371 refs.set(`#/${container}/${key}`, name)
372 defs.push({ name, node: block[key] })
373 }
374 }
375
376 const ctx: EmitCtx = {
377 optionalStyle,
378 refs,
379 provider: input.provider,
380 modelIds,
381 overlayModel,
382 }
383 const banner = [
384 `// @generated by modelschemas typegen v${TYPEGEN_VERSION} — do not edit; refresh with \`modelschemas update\`.`,
385 `// provider: ${input.provider} · endpoint: ${input.endpointId} · kind: ${input.kind}`,
386 ...(input.sourceUrl !== undefined ? [`// source: ${input.sourceUrl}`] : []),
387 `// schema version: ${input.contentHash}`,
388 ].join('\n')
389
390 const sections = [
391 banner,
392 `export type JsonSchema = { readonly [key: string]: unknown }`,
393 ...(overlayModel ? [LISTED_MODEL_ID_DECL] : []),
394 `export const ${schemaConst}: JsonSchema = ${JSON.stringify(input.schema, null, 2)}`,
395 declaration(rootType, input.schema, ctx).trimEnd(),
396 ...defs.map(({ name, node }) =>
397 declaration(name, node, { ...ctx, overlayModel: false }).trimEnd(),
398 ),
399 ]
400 return `${sections.join('\n\n')}\n`
401}