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

elevenlabs.ts

153 lines4.8 KB

1/**
2 * Pure helpers for `scripts/sync-elevenlabs-models.ts`.
3 *
4 * Text-to-speech ids come from the modelschemas model list. Music, sound
5 * effects, and voice design come from request-schema `model_id` enums.
6 * Transcription has no enum there.
7 */
8​
9const SAFE_ID = /^[a-z0-9_]+$/
10​
11export interface ElevenLabsCatalogModel {
12 rawId?: unknown
13 firstSeenAt?: unknown
14 deprecatedAt?: unknown
15 capabilities?: {
16 canDoTextToSpeech?: unknown
17 } | null
19​
20/**
21 * Text-to-speech ids, newest first. Voice-conversion-only rows and rows
22 * modelschemas has marked deprecated are omitted. Ids that are not a safe
23 * token are omitted so they cannot be written into source.
24 */
25function isListedTtsModel(
26 model: ElevenLabsCatalogModel,
27): model is ElevenLabsCatalogModel & { rawId: string } {
28 return (
29 model.capabilities?.canDoTextToSpeech === true &&
30 model.deprecatedAt == null &&
31 typeof model.rawId === 'string' &&
32 SAFE_ID.test(model.rawId)
33 )
35​
36export function ttsModelIdsFromCatalog(
37 models: readonly ElevenLabsCatalogModel[],
38): Array<string> {
39 return models
40 .filter(isListedTtsModel)
41 .slice()
42 .sort((a, b) => {
43 const aSeen = typeof a.firstSeenAt === 'number' ? a.firstSeenAt : 0
44 const bSeen = typeof b.firstSeenAt === 'number' ? b.firstSeenAt : 0
45 if (aSeen !== bSeen) return bSeen - aSeen
46 return a.rawId.localeCompare(b.rawId)
47 })
48 .map((model) => model.rawId)
50​
51interface JsonSchema {
52 enum?: unknown
53 $ref?: unknown
54 properties?: Record<string, JsonSchema> | null
55 $defs?: Record<string, JsonSchema> | null
56 'x-fern-enum'?: Record<string, { deprecated?: unknown }> | null
58​
59function isSchema(value: unknown): value is JsonSchema {
60 return typeof value === 'object' && value !== null && !Array.isArray(value)
62​
63/**
64 * Current `model_id` values from a modelschemas input schema.
65 * Enum order is oldest-first, so the result is reversed.
66 * `x-fern-enum` entries marked deprecated are omitted.
67 *
68 * ponytail: reverse the enum. Sort by a real timestamp if a schema stops
69 * listing the newest id last.
70 */
71export function modelIdsFromRequestSchema(schema: unknown): Array<string> {
72 if (!isSchema(schema)) {
73 throw new Error('modelschemas schema is not an object')
74 }
75 const modelId = schema.properties?.model_id
76 if (!isSchema(modelId)) {
77 throw new Error('modelschemas schema has no model_id')
78 }
79 const target = resolveRef(schema, modelId)
80 if (!Array.isArray(target.enum) || target.enum.length === 0) {
81 throw new Error('modelschemas model_id has no enum')
82 }
83 const deprecated = new Set(
84 Object.entries(target['x-fern-enum'] ?? {})
85 .filter(([, entry]) => entry?.deprecated === true)
86 .map(([name]) => name),
87 )
88 const ids: Array<string> = []
89 for (const value of target.enum) {
90 if (typeof value !== 'string' || !SAFE_ID.test(value)) {
91 throw new Error(
92 `Refusing to insert ElevenLabs model id: ${String(value)}`,
93 )
94 }
95 if (!deprecated.has(value)) ids.push(value)
96 }
97 if (ids.length === 0) {
98 throw new Error('modelschemas model_id enum has no current ids')
99 }
100 return ids.reverse()
102​
103function resolveRef(root: JsonSchema, node: JsonSchema): JsonSchema {
104 if (typeof node.$ref !== 'string') return node
105 if (!node.$ref.startsWith('#/$defs/')) {
106 throw new Error(`Unsupported schema $ref: ${node.$ref}`)
107 }
108 const name = node.$ref.slice('#/$defs/'.length)
109 const target = root.$defs?.[name]
110 if (!isSchema(target)) {
111 throw new Error(`schema $ref not found: ${node.$ref}`)
112 }
113 return target
115​
116/**
117 * Prepend ids that are not already in the named `export const` array.
118 * Existing rows, including deprecated ones the catalog dropped, stay put.
119 *
120 * ponytail: prepend only. A newly seen id that is older than rows we already
121 * list lands above them. Sort the whole array if that order starts to matter.
122 */
123export function insertMissingModels(
124 source: string,
125 exportName: string,
126 orderedIds: readonly string[],
127): string {
128 const marker = `export const ${exportName} = [`
129 const start = source.indexOf(marker)
130 if (start < 0) {
131 throw new Error(`${exportName} array not found`)
132 }
133 const open = start + marker.length
134 const close = source.indexOf('] as const', open)
135 if (close < 0) {
136 throw new Error(exportName + ' array is not closed with `] as const`')
137 }
138 const existing = new Set(
139 [...source.slice(open, close).matchAll(/'([a-z0-9_]+)'/g)].map(
140 (match) => match[1],
141 ),
142 )
143 const missing: Array<string> = []
144 for (const id of orderedIds) {
145 if (!SAFE_ID.test(id)) {
146 throw new Error(`Refusing to insert ElevenLabs model id: ${id}`)
147 }
148 if (!existing.has(id) && !missing.includes(id)) missing.push(id)
149 }
150 if (missing.length === 0) return source
151 const lines = missing.map((id) => ` '${id}',`).join('\n')
152 return `${source.slice(0, open)}\n${lines}${source.slice(open)}`