Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

schemas-api.ts

304 lines8.7 KB

1/**
2 * Schema read queries (PLAN.md task 4.3). Endpoint ids exposed publicly are
3 * the PR #622 path-derived ids (`v1/messages`, `chat/completions`, …) — the
4 * db id minus the `${providerId}/` prefix. Stored schema text is parsed and
5 * re-serialised verbatim (JSON.stringify preserves insertion order), so the
6 * served bytes match what the sync engine wrote to D1.
7 */
8import { and, eq, isNull } from 'drizzle-orm'
9​
10import type { Db } from '#/db/index.ts'
11import { endpoints, providers, schemaVersions } from '#/db/schema.ts'
12import type { Activity } from '#/db/schema.ts'
13import { halGet } from '#/server/hal.ts'
14import { pinModelField, resolveEndpointAlias } from '#/server/schema-binding.ts'
15​
16export function publicEndpointId(dbId: string, providerId: string): string {
17 return dbId.startsWith(`${providerId}/`)
18 ? dbId.slice(providerId.length + 1)
19 : dbId
21​
22export async function providerExists(
23 db: Db,
24 providerId: string,
25): Promise<boolean> {
26 const row = await db.query.providers.findFirst({
27 where: eq(providers.id, providerId),
28 columns: { id: true },
29 })
30 return row !== undefined
32​
33export interface ProviderSchemaGroup {
34 provider: string
35 count: number
36 activities: Partial<Record<Activity, Array<string>>>
38​
39/**
40 * GET /v1/schemas — the system-wide schema index: every provider that has
41 * extracted schemas, with its activities and endpoint ids. The one URL an
42 * agent (or the /schemas page) needs to discover every schema on the system.
43 */
44export async function getSystemSchemaIndex(db: Db) {
45 const rows = await db
46 .select({
47 id: endpoints.id,
48 providerId: endpoints.providerId,
49 activity: endpoints.activity,
50 })
51 .from(endpoints)
52 .orderBy(endpoints.id)
53​
54 const byProvider = new Map<string, ProviderSchemaGroup>()
55 for (const row of rows) {
56 let group = byProvider.get(row.providerId)
57 if (!group) {
58 group = { provider: row.providerId, count: 0, activities: {} }
59 byProvider.set(row.providerId, group)
60 }
61 group.count++
62 ;(group.activities[row.activity] ??= []).push(
63 publicEndpointId(row.id, row.providerId),
64 )
65 }
66​
67 const providerGroups = [...byProvider.values()].sort((a, b) =>
68 a.provider.localeCompare(b.provider),
69 )
70 return {
71 count: rows.length,
72 providers: providerGroups,
73 _links: {
74 self: halGet('/v1/schemas'),
75 provider: halGet('/v1/schemas/{provider}'),
76 activity: halGet('/v1/schemas/{provider}/{activity}'),
77 schema: halGet(
78 '/v1/schemas/{provider}/{activity}/{endpointId}{?kind,version}',
79 ),
80 },
81 }
83​
84/** GET /v1/schemas/{provider} — activities + endpoint ids. */
85export async function getProviderSchemaIndex(db: Db, providerId: string) {
86 const rows = await db
87 .select({ id: endpoints.id, activity: endpoints.activity })
88 .from(endpoints)
89 .where(eq(endpoints.providerId, providerId))
90 .orderBy(endpoints.id)
91​
92 const activities: Partial<Record<Activity, Array<string>>> = {}
93 for (const row of rows) {
94 ;(activities[row.activity] ??= []).push(
95 publicEndpointId(row.id, providerId),
96 )
97 }
98 return {
99 provider: providerId,
100 count: rows.length,
101 activities,
102 _links: {
103 self: halGet(`/v1/schemas/${providerId}`),
104 activity: halGet(`/v1/schemas/${providerId}/{activity}`),
105 schema: halGet(
106 `/v1/schemas/${providerId}/{activity}/{endpointId}{?kind,version}`,
107 ),
108 },
109 }
111​
112interface SchemaPair {
113 input?: unknown
114 output?: unknown
116​
117/**
118 * GET /v1/schemas/{provider}/{activity} — endpoint-id-keyed map of current
119 * input/output schemas (the PR's `endpoint-schema-map` shape).
120 */
121export async function getActivitySchemaMap(
122 db: Db,
123 providerId: string,
124 activity: Activity,
125) {
126 const rows = await db
127 .select({
128 endpointId: endpoints.id,
129 kind: schemaVersions.kind,
130 schema: schemaVersions.schema,
131 })
132 .from(endpoints)
133 .leftJoin(
134 schemaVersions,
135 and(
136 eq(schemaVersions.endpointId, endpoints.id),
137 isNull(schemaVersions.supersededAt),
138 ),
139 )
140 .where(
141 and(
142 eq(endpoints.providerId, providerId),
143 eq(endpoints.activity, activity),
144 ),
145 )
146 .orderBy(endpoints.id)
147​
148 const map: Record<string, SchemaPair> = {}
149 for (const row of rows) {
150 const id = publicEndpointId(row.endpointId, providerId)
151 if (row.kind === null || row.schema === null) {
152 map[id] = { input: null, output: null }
153 } else {
154 ;(map[id] ??= {})[row.kind] = JSON.parse(row.schema) as unknown
155 }
156 }
157 return {
158 provider: providerId,
159 activity,
160 count: Object.keys(map).length,
161 endpoints: map,
162 _links: {
163 self: halGet(`/v1/schemas/${providerId}/${activity}`),
164 schema: halGet(
165 `/v1/schemas/${providerId}/${activity}/{endpointId}{?kind,version}`,
166 ),
167 },
168 }
170​
171export interface SchemaProvenance {
172 /** Upstream document the schema was derived from. */
173 sourceUrl: string | null
174 /** SHA-256 of that document as fetched (see SpecSource.hash). */
175 sourceHash: string | null
176 /** When this version was derived (the row's createdAt). */
177 fetchedAt: number
178 /** Extraction-pipeline version that produced contentHash. */
179 extractorVersion: string | null
180 /**
181 * How the content was arrived at — a trust ladder, strongest first:
182 * `upstream-spec` (extracted from a spec the provider publishes and we
183 * re-fetch every sync), `generated` (derived each sync from a
184 * provider-published artifact that is not a spec, e.g. SDK sources),
185 * `probe-verified` (hand-written but confirmed against live API calls on
186 * `verifiedAt`), `docs-derived` (hand-written from prose docs and NOT
187 * confirmed). The first two self-heal; the last two are point-in-time
188 * claims that can go stale. Null on versions synced before this was
189 * recorded.
190 */
191 derivation:
192 | 'upstream-spec'
193 | 'generated'
194 | 'probe-verified'
195 | 'docs-derived'
196 | null
197 /**
198 * `YYYY-MM-DD` the claim was last confirmed against the live API. Set for
199 * `probe-verified`; null for the self-healing derivations, whose freshness
200 * is `fetchedAt`.
201 */
202 verifiedAt: string | null
204​
205export interface EndpointSchemaResult {
206 provider: string
207 activity: Activity
208 endpointId: string
209 kind: 'input' | 'output'
210 contentHash: string
211 specRevision: string | null
212 provenance: SchemaProvenance
213 createdAt: number
214 supersededAt: number | null
215 schema: unknown
216 /**
217 * Set when `{endpointId}` was a listed model rawId/slug aliased onto
218 * the canonical generation route. The served `endpointId` is that route.
219 */
220 aliasedFrom?: string
222​
223/**
224 * GET /v1/schemas/{provider}/{activity}/{endpointId}?kind=&version= —
225 * a single self-contained JSON Schema; current version unless a content
226 * hash is passed. Returns null when the endpoint/kind/version is unknown.
227 */
228export async function getEndpointSchema(
229 db: Db,
230 providerId: string,
231 activity: Activity,
232 endpointId: string,
233 kind: 'input' | 'output' = 'input',
234 version?: string,
235): Promise<EndpointSchemaResult | null> {
236 const resolved = await resolveEndpointAlias(
237 db,
238 providerId,
239 endpointId,
240 activity,
241 )
242 if (!resolved) return null
243​
244 const row = await db.query.schemaVersions.findFirst({
245 where: and(
246 eq(schemaVersions.endpointId, resolved.dbId),
247 eq(schemaVersions.kind, kind),
248 version !== undefined
249 ? eq(schemaVersions.contentHash, version)
250 : isNull(schemaVersions.supersededAt),
251 ),
252 })
253 if (!row) return null
254​
255 const schema = JSON.parse(row.schema) as unknown
256 const pinned =
257 resolved.pinRawId !== null && kind === 'input'
258 ? pinModelField(schema, resolved.pinRawId)
259 : schema
260​
261 return {
262 provider: providerId,
263 activity,
264 endpointId: resolved.publicId,
265 kind,
266 contentHash: row.contentHash,
267 specRevision: row.specRevision,
268 provenance: {
269 sourceUrl: row.sourceUrl,
270 sourceHash: row.sourceHash,
271 fetchedAt: row.createdAt,
272 extractorVersion: row.extractorVersion,
273 derivation: row.derivation,
274 verifiedAt: row.verifiedAt,
275 },
276 createdAt: row.createdAt,
277 supersededAt: row.supersededAt,
278 schema: pinned,
279 ...(resolved.pinRawId !== null ? { aliasedFrom: resolved.pinRawId } : {}),
280 }
282​
283/** Endpoint-id hints for 404 remediation (capped). */
284export async function knownEndpointIds(
285 db: Db,
286 providerId: string,
287 activity?: Activity,
288 limit = 25,
289): Promise<Array<string>> {
290 const rows = await db
291 .select({ id: endpoints.id })
292 .from(endpoints)
293 .where(
294 activity
295 ? and(
296 eq(endpoints.providerId, providerId),
297 eq(endpoints.activity, activity),
298 )
299 : eq(endpoints.providerId, providerId),
300 )
301 .orderBy(endpoints.id)
302 .limit(limit)
303 return rows.map((r) => publicEndpointId(r.id, providerId))