Open History to see the last commit
1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { getDb } from '../db/index.ts'
5import type { Db } from '../db/index.ts'
6import { endpoints, models, providers, schemaVersions } from '../db/schema.ts'
7import { serviceIndex } from '../routes/v1/index.ts'
8import { listChanges } from './changes-api.ts'
9import {
10 getModelDetail,
11 getProviderCatalog,
12 listModelsCatalog,
13 listProvidersCatalog,
14} from './catalog.ts'
15import type { HalLink } from './hal.ts'
16import {
17 getActivitySchemaMap,
18 getEndpointSchema,
19 getProviderSchemaIndex,
20 getSystemSchemaIndex,
21} from './schemas-api.ts'
22import { getServiceStatus } from './status.ts'
23import { assembleProviderOpenApi } from './provider-openapi.ts'
24import { estimateCost } from './estimate.ts'
25import type { EstimateRequestBody } from './estimate.ts'
26import { validatePayload } from './validate.ts'
27import type { ValidateRequestBody } from './validate.ts'
28import { GPT_4O } from '../../packages/rate-card/src/fixtures/gpt-4o.ts'
29
30let db: Db
31
32const SCHEMA = JSON.stringify({
33 type: 'object',
34 required: ['model', 'max_tokens'],
35 properties: {
36 model: { type: 'string' },
37 max_tokens: { type: 'integer' },
38 },
39})
40
41beforeAll(async () => {
42 db = getDb(env)
43 // Seed the data the serviceIndex examples reference, so walking the
44 // examples proves they are live URLs.
45 await db.insert(providers).values({
46 id: 'anthropic',
47 displayName: 'Anthropic',
48 specSourceUrl: 'https://example.com/spec.json',
49 })
50 const NOW = 1_781_150_000
51 await db.insert(models).values({
52 id: 'anthropic-claude-sonnet-4-5',
53 providerId: 'anthropic',
54 rawId: 'claude-sonnet-4-5',
55 activity: 'chat',
56 firstSeenAt: NOW,
57 lastSeenAt: NOW,
58 })
59 await db.insert(endpoints).values({
60 id: 'anthropic/v1/messages',
61 providerId: 'anthropic',
62 path: '/v1/messages',
63 method: 'POST',
64 activity: 'chat',
65 })
66 await db.insert(schemaVersions).values({
67 id: 'sv-hal-input',
68 endpointId: 'anthropic/v1/messages',
69 kind: 'input',
70 contentHash: 'hash-hal-input',
71 schema: SCHEMA,
72 createdAt: NOW,
73 })
74 await db.insert(providers).values({
75 id: 'openai',
76 displayName: 'OpenAI',
77 specSourceUrl: 'https://example.com/openai.json',
78 })
79 await db.insert(models).values({
80 id: 'openai-gpt-4o',
81 providerId: 'openai',
82 rawId: 'gpt-4o',
83 activity: 'chat',
84 pricing: GPT_4O,
85 firstSeenAt: NOW,
86 lastSeenAt: NOW,
87 })
88})
89
90/** Resolves a link the way the HTTP router would; throws on unknown paths
91 * so a new link without a dispatcher entry fails the walk. */
92async function resolve(target: string | Record<string, unknown>) {
93 if (typeof target !== 'string') {
94 if ('endpointId' in target) {
95 const outcome = await validatePayload(
96 db,
97 target as unknown as ValidateRequestBody,
98 )
99 expect(outcome.ok).toBe(true)
100 return
101 }
102 const outcome = await estimateCost(
103 db,
104 target as unknown as EstimateRequestBody,
105 )
106 expect(outcome.ok).toBe(true)
107 return
108 }
109 if (!target.startsWith('/v1')) return // .well-known etc. — out of scope
110 const url = new URL(target, 'https://walk.test')
111 const segments = url.pathname.split('/').filter(Boolean).slice(1)
112 const [head, ...rest] = segments
113 switch (head) {
114 case undefined:
115 return // /v1 — the document under test
116 case 'status':
117 expect((await getServiceStatus(db)).providers.length).toBeGreaterThan(0)
118 return
119 case 'providers': {
120 if (rest.length === 0) {
121 expect(
122 (await listProvidersCatalog(db)).providers.length,
123 ).toBeGreaterThan(0)
124 return
125 }
126 const [provider] = rest
127 expect(await getProviderCatalog(db, provider ?? '')).not.toBeNull()
128 return
129 }
130 case 'models': {
131 if (rest.length === 0) {
132 const activity = url.searchParams.get('activity')
133 const result = await listModelsCatalog(db, {
134 activity: activity === 'chat' ? 'chat' : undefined,
135 q: url.searchParams.get('q') ?? undefined,
136 })
137 expect(result.count).toBeGreaterThan(0)
138 return
139 }
140 const [provider, modelId] = rest
141 expect(
142 await getModelDetail(db, provider ?? '', modelId ?? ''),
143 ).not.toBeNull()
144 return
145 }
146 case 'schemas': {
147 const [provider, activity, ...endpointParts] = rest
148 if (!provider) {
149 // /v1/schemas — the system-wide index.
150 expect((await getSystemSchemaIndex(db)).count).toBeGreaterThan(0)
151 return
152 }
153 if (!activity) {
154 expect(
155 (await getProviderSchemaIndex(db, provider)).count,
156 ).toBeGreaterThan(0)
157 return
158 }
159 if (endpointParts.length === 0) {
160 expect(activity).toBe('chat')
161 expect(
162 (await getActivitySchemaMap(db, provider, 'chat')).count,
163 ).toBeGreaterThan(0)
164 return
165 }
166 const endpointId = decodeURIComponent(endpointParts.join('/'))
167 const kind =
168 url.searchParams.get('kind') === 'output' ? 'output' : 'input'
169 expect(activity).toBe('chat')
170 expect(
171 await getEndpointSchema(db, provider, 'chat', endpointId, kind),
172 ).not.toBeNull()
173 return
174 }
175 case 'changes': {
176 const outcome = await listChanges(db, {})
177 expect(outcome.ok).toBe(true)
178 return
179 }
180 case 'openapi': {
181 const [provider] = rest
182 const assembled = await assembleProviderOpenApi(db, provider ?? '', {
183 model: url.searchParams.get('model') ?? undefined,
184 activity: url.searchParams.get('activity') ?? undefined,
185 })
186 expect(assembled.ok).toBe(true)
187 return
188 }
189 default:
190 throw new Error(`no dispatcher for link target ${target}`)
191 }
192}
193
194function assertHalShape(name: string, link: HalLink) {
195 expect(link.href, name).toBeTruthy()
196 expect(['GET', 'POST', 'DELETE'], name).toContain(link.method)
197 expect(link.contentType, name).toBeTruthy()
198 if (link.href.includes('{')) {
199 expect(link.templated, `${name} must mark templated`).toBe(true)
200 expect(link.example, `${name} template needs an example`).toBeDefined()
201 }
202}
203
204describe('HAL self-description (task 11.1)', () => {
205 it('walks every GET /v1 link to a live resource', async () => {
206 for (const [name, link] of Object.entries(serviceIndex._links)) {
207 assertHalShape(name, link)
208 await resolve(link.example ?? link.href)
209 }
210 })
211
212 it('walks every GET /v1/models link', async () => {
213 const result = await listModelsCatalog(db, {})
214 for (const [name, link] of Object.entries(result._links)) {
215 assertHalShape(name, link)
216 await resolve(link.example ?? link.href)
217 }
218 // Model rows carry HAL links too.
219 const model = result.models[0]
220 for (const [name, link] of Object.entries(model?._links ?? {})) {
221 assertHalShape(name, link)
222 await resolve(link.href)
223 }
224 })
225})