Open History to see the last commit
1/**
2 * Server-side sweep of every provider's video activity schemas, plus a
3 * validation proxy — the modelschemas API is only ever called from the
4 * server, so the browser needs no CORS.
5 */
6import { createServerFn } from '@tanstack/react-start'
7import {
8 createModelschemasClient,
9 getActivitySchemas,
10 listProviders,
11 validatePayload,
12} from '@modelschemas/client'
13import { extractVideoControls } from '../lib/video'
14import type { SchemaNode, VideoControls } from '../lib/video'
15
16const BASE_URL = process.env.MODELSCHEMAS_URL ?? 'https://modelschemas.com'
17
18export interface VideoModelEntry {
19 provider: string
20 endpointId: string
21 controls: VideoControls
22}
23
24export interface VideoCatalog {
25 baseUrl: string
26 providers: Array<string>
27 entries: Array<VideoModelEntry>
28}
29
30function isNode(value: unknown): value is SchemaNode {
31 return typeof value === 'object' && value !== null && !Array.isArray(value)
32}
33
34function makeClient() {
35 return createModelschemasClient({ baseUrl: BASE_URL })
36}
37
38async function buildCatalog(): Promise<VideoCatalog> {
39 const client = makeClient()
40
41 const providersResult = await listProviders({ client })
42 const providerList = isNode(providersResult.data)
43 ? providersResult.data['providers']
44 : undefined
45 const providerIds = Array.isArray(providerList)
46 ? providerList
47 .map((entry) => (isNode(entry) ? entry['id'] : undefined))
48 .filter((id): id is string => typeof id === 'string')
49 : []
50
51 const entries: Array<VideoModelEntry> = []
52 await Promise.all(
53 providerIds.map(async (provider) => {
54 const result = await getActivitySchemas({
55 client,
56 path: { provider, activity: 'video' },
57 })
58 if (result.error !== undefined || !isNode(result.data)) return
59 const endpoints = result.data['endpoints']
60 if (!isNode(endpoints)) return
61 for (const [endpointId, pair] of Object.entries(endpoints)) {
62 if (!isNode(pair)) continue
63 const input = pair['input']
64 if (!isNode(input)) continue
65 const controls = extractVideoControls(input)
66 // Only list endpoints that are actually composable: a prompt plus
67 // at least one schema-constrained knob.
68 if (
69 controls.promptPath !== null &&
70 (controls.aspect !== null || controls.duration !== null)
71 ) {
72 entries.push({ provider, endpointId, controls })
73 }
74 }
75 }),
76 )
77
78 entries.sort((a, b) =>
79 a.provider === b.provider
80 ? a.endpointId.localeCompare(b.endpointId)
81 : a.provider.localeCompare(b.provider),
82 )
83 return { baseUrl: BASE_URL, providers: providerIds, entries }
84}
85
86let cache: { at: number; catalog: Promise<VideoCatalog> } | null = null
87const TTL_MS = 5 * 60 * 1000
88
89export const getVideoCatalog = createServerFn({ method: 'GET' }).handler(
90 (): Promise<VideoCatalog> => {
91 if (cache === null || Date.now() - cache.at > TTL_MS) {
92 cache = { at: Date.now(), catalog: buildCatalog() }
93 cache.catalog.catch(() => {
94 cache = null
95 })
96 }
97 return cache.catalog
98 },
99)
100
101export interface ValidationOutcome {
102 valid: boolean
103 errors: Array<{ path: string; message: string }>
104 failure: string | null
105}
106
107interface ValidateInput {
108 provider: string
109 endpointId: string
110 payload: unknown
111}
112
113function narrowValidateInput(input: unknown): ValidateInput {
114 if (!isNode(input)) throw new Error('expected an object')
115 const provider = input['provider']
116 const endpointId = input['endpointId']
117 if (typeof provider !== 'string' || typeof endpointId !== 'string') {
118 throw new Error('provider and endpointId must be strings')
119 }
120 return { provider, endpointId, payload: input['payload'] }
121}
122
123export const validateVideoRequest = createServerFn({ method: 'POST' })
124 .inputValidator(narrowValidateInput)
125 .handler(async ({ data }): Promise<ValidationOutcome> => {
126 const client = makeClient()
127 const result = await validatePayload({
128 client,
129 body: {
130 provider: data.provider,
131 endpointId: data.endpointId,
132 kind: 'input',
133 payload: data.payload,
134 },
135 })
136 if (result.error !== undefined || !isNode(result.data)) {
137 return {
138 valid: false,
139 errors: [],
140 failure: `validation call failed (${String(result.response?.status ?? 'no response')})`,
141 }
142 }
143 const errors: Array<{ path: string; message: string }> = []
144 const rawErrors = result.data['errors']
145 if (Array.isArray(rawErrors)) {
146 for (const entry of rawErrors) {
147 if (!isNode(entry)) continue
148 const path = entry['path']
149 const message = entry['message']
150 errors.push({
151 path: typeof path === 'string' ? path : '',
152 message: typeof message === 'string' ? message : 'invalid',
153 })
154 }
155 }
156 return { valid: result.data['valid'] === true, errors, failure: null }
157 })