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

fetch-lovable-gateway-models.ts

80 lines2.2 KB

1/**
2 * Fetches models from the Lovable AI Gateway API and writes them to
3 * lovable-gateway.models.json.
4 *
5 * Usage:
6 * pnpm tsx scripts/fetch-lovable-gateway-models.ts
7 *
8 * The endpoint is public — no API key required.
9 *
10 * The output is plain JSON so a malicious or compromised upstream response
11 * cannot smuggle executable code into the build (JSON.stringify cannot produce
12 * a JS expression). The committed wrapper at `lovable-gateway.models.ts`
13 * re-exports this JSON typed as `Array<LovableGatewayCatalogModel>`.
14 */
15​
16import { writeFile } from 'node:fs/promises'
17import { dirname, resolve } from 'node:path'
18import { fileURLToPath } from 'node:url'
19​
20const __dirname = dirname(fileURLToPath(import.meta.url))
21const OUTPUT_PATH = resolve(__dirname, 'lovable-gateway.models.json')
22const API_URL = 'https://ai.gateway.lovable.dev/v1/models'
23​
24interface ApiModel {
25 id: string
26 [key: string]: unknown
28​
29function isValidModel(model: unknown): model is ApiModel {
30 return (
31 typeof model === 'object' &&
32 model !== null &&
33 typeof (model as { id?: unknown }).id === 'string' &&
34 (model as { id: string }).id.length > 0
35 )
37​
38async function main() {
39 console.log(`Fetching models from ${API_URL}...`)
40​
41 const response = await fetch(API_URL, {
42 headers: { Accept: 'application/json' },
43 signal: AbortSignal.timeout(30_000),
44 })
45​
46 if (!response.ok) {
47 throw new Error(
48 `Failed to fetch Lovable AI Gateway models: ${response.status} ${response.statusText}`,
49 )
50 }
51​
52 const json = (await response.json()) as { data?: unknown }
53 if (!Array.isArray(json.data)) {
54 throw new Error(
55 'Lovable AI Gateway /v1/models response is missing a data array',
56 )
57 }
58​
59 const allModels = json.data
60 const validModels = allModels.filter(isValidModel)
61 const skipped = allModels.length - validModels.length
62 if (skipped > 0) {
63 console.log(`Skipped ${skipped} models missing a string id`)
64 }
65​
66 validModels.sort((a, b) => a.id.localeCompare(b.id))
67​
68 await writeFile(
69 OUTPUT_PATH,
70 JSON.stringify(validModels, null, 2) + '\n',
71 'utf-8',
72 )
73 console.log(`Fetched ${validModels.length} models`)
74 console.log(`Written to ${OUTPUT_PATH}`)
76​
77main().catch((error) => {
78 console.error(error)
79 process.exit(1)
80})