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

transform.ts

380 lines12.6 KB

1/**
2 * jscodeshift transform: move root sampling options into provider-native
3 * `modelOptions`.
4 *
5 * The root-level `temperature` / `topP` / `maxTokens` convenience props on
6 * `chat()` / `ai()` / `generate()` / `createChatOptions()` are being moved
7 * into the provider-native `modelOptions` object. Each provider names these
8 * options differently, so the rename is provider-specific and resolved from
9 * the `adapter:` property's factory call (e.g. `openaiText('gpt-4o')`).
10 *
11 * Per-provider rename of the three root keys:
12 *
13 * openai: temperature → temperature, topP → top_p, maxTokens → max_output_tokens
14 * anthropic: temperature → temperature, topP → top_p, maxTokens → max_tokens
15 * gemini: temperature → temperature, topP → topP, maxTokens → maxOutputTokens
16 * grok: temperature → temperature, topP → top_p, maxTokens → max_tokens
17 * groq: temperature → temperature, topP → top_p, maxTokens → max_completion_tokens
18 * openrouter: temperature → temperature, topP → topP, maxTokens → maxCompletionTokens
19 * ollama: NESTED inside a `options` object —
20 * temperature → options.temperature, topP → options.top_p, maxTokens → options.num_predict
21 *
22 * This is a breaking change: the root props have been removed, so this
23 * codemod migrates existing call sites onto the new `modelOptions` shape.
24 *
25 * Skip + report (via `api.report`) behavior, never partially transforming a
26 * single call:
27 * - the adapter can't be resolved to a known provider factory (missing
28 * `adapter`, dynamic/spread adapter, or unknown callee);
29 * - `modelOptions` exists but isn't a plain object literal;
30 * - a target renamed key already exists in `modelOptions` (or in
31 * `modelOptions.options` for ollama).
32 */
33​
34import type {
35 API,
36 ASTPath,
37 CallExpression,
38 Collection,
39 FileInfo,
40 Identifier,
41 ImportDeclaration,
42 JSCodeshift,
43 ObjectExpression,
44 Property,
45} from 'jscodeshift'
46​
47const CORE_PACKAGE = '@tanstack/ai'
48​
49/** Helper names (imported from `@tanstack/ai`) we operate on. */
50const TARGET_CALLEES = new Set(['chat', 'ai', 'generate', 'createChatOptions'])
51​
52/** The three root sampling props we relocate. */
53const ROOT_SAMPLING_KEYS = ['temperature', 'topP', 'maxTokens'] as const
54type RootSamplingKey = (typeof ROOT_SAMPLING_KEYS)[number]
55​
56type Provider =
57 | 'openai'
58 | 'anthropic'
59 | 'gemini'
60 | 'grok'
61 | 'groq'
62 | 'openrouter'
63 | 'ollama'
64​
65/**
66 * Map a provider text-adapter factory name → provider. Factory names were
67 * confirmed against each provider package's `index.ts` exports. Note the
68 * OpenRouter factory is `openRouterText` (capital R); `openrouterText` is
69 * accepted defensively but is not a real export.
70 */
71const FACTORY_TO_PROVIDER: Record<string, Provider> = {
72 openaiText: 'openai',
73 anthropicText: 'anthropic',
74 geminiText: 'gemini',
75 grokText: 'grok',
76 groqText: 'groq',
77 openRouterText: 'openrouter',
78 openrouterText: 'openrouter',
79 ollamaText: 'ollama',
81​
82/**
83 * Per-provider rename of each root key → its `modelOptions` key name. For
84 * ollama the renamed keys live inside a nested `options` object (handled
85 * separately), so the names here are the keys *within* that nested object.
86 */
87const RENAME: Record<Provider, Record<RootSamplingKey, string>> = {
88 openai: {
89 temperature: 'temperature',
90 topP: 'top_p',
91 maxTokens: 'max_output_tokens',
92 },
93 anthropic: {
94 temperature: 'temperature',
95 topP: 'top_p',
96 maxTokens: 'max_tokens',
97 },
98 gemini: {
99 temperature: 'temperature',
100 topP: 'topP',
101 maxTokens: 'maxOutputTokens',
102 },
103 grok: {
104 temperature: 'temperature',
105 topP: 'top_p',
106 maxTokens: 'max_tokens',
107 },
108 groq: {
109 temperature: 'temperature',
110 topP: 'top_p',
111 maxTokens: 'max_completion_tokens',
112 },
113 openrouter: {
114 temperature: 'temperature',
115 topP: 'topP',
116 maxTokens: 'maxCompletionTokens',
117 },
118 ollama: {
119 temperature: 'temperature',
120 topP: 'top_p',
121 maxTokens: 'num_predict',
122 },
124​
125/** ollama nests the renamed keys inside a `modelOptions.options` object. */
126const PROVIDERS_WITH_NESTED_OPTIONS = new Set<Provider>(['ollama'])
127​
128interface ImportFacts {
129 /** Whether any helper we transform is imported from `@tanstack/ai`. */
130 hasCoreHelper: boolean
132​
133function collectImportFacts(j: JSCodeshift, root: Collection): ImportFacts {
134 const facts: ImportFacts = { hasCoreHelper: false }
135​
136 root.find(j.ImportDeclaration).forEach((path: ASTPath<ImportDeclaration>) => {
137 const source = path.node.source.value
138 if (source !== CORE_PACKAGE) return
139 const specifiers = path.node.specifiers ?? []
140 for (const spec of specifiers) {
141 if (
142 spec.type === 'ImportSpecifier' &&
143 TARGET_CALLEES.has(spec.imported.name)
144 ) {
145 facts.hasCoreHelper = true
146 }
147 }
148 })
149​
150 return facts
152​
153/**
154 * Find a non-computed, non-spread Property by its Identifier key name.
155 * Handles both `Property` (ESTree) and `ObjectProperty` (Babel) node types.
156 */
157function findKey(obj: ObjectExpression, name: string): Property | undefined {
158 for (const prop of obj.properties) {
159 if (prop.type !== 'Property' && prop.type !== 'ObjectProperty') continue
160 if ((prop as Property).computed) continue
161 const key = (prop as Property).key
162 if (key.type === 'Identifier' && key.name === name) {
163 return prop as Property
164 }
165 }
166 return undefined
168​
169/**
170 * Extract the value expression of a property, expanding shorthand. For a
171 * shorthand `{ temperature }`, the value is the `temperature` Identifier,
172 * which is exactly the reference we want to preserve when relocating.
173 */
174function valueOf(prop: Property): Property['value'] {
175 return prop.value
177​
178/** The first object-literal argument of a call, or undefined. */
179function firstObjectArg(node: CallExpression): ObjectExpression | undefined {
180 return node.arguments.find(
181 (a): a is ObjectExpression => a.type === 'ObjectExpression',
182 )
184​
185/**
186 * Resolve the provider from a call's first object argument by inspecting its
187 * `adapter` property. Returns the provider, or `null` if it can't be
188 * resolved (no adapter, non-call adapter, spread, or unknown factory).
189 */
190function resolveProvider(obj: ObjectExpression): Provider | null {
191 const adapterProp = findKey(obj, 'adapter')
192 if (!adapterProp) return null
193 const value = adapterProp.value
194 if (!value || value.type !== 'CallExpression') return null
195 const callee = (value as CallExpression).callee
196 if (callee.type !== 'Identifier') return null
197 const provider = FACTORY_TO_PROVIDER[(callee as Identifier).name]
198 return provider ?? null
200​
201interface Conflict {
202 filePath: string
203 line?: number
204 reason: string
206​
207export default function transform(
208 file: FileInfo,
209 api: API,
210): string | null | undefined {
211 const j = api.jscodeshift
212 const root = j(file.source)
213 const facts = collectImportFacts(j, root)
214​
215 // Bail out early if none of the target helpers are imported from
216 // `@tanstack/ai` — keeps the codemod a no-op on unrelated files that
217 // happen to use a `temperature`/`topP`/`maxTokens` key.
218 if (!facts.hasCoreHelper) {
219 return file.source
220 }
221​
222 let changed = 0
223 const conflicts: Array<Conflict> = []
224​
225 root
226 .find(j.CallExpression)
227 .filter((path) => {
228 const callee = path.node.callee
229 return callee.type === 'Identifier' && TARGET_CALLEES.has(callee.name)
230 })
231 .forEach((path: ASTPath<CallExpression>) => {
232 const obj = firstObjectArg(path.node)
233 if (!obj) return
234​
235 // Only act if at least one root sampling prop is present.
236 const presentKeys = ROOT_SAMPLING_KEYS.filter((k) => findKey(obj, k))
237 if (presentKeys.length === 0) return
238​
239 const line = path.node.loc?.start.line
240 const calleeName =
241 path.node.callee.type === 'Identifier' ? path.node.callee.name : 'call'
242​
243 // Resolve the provider from the adapter. Skip + report if we can't.
244 const provider = resolveProvider(obj)
245 if (!provider) {
246 conflicts.push({
247 filePath: file.path,
248 line,
249 reason: `${calleeName}(): could not resolve a known provider adapter from the \`adapter\` property; left alone.`,
250 })
251 return
252 }
253​
254 const renameMap = RENAME[provider]
255 const nested = PROVIDERS_WITH_NESTED_OPTIONS.has(provider)
256​
257 // Validate / locate modelOptions before mutating anything, so a
258 // conflict aborts the WHOLE call without a partial transform.
259 let modelOptionsObj: ObjectExpression | null = null
260 const modelOptionsProp = findKey(obj, 'modelOptions')
261 if (modelOptionsProp) {
262 if (modelOptionsProp.value.type !== 'ObjectExpression') {
263 conflicts.push({
264 filePath: file.path,
265 line,
266 reason: `${calleeName}(): \`modelOptions\` exists but is not a plain object literal; left alone. Merge by hand.`,
267 })
268 return
269 }
270 modelOptionsObj = modelOptionsProp.value as ObjectExpression
271 }
272​
273 // For ollama, locate/validate the nested `options` object too.
274 let nestedOptionsObj: ObjectExpression | null = null
275 if (nested && modelOptionsObj) {
276 const optionsProp = findKey(modelOptionsObj, 'options')
277 if (optionsProp) {
278 if (optionsProp.value.type !== 'ObjectExpression') {
279 conflicts.push({
280 filePath: file.path,
281 line,
282 reason: `${calleeName}(): \`modelOptions.options\` exists but is not a plain object literal; left alone. Merge by hand.`,
283 })
284 return
285 }
286 nestedOptionsObj = optionsProp.value as ObjectExpression
287 }
288 }
289​
290 // Conflict check: would any renamed target key collide with an
291 // existing key in the destination object?
292 const destForCheck = nested ? nestedOptionsObj : modelOptionsObj
293 let hasConflict = false
294 for (const key of presentKeys) {
295 const renamed = renameMap[key]
296 if (destForCheck && findKey(destForCheck, renamed)) {
297 hasConflict = true
298 break
299 }
300 }
301 if (hasConflict) {
302 conflicts.push({
303 filePath: file.path,
304 line,
305 reason: `${calleeName}(): a target key already exists in ${
306 nested ? '`modelOptions.options`' : '`modelOptions`'
307 }; left alone. Merge by hand.`,
308 })
309 return
310 }
311​
312 // ---- All validations passed; perform the move. ----
313​
314 // Build the renamed properties, preserving original value expressions.
315 const movedProps: Array<Property> = presentKeys.map((key) => {
316 const original = findKey(obj, key)!
317 const renamed = renameMap[key]
318 const value = valueOf(original)
319 const moved = j.property('init', j.identifier(renamed), value)
320 // Emit ES6 shorthand (`temperature`) rather than `temperature:
321 // temperature` when the value is exactly the same identifier as the
322 // (renamed) destination key — e.g. a shorthand `{ temperature }` whose
323 // provider key is unchanged.
324 if (value.type === 'Identifier' && value.name === renamed) {
325 moved.shorthand = true
326 }
327 return moved
328 })
329​
330 // Ensure the destination object exists.
331 if (!modelOptionsObj) {
332 modelOptionsObj = j.objectExpression([])
333 obj.properties.push(
334 j.property('init', j.identifier('modelOptions'), modelOptionsObj),
335 )
336 }
337​
338 if (nested) {
339 if (!nestedOptionsObj) {
340 nestedOptionsObj = j.objectExpression([])
341 modelOptionsObj.properties.push(
342 j.property('init', j.identifier('options'), nestedOptionsObj),
343 )
344 }
345 nestedOptionsObj.properties.push(...movedProps)
346 } else {
347 modelOptionsObj.properties.push(...movedProps)
348 }
349​
350 // Remove the moved root props from the call's first arg.
351 const movedSet = new Set<string>(presentKeys)
352 obj.properties = obj.properties.filter((prop) => {
353 if (prop.type !== 'Property' && prop.type !== 'ObjectProperty') {
354 return true
355 }
356 if ((prop as Property).computed) return true
357 const key = (prop as Property).key
358 if (key.type === 'Identifier' && movedSet.has(key.name)) {
359 return false
360 }
361 return true
362 })
363​
364 changed++
365 })
366​
367 for (const conflict of conflicts) {
368 const where =
369 conflict.line !== undefined
370 ? `${conflict.filePath}:${conflict.line}`
371 : conflict.filePath
372 api.report(`[move-sampling-to-model-options] ${where} — ${conflict.reason}`)
373 }
374​
375 return changed > 0 ? root.toSource() : file.source
377​
378// jscodeshift inspects `.parser` on the default export to choose its
379// AST flavor. We support both .ts and .tsx out of the box.
380;(transform as unknown as { parser: string }).parser = 'tsx'