Open History to see the last commit
1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3import { eq } from 'drizzle-orm'
4
5import { getDb } from '../db/index.ts'
6import type { Db } from '../db/index.ts'
7import { endpoints, models, providers, schemaVersions } from '../db/schema.ts'
8import {
9 getActivitySchemaMap,
10 getEndpointSchema,
11 getProviderSchemaIndex,
12 getSystemSchemaIndex,
13 knownEndpointIds,
14 publicEndpointId,
15} from './schemas-api.ts'
16import { cachedText } from './http-cache.ts'
17import { emitTypesModule, typesEtag } from './typegen.ts'
18
19const NOW = 1_781_150_000
20const INPUT_SCHEMA = {
21 type: 'object',
22 properties: { model: { type: 'string' }, blocks: { type: 'array' } },
23 $defs: { Block: { type: 'object' } },
24}
25const OLD_INPUT = { type: 'object', properties: { model: { type: 'string' } } }
26const OUTPUT_SCHEMA = { type: 'object', properties: { id: { type: 'string' } } }
27
28let db: Db
29
30beforeAll(async () => {
31 db = getDb(env)
32 await db.insert(providers).values({
33 id: 'sch-prov',
34 displayName: 'Schema Prov',
35 specSourceUrl: 'https://example.com/spec.json',
36 })
37 await db.insert(endpoints).values([
38 {
39 id: 'sch-prov/v1/messages',
40 providerId: 'sch-prov',
41 activity: 'chat',
42 method: 'POST',
43 path: '/v1/messages',
44 },
45 {
46 id: 'sch-prov/v1/images/generations',
47 providerId: 'sch-prov',
48 activity: 'image',
49 method: 'POST',
50 path: '/v1/images/generations',
51 },
52 ])
53 await db.insert(schemaVersions).values([
54 {
55 id: 'sch-prov/v1/messages:input:current',
56 endpointId: 'sch-prov/v1/messages',
57 kind: 'input',
58 contentHash: 'f'.repeat(64),
59 schema: JSON.stringify(INPUT_SCHEMA),
60 derivation: 'probe-verified',
61 verifiedAt: '2026-08-12',
62 createdAt: NOW,
63 },
64 {
65 id: 'sch-prov/v1/messages:input:old',
66 endpointId: 'sch-prov/v1/messages',
67 kind: 'input',
68 contentHash: 'e'.repeat(64),
69 schema: JSON.stringify(OLD_INPUT),
70 createdAt: NOW - 100,
71 supersededAt: NOW,
72 },
73 {
74 id: 'sch-prov/v1/messages:output:current',
75 endpointId: 'sch-prov/v1/messages',
76 kind: 'output',
77 contentHash: 'a'.repeat(64),
78 schema: JSON.stringify(OUTPUT_SCHEMA),
79 createdAt: NOW,
80 },
81 ])
82})
83
84describe('getProviderSchemaIndex', () => {
85 it('groups public endpoint ids by activity', async () => {
86 const index = await getProviderSchemaIndex(db, 'sch-prov')
87 expect(index.activities).toEqual({
88 chat: ['v1/messages'],
89 image: ['v1/images/generations'],
90 })
91 expect(index.count).toBe(2)
92 })
93})
94
95describe('getSystemSchemaIndex', () => {
96 it('lists every provider with its activity → endpoint-id groups', async () => {
97 const index = await getSystemSchemaIndex(db)
98 expect(index.count).toBe(2)
99 const group = index.providers.find((p) => p.provider === 'sch-prov')
100 expect(group).toEqual({
101 provider: 'sch-prov',
102 count: 2,
103 activities: {
104 chat: ['v1/messages'],
105 image: ['v1/images/generations'],
106 },
107 })
108 expect(index._links.self.href).toBe('/v1/schemas')
109 })
110})
111
112describe('getActivitySchemaMap', () => {
113 it('returns the endpoint-id-keyed map of current versions only', async () => {
114 const map = await getActivitySchemaMap(db, 'sch-prov', 'chat')
115 expect(Object.keys(map.endpoints)).toEqual(['v1/messages'])
116 expect(map.endpoints['v1/messages']?.input).toEqual(INPUT_SCHEMA)
117 expect(map.endpoints['v1/messages']?.output).toEqual(OUTPUT_SCHEMA)
118 // The superseded version is not served.
119 expect(map.endpoints['v1/messages']?.input).not.toEqual(OLD_INPUT)
120 })
121
122 it('is empty for activities without endpoints', async () => {
123 const map = await getActivitySchemaMap(db, 'sch-prov', 'audio')
124 expect(map.count).toBe(0)
125 })
126})
127
128describe('getEndpointSchema', () => {
129 it('serves the current input schema byte-identical to D1', async () => {
130 const result = await getEndpointSchema(
131 db,
132 'sch-prov',
133 'chat',
134 'v1/messages',
135 )
136 expect(result?.kind).toBe('input')
137 expect(result?.contentHash).toBe('f'.repeat(64))
138 const stored = await db.query.schemaVersions.findFirst({
139 where: eq(schemaVersions.id, 'sch-prov/v1/messages:input:current'),
140 })
141 expect(JSON.stringify(result?.schema)).toBe(stored?.schema)
142 })
143
144 it('surfaces the derivation grade and verified-on date', async () => {
145 const result = await getEndpointSchema(
146 db,
147 'sch-prov',
148 'chat',
149 'v1/messages',
150 )
151 expect(result?.provenance.derivation).toBe('probe-verified')
152 expect(result?.provenance.verifiedAt).toBe('2026-08-12')
153 })
154
155 it('reports null derivation for versions synced before it was recorded', async () => {
156 const result = await getEndpointSchema(
157 db,
158 'sch-prov',
159 'chat',
160 'v1/messages',
161 'input',
162 'e'.repeat(64),
163 )
164 expect(result?.provenance.derivation).toBeNull()
165 expect(result?.provenance.verifiedAt).toBeNull()
166 })
167
168 it('serves output schemas and historical versions by content hash', async () => {
169 const output = await getEndpointSchema(
170 db,
171 'sch-prov',
172 'chat',
173 'v1/messages',
174 'output',
175 )
176 expect(output?.schema).toEqual(OUTPUT_SCHEMA)
177
178 const historical = await getEndpointSchema(
179 db,
180 'sch-prov',
181 'chat',
182 'v1/messages',
183 'input',
184 'e'.repeat(64),
185 )
186 expect(historical?.schema).toEqual(OLD_INPUT)
187 expect(historical?.supersededAt).toBe(NOW)
188 })
189
190 it('returns null for unknown endpoint, wrong activity, or bad version', async () => {
191 expect(await getEndpointSchema(db, 'sch-prov', 'chat', 'nope')).toBeNull()
192 expect(
193 await getEndpointSchema(db, 'sch-prov', 'image', 'v1/messages'),
194 ).toBeNull()
195 expect(
196 await getEndpointSchema(
197 db,
198 'sch-prov',
199 'chat',
200 'v1/messages',
201 'input',
202 'deadbeef',
203 ),
204 ).toBeNull()
205 })
206
207 it('aliases a grok model rawId onto the shared generation route and pins model', async () => {
208 await db
209 .insert(providers)
210 .values({
211 id: 'grok',
212 displayName: 'xAI Grok',
213 specSourceUrl: 'https://example.com/g.json',
214 })
215 .onConflictDoNothing()
216 await db.insert(endpoints).values({
217 id: 'grok/v1/images/generations',
218 providerId: 'grok',
219 activity: 'image',
220 method: 'POST',
221 path: '/v1/images/generations',
222 })
223 const imageInput = {
224 type: 'object',
225 properties: {
226 model: { type: 'string', example: 'grok-imagine-image' },
227 prompt: { type: 'string' },
228 },
229 }
230 await db.insert(schemaVersions).values({
231 id: 'grok/v1/images/generations:input:current',
232 endpointId: 'grok/v1/images/generations',
233 kind: 'input',
234 contentHash: 'c'.repeat(64),
235 schema: JSON.stringify(imageInput),
236 createdAt: NOW,
237 })
238 await db.insert(models).values({
239 id: 'grok-grok-imagine-image-2-0',
240 providerId: 'grok',
241 rawId: 'grok-imagine-image-2.0',
242 activity: 'image',
243 firstSeenAt: NOW,
244 lastSeenAt: NOW,
245 })
246
247 const aliased = await getEndpointSchema(
248 db,
249 'grok',
250 'image',
251 'grok-imagine-image-2.0',
252 )
253 expect(aliased?.endpointId).toBe('v1/images/generations')
254 expect(aliased?.aliasedFrom).toBe('grok-imagine-image-2.0')
255 expect(aliased?.contentHash).toBe('c'.repeat(64))
256 expect(aliased?.schema).toEqual({
257 type: 'object',
258 properties: {
259 model: {
260 type: 'string',
261 example: 'grok-imagine-image-2.0',
262 enum: ['grok-imagine-image-2.0'],
263 },
264 prompt: { type: 'string' },
265 },
266 })
267
268 const direct = await getEndpointSchema(
269 db,
270 'grok',
271 'image',
272 'v1/images/generations',
273 )
274 expect(direct?.aliasedFrom).toBeUndefined()
275 expect(direct?.schema).toEqual(imageInput)
276
277 expect(
278 await getEndpointSchema(db, 'grok', 'chat', 'grok-imagine-image-2.0'),
279 ).toBeNull()
280 })
281})
282
283describe('helpers', () => {
284 it('derives public endpoint ids and 404 hints', async () => {
285 expect(publicEndpointId('sch-prov/v1/messages', 'sch-prov')).toBe(
286 'v1/messages',
287 )
288 expect(await knownEndpointIds(db, 'sch-prov', 'chat')).toEqual([
289 'v1/messages',
290 ])
291 expect(await knownEndpointIds(db, 'sch-prov')).toEqual([
292 'v1/images/generations',
293 'v1/messages',
294 ])
295 })
296})
297
298describe('?format=types flow (12.2)', () => {
299 it('emits a typescript module for a stored schema and honours ETag replay', async () => {
300 const result = await getEndpointSchema(
301 db,
302 'sch-prov',
303 'chat',
304 'v1/messages',
305 )
306 expect(result).not.toBeNull()
307 if (result === null) return
308
309 const text = emitTypesModule({
310 provider: result.provider,
311 endpointId: result.endpointId,
312 kind: result.kind,
313 contentHash: result.contentHash,
314 schema: result.schema as Record<string, unknown>,
315 sourceUrl:
316 'https://example.com/v1/schemas/sch-prov/chat/v1/messages?kind=input',
317 })
318 expect(text).toContain('export const schProvV1MessagesRequestSchema')
319 expect(text).toContain('export interface SchProvV1MessagesRequest')
320 expect(text).toContain('export type Block =')
321 expect(text).not.toMatch(/^import /m)
322
323 const etag = typesEtag(result.contentHash, 'exact')
324 const fresh = cachedText(
325 new Request('https://example.com/x'),
326 text,
327 'text/typescript; charset=utf-8',
328 { etag, fetchedAt: NOW, staleAt: NOW + 300 },
329 )
330 expect(fresh.status).toBe(200)
331 expect(fresh.headers.get('content-type')).toBe(
332 'text/typescript; charset=utf-8',
333 )
334 expect(await fresh.text()).toBe(text)
335
336 const replay = cachedText(
337 new Request('https://example.com/x', {
338 headers: { 'if-none-match': fresh.headers.get('etag') ?? '' },
339 }),
340 text,
341 'text/typescript; charset=utf-8',
342 { etag, fetchedAt: NOW, staleAt: NOW + 300 },
343 )
344 expect(replay.status).toBe(304)
345 expect(await replay.text()).toBe('')
346 })
347})