Open History to see the last commit
1/**
2 * File-mutation helpers for `sync-provider-models.ts`.
3 *
4 * Kept here so the insert path (chat array + type maps) can be unit-tested
5 * without running the full modelschemas fetch.
6 */
7
8export type ArrayRef = '.name' | '.id'
9
10export function insertConstants(
11 content: string,
12 constants: Array<string>,
13): string {
14 const block = '\n' + constants.join('\n\n') + '\n'
15 const exportIndex = content.indexOf('\nexport ')
16 if (exportIndex === -1) {
17 return content + block
18 }
19 // Insert above the export's JSDoc, so the comment stays on its export.
20 const doc = /\n\/\*\*(?:(?!\*\/)[\s\S])*\*\/\s*$/.exec(
21 content.slice(0, exportIndex),
22 )
23 const at = doc ? doc.index : exportIndex
24 return content.slice(0, at) + block + content.slice(at)
25}
26
27/**
28 * Insert entries immediately AFTER the opening bracket. Each inserted line
29 * carries its own trailing comma so the existing body does not need a
30 * comma-guess. See the grok-4.5 single-line array breakage.
31 *
32 * Every insert helper throws when its anchor is missing: the constants are
33 * already in the file, and nothing would reference them.
34 */
35function addToArray(
36 content: string,
37 arrayName: string,
38 entries: Array<string>,
39 arrayRef: string,
40): string {
41 const decl = `export const ${arrayName} = `
42 const declIndex = content.indexOf(decl)
43 const afterDecl = declIndex === -1 ? -1 : declIndex + decl.length
44 const bracket = afterDecl === -1 ? -1 : content.indexOf('[', afterDecl)
45 if (declIndex === -1 || bracket === -1 || bracket - afterDecl > 40) {
46 throw new Error(`Could not find array '${arrayName}' in file`)
47 }
48
49 const newEntries = entries
50 .map((constName) => ` ${constName}${arrayRef},`)
51 .join('\n')
52 const insertAt = bracket + 1
53 return `${content.slice(0, insertAt)}\n${newEntries}${content.slice(insertAt)}`
54}
55
56function addToTypeMap(
57 content: string,
58 typeName: string,
59 entries: Array<string>,
60): string {
61 const pattern = new RegExp(
62 `(export type ${typeName} = \\{[\\s\\S]*?)(\\n\\})`,
63 )
64 const match = pattern.exec(content)
65 if (!match) {
66 throw new Error(`Could not find type map '${typeName}' in file`)
67 }
68
69 const newEntries = entries.join('\n')
70 return content.replace(pattern, () => `${match[1]}\n${newEntries}${match[2]}`)
71}
72
73function addToObjectMap(
74 content: string,
75 mapName: string,
76 entries: Array<string>,
77): string {
78 const pattern = new RegExp(
79 `(const ${mapName}: Record<string, number> = \\{[\\s\\S]*?)(\\n\\})`,
80 )
81 const match = pattern.exec(content)
82 if (!match) {
83 throw new Error(`Could not find object map '${mapName}' in file`)
84 }
85
86 const newEntries = entries.join('\n')
87 return content.replace(pattern, () => `${match[1]}\n${newEntries}${match[2]}`)
88}
89
90/**
91 * Append entries to the runtime map that ends with `} satisfies <typeName>`.
92 * A file without that map is left as it is.
93 */
94function addToSatisfyingMap(
95 content: string,
96 typeName: string,
97 entries: Array<string>,
98): string {
99 // ponytail: found by its `satisfies` tail, so the sync config needs no map name.
100 const pattern = new RegExp(`\\n\\} satisfies ${typeName}\\b`)
101 return content.replace(pattern, (close) => `\n${entries.join('\n')}${close}`)
102}
103
104interface ChatModelInsert {
105 constName: string
106 providerOptionsEntry: string
107 hasMaxOutputTokens: boolean
108 /** Anthropic: add to the combined tools + output_config.format set. */
109 acceptsCombinedToolsAndSchema?: boolean
110}
111
112interface ChatModelCatalogInsertConfig {
113 chatArrayName: string
114 arrayRef: ArrayRef
115 providerOptionsTypeName: string
116 inputModalitiesTypeName: string
117 toolCapabilitiesTypeName?: string
118 maxOutputTokensMapName?: string
119 combinedToolsAndSchemaSetName?: string
120 providerOptionsIsMappedType: boolean
121}
122
123/**
124 * Write a new chat model into the catalog tables the adapter types read:
125 * the exported id array, provider-options map, input-modalities type map and
126 * its runtime map (when the file has one), tool-capabilities map, and
127 * (Anthropic) max-output-tokens object.
128 */
129export function applyChatModelCatalogInserts(
130 content: string,
131 config: ChatModelCatalogInsertConfig,
132 chatModels: Array<ChatModelInsert>,
133): string {
134 if (chatModels.length === 0) return content
135
136 let next = addToArray(
137 content,
138 config.chatArrayName,
139 chatModels.map(({ constName }) => constName),
140 config.arrayRef,
141 )
142
143 if (!config.providerOptionsIsMappedType) {
144 next = addToTypeMap(
145 next,
146 config.providerOptionsTypeName,
147 chatModels.map(
148 ({ constName, providerOptionsEntry }) =>
149 ` [${constName}${config.arrayRef}]: ${providerOptionsEntry}`,
150 ),
151 )
152 }
153
154 next = addToTypeMap(
155 next,
156 config.inputModalitiesTypeName,
157 chatModels.map(
158 ({ constName }) =>
159 ` [${constName}${config.arrayRef}]: typeof ${constName}.supports.input`,
160 ),
161 )
162 next = addToSatisfyingMap(
163 next,
164 config.inputModalitiesTypeName,
165 chatModels.map(
166 ({ constName }) =>
167 ` [${constName}${config.arrayRef}]: ${constName}.supports.input,`,
168 ),
169 )
170
171 if (config.toolCapabilitiesTypeName) {
172 next = addToTypeMap(
173 next,
174 config.toolCapabilitiesTypeName,
175 chatModels.map(
176 ({ constName }) =>
177 ` [${constName}${config.arrayRef}]: typeof ${constName}.supports.tools`,
178 ),
179 )
180 }
181
182 if (config.combinedToolsAndSchemaSetName) {
183 const combined = chatModels.filter(
184 ({ acceptsCombinedToolsAndSchema }) => acceptsCombinedToolsAndSchema,
185 )
186 if (combined.length > 0) {
187 next = addToArray(
188 next,
189 config.combinedToolsAndSchemaSetName,
190 combined.map(({ constName }) => constName),
191 config.arrayRef,
192 )
193 }
194 }
195
196 if (config.maxOutputTokensMapName) {
197 const maxOutputEntries = chatModels
198 .filter(({ hasMaxOutputTokens }) => hasMaxOutputTokens)
199 .map(
200 ({ constName }) =>
201 ` [${constName}${config.arrayRef}]: ${constName}.max_output_tokens,`,
202 )
203 if (maxOutputEntries.length > 0) {
204 next = addToObjectMap(
205 next,
206 config.maxOutputTokensMapName,
207 maxOutputEntries,
208 )
209 }
210 }
211
212 return next
213}