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

load-adapters.ts

77 lines2.5 KB

1/**
2 * Auto-discover provider adapters so each new provider is a single new
3 * file under `./adapters/` (plus its test). Adding a provider must not
4 * edit this file, `index.ts`, or `seed-providers.ts` — otherwise parallel
5 * adapter branches collide.
6 *
7 * Convention: `src/server/providers/adapters/<id>.ts` exports
8 * `export const provider: ProviderConfig` with `id`, `specSourceUrl`,
9 * and `modelsEndpoint` set. `*.test.ts` files are ignored.
10 *
11 * Vite/vitest transform `import.meta.glob`. Do not import this module
12 * from bun scripts (`scripts/seed.ts` scans the adapters directory
13 * itself).
14 */
15import type { ProviderConfig } from './types.ts'
16​
17const CORE_PROVIDER_IDS = new Set([
18 'openai',
19 'anthropic',
20 'gemini',
21 'grok',
22 'elevenlabs',
23 'openrouter',
24 'fal',
25 'byteplus',
26])
27​
28// Exclude `*.test.ts` in the glob itself. `{ eager: true }` on `*.ts`
29// would also load the tests, and a test that imports classifyAndBundle
30// (→ sync → this registry) then deadlocks: adapterProviders is still
31// undefined and `...adapterProviders` throws "not iterable".
32const modules = import.meta.glob<{ provider?: ProviderConfig }>(
33 ['./adapters/*.ts', '!./adapters/*.test.ts'],
34 { eager: true },
36​
37function isProvider(value: unknown): value is ProviderConfig {
38 if (value === null || typeof value !== 'object') return false
39 const record = value as Record<string, unknown>
40 return (
41 typeof record.id === 'string' &&
42 typeof record.displayName === 'string' &&
43 typeof record.fetchSpec === 'function' &&
44 typeof record.listModels === 'function' &&
45 typeof record.classify === 'function'
46 )
48​
49function loadAdapters(): Array<ProviderConfig> {
50 const loaded: Array<ProviderConfig> = []
51 const seen = new Set<string>()
52 for (const [path, mod] of Object.entries(modules)) {
53 const candidate = mod.provider
54 if (!isProvider(candidate)) {
55 throw new Error(
56 `adapter ${path} must export const provider: ProviderConfig`,
57 )
58 }
59 if (CORE_PROVIDER_IDS.has(candidate.id)) {
60 throw new Error(
61 `adapter ${path} reuses core provider id "${candidate.id}"`,
62 )
63 }
64 if (seen.has(candidate.id)) {
65 throw new Error(`duplicate adapter id "${candidate.id}" (${path})`)
66 }
67 if (!candidate.specSourceUrl) {
68 throw new Error(`adapter ${candidate.id} is missing specSourceUrl`)
69 }
70 seen.add(candidate.id)
71 loaded.push(candidate)
72 }
73 loaded.sort((a, b) => a.id.localeCompare(b.id))
74 return loaded
76​
77export const adapterProviders: Array<ProviderConfig> = loadAdapters()