Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2
3import type { ListedModelId as ClientListedModelId } from '../../packages/client/src/listed-model.ts'
4import {
5 TYPEGEN_VERSION,
6 emitTypesModule,
7 modelIdsKey,
8 moduleNames,
9 typesEtag,
10} from './typegen.ts'
11
12type InlinedListedModelId<TProvider extends string = string> = string & {
13 readonly __modelschemasListed: TProvider
14}
15const clientBrandMatchesInline: ClientListedModelId<'anthropic'> =
16 '' as InlinedListedModelId<'anthropic'>
17
18/** Messages-shaped bundled schema exercising the emitter's full subset. */
19const fixture = {
20 type: 'object',
21 description: 'Create a message.',
22 required: ['model', 'messages', 'max_tokens'],
23 properties: {
24 model: { type: 'string', description: 'Model id, e.g. claude-sonnet-4-6.' },
25 max_tokens: { type: 'integer' },
26 temperature: { type: 'number', nullable: true },
27 stream: { type: 'boolean', default: false },
28 stop_sequences: { type: 'array', items: { type: 'string' } },
29 messages: { type: 'array', items: { $ref: '#/$defs/Message' } },
30 tool_choice: {
31 oneOf: [
32 { $ref: '#/$defs/ToolChoiceAuto' },
33 { $ref: '#/$defs/ToolChoiceTool' },
34 ],
35 },
36 metadata: {
37 type: 'object',
38 additionalProperties: { type: 'string' },
39 },
40 'odd-key': { const: 42 },
41 coords: {
42 type: 'array',
43 prefixItems: [{ type: 'number' }, { type: 'number' }],
44 items: false,
45 },
46 legacy: {
47 deprecated: true,
48 description: 'Ends with a tricky */ sequence.',
49 type: ['string', 'null'],
50 },
51 },
52 $defs: {
53 Message: {
54 type: 'object',
55 required: ['role', 'content'],
56 properties: {
57 role: { enum: ['user', 'assistant'] },
58 content: {
59 anyOf: [
60 { type: 'string' },
61 { type: 'array', items: { $ref: '#/$defs/ContentBlock' } },
62 ],
63 },
64 // Circular: a message can quote another message.
65 quoted: { $ref: '#/$defs/Message' },
66 },
67 },
68 ContentBlock: {
69 allOf: [
70 {
71 type: 'object',
72 required: ['type'],
73 properties: { type: { type: 'string' } },
74 },
75 { type: 'object', properties: { text: { type: 'string' } } },
76 ],
77 },
78 ToolChoiceAuto: {
79 type: 'object',
80 required: ['type'],
81 properties: { type: { const: 'auto' } },
82 additionalProperties: false,
83 },
84 ToolChoiceTool: {
85 type: 'object',
86 required: ['type', 'name'],
87 properties: { type: { const: 'tool' }, name: { type: 'string' } },
88 },
89 // Collides with the reserved alias name.
90 JsonSchema: { type: 'object', properties: { ok: { type: 'boolean' } } },
91 },
92} satisfies Record<string, unknown>
93
94function emitFixture(optionalStyle?: 'exact' | 'undefined') {
95 return emitTypesModule({
96 provider: 'anthropic',
97 endpointId: 'v1/messages',
98 kind: 'input',
99 contentHash: 'abc123def456',
100 schema: fixture,
101 optionalStyle,
102 sourceUrl:
103 'https://modelschemas.com/v1/schemas/anthropic/text/v1/messages?kind=input',
104 })
105}
106
107describe('emitTypesModule', () => {
108 it('emits the documented module shape', () => {
109 const source = emitFixture()
110 expect(source).toContain(
111 `@generated by modelschemas typegen v${TYPEGEN_VERSION}`,
112 )
113 expect(source).toContain('// schema version: abc123def456')
114 expect(source).toContain(
115 'export const anthropicV1MessagesRequestSchema: JsonSchema =',
116 )
117 expect(source).toContain('export interface AnthropicV1MessagesRequest {')
118 // Required vs optional, with exact style by default.
119 expect(source).toContain('model: string')
120 expect(source).toContain('temperature?: number | null')
121 // Enum union + const literal + quoted member names.
122 expect(source).toContain('role: "user" | "assistant"')
123 expect(source).toContain('"odd-key"?: 42')
124 // Tuple, typed record, $defs as exported declarations.
125 expect(source).toContain('coords?: [number, number]')
126 expect(source).toContain('metadata?: Record<string, string>')
127 expect(source).toContain('export interface Message {')
128 expect(source).toContain('quoted?: Message')
129 // allOf intersection, closed object.
130 expect(source).toContain('export type ContentBlock =')
131 expect(source).toContain('@deprecated')
132 // Zero imports, zero `any`.
133 expect(source).not.toMatch(/^import /m)
134 expect(source).not.toMatch(/: any\b/)
135 })
136
137 it('renames $defs that collide with reserved names', () => {
138 const source = emitFixture()
139 expect(source).toContain('export interface JsonSchema2 {')
140 expect(source).toContain('export type JsonSchema = ')
141 })
142
143 it('optionalStyle=undefined widens optional members', () => {
144 const source = emitFixture('undefined')
145 expect(source).toContain('stream?: boolean | undefined')
146 })
147
148 it('is deterministic', () => {
149 expect(emitFixture()).toBe(emitFixture())
150 })
151
152 it('handles boolean and ref-rooted schemas', () => {
153 const refRooted = emitTypesModule({
154 provider: 'openai',
155 endpointId: 'chat/completions',
156 kind: 'output',
157 contentHash: 'deadbeef',
158 schema: {
159 $ref: '#/$defs/Completion',
160 $defs: {
161 Completion: {
162 type: 'object',
163 required: ['id'],
164 properties: { id: { type: 'string' } },
165 },
166 },
167 },
168 })
169 expect(refRooted).toContain(
170 'export type OpenaiChatCompletionsResponse = Completion',
171 )
172 })
173
174 it('overlays model as Known | ListedModelId when modelIds are passed', () => {
175 const source = emitFixture()
176 expect(source).toContain('model: string')
177 expect(source).not.toContain('ListedModelId')
178 void clientBrandMatchesInline
179
180 const overlaid = emitTypesModule({
181 provider: 'anthropic',
182 endpointId: 'v1/messages',
183 kind: 'input',
184 contentHash: 'abc123def456',
185 schema: fixture,
186 modelIds: ['claude-sonnet-4-5', 'claude-opus-4-1'],
187 })
188 expect(overlaid).toContain('export type ListedModelId')
189 expect(overlaid).toContain(
190 'model: "claude-opus-4-1" | "claude-sonnet-4-5" | ListedModelId<"anthropic">',
191 )
192 expect(overlaid).not.toMatch(/^import /m)
193 expect(overlaid).toContain('"model": {\n "type": "string"')
194 })
195
196 it('overlays ListedModelId only when the catalog is empty', () => {
197 const overlaid = emitTypesModule({
198 provider: 'anthropic',
199 endpointId: 'v1/messages',
200 kind: 'input',
201 contentHash: 'abc123def456',
202 schema: fixture,
203 modelIds: [],
204 })
205 expect(overlaid).toContain('model: ListedModelId<"anthropic">')
206 expect(overlaid).not.toContain('model: string')
207 })
208
209 it('does not overlay output schemas or schemas without a model field', () => {
210 const output = emitTypesModule({
211 provider: 'anthropic',
212 endpointId: 'v1/messages',
213 kind: 'output',
214 contentHash: 'abc',
215 schema: fixture,
216 modelIds: ['claude-sonnet-4-5'],
217 })
218 expect(output).not.toContain('ListedModelId')
219
220 const noModel = emitTypesModule({
221 provider: 'fal',
222 endpointId: 'fal-ai/flux/dev',
223 kind: 'input',
224 contentHash: 'abc',
225 schema: {
226 type: 'object',
227 properties: { prompt: { type: 'string' } },
228 },
229 modelIds: ['fal-ai/flux/dev'],
230 })
231 expect(noModel).not.toContain('ListedModelId')
232 })
233
234 it('keys the types ETag by the live model list, not the schema hash', () => {
235 const hash = 'f'.repeat(64)
236 expect(typesEtag(hash, 'exact', modelIdsKey(['b', 'a']))).toBe(
237 typesEtag(hash, 'exact', modelIdsKey(['a', 'b'])),
238 )
239 expect(typesEtag(hash, 'exact', modelIdsKey(['a']))).not.toBe(
240 typesEtag(hash, 'exact', modelIdsKey(['a', 'c'])),
241 )
242 expect(typesEtag(hash, 'exact')).not.toContain('-m')
243 })
244
245 it('derives stable export names', () => {
246 expect(moduleNames('anthropic', 'v1/messages', 'input')).toEqual({
247 rootType: 'AnthropicV1MessagesRequest',
248 schemaConst: 'anthropicV1MessagesRequestSchema',
249 })
250 expect(
251 moduleNames('elevenlabs', 'v1/text-to-speech/{voice_id}', 'output')
252 .rootType,
253 ).toBe('ElevenlabsV1TextToSpeechVoiceIdResponse')
254 })
255})