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

opencode-routes.ts

65 lines2.2 KB

1/** Native OpenCode routes, with unpublished request/response schemas absent. */
2import { fetchText, sha256Text } from './types.ts'
3import type { OpenApiDocument, SpecFetchResult } from './types.ts'
4​
5export const ROUTE_ONLY_MARKER = 'x-modelschemas-route-only'
6const ROUTE_ACTIVITY = 'x-modelschemas-opencode-activity'
7const SOURCE_ROOT =
8 'https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/console/app/src/routes/zen/'
9​
10interface RouteRow {
11 schemaEndpointId: string | null
12 activity: string | null
14​
15export async function openCodeRouteSpec(
16 rows: Array<RouteRow>,
17 docs: { url: string; text: string },
18 go: boolean,
19): Promise<SpecFetchResult> {
20 const paths: NonNullable<OpenApiDocument['paths']> = {}
21 const code = new Map<string, { text: string; hash: string }>()
22 for (const row of rows) {
23 if (!row.schemaEndpointId || row.activity !== 'chat') continue
24 const path = `/${row.schemaEndpointId.replace(/^\//, '')}`
25 const file = path.startsWith('/v1/models/')
26 ? 'v1/models/[model]'
27 : path.slice(1)
28 const url = `${SOURCE_ROOT}${go ? 'go/' : ''}${file}.ts`
29 let native = code.get(url)
30 if (!native) {
31 const text = await fetchText(url, { signal: AbortSignal.timeout(30_000) })
32 if (!/export\s+(?:async\s+)?function\s+POST\s*\(/.test(text))
33 throw new Error(
34 `opencode: native route ${url} publishes no POST handler`,
35 )
36 native = { text, hash: await sha256Text(text) }
37 code.set(url, native)
38 }
39 paths[path] = {
40 post: {
41 [ROUTE_ONLY_MARKER]: true,
42 [ROUTE_ACTIVITY]: 'chat',
43 'x-modelschemas-method-source': { url, hash: native.hash },
44 responses: {},
45 },
46 }
47 }
48 if (Object.keys(paths).length === 0)
49 throw new Error('opencode: docs name no verified chat routes')
50 return {
51 specs: [{ openapi: '3.1.0', paths }],
52 sources: [{ url: docs.url, hash: await sha256Text(docs.text) }],
53 outputStrategy: 'post-200',
54 }
56​
57export function classifyOpenCodeRoute(
58 _path: string,
59 operation: Record<string, unknown>,
60): 'chat' | null {
61 return operation[ROUTE_ONLY_MARKER] === true &&
62 operation[ROUTE_ACTIVITY] === 'chat'
63 ? 'chat'
64 : null