Open History to see the last commit
1/**
2 * jscodeshift transform: AG-UI client compliance migration
3 *
4 * Renames the deprecated client-side fields introduced by the AG-UI
5 * compliance release of `@tanstack/ai`. Each rename is gated by an
6 * import-source check so we don't touch unrelated code that happens
7 * to share a property name.
8 *
9 * Transforms (all opt-in — the deprecated names keep working):
10 *
11 * 1. `useChat({ body })` → `useChat({ forwardedProps })`
12 * 2. `new ChatClient({ body })` → `new ChatClient({ forwardedProps })`
13 * 3. `client.updateOptions({ body })` → `{ forwardedProps }`
14 * (when `ChatClient` is imported in the file)
15 * 4. `chat.updateBody(x)` → `chat.updateForwardedProps(x)`
16 * (when imported from `@tanstack/ai-svelte`)
17 * 5. `chat({ conversationId })` → `chat({ threadId })`
18 * (when `chat` is imported from `@tanstack/ai`)
19 *
20 * Conflict handling: if both the legacy and canonical key are already
21 * present in the same object literal we leave the property alone — the
22 * user has authored a deliberate mix and a blind rename would create
23 * a duplicate key.
24 */
25
26import type {
27 API,
28 ASTPath,
29 Collection,
30 FileInfo,
31 ImportDeclaration,
32 JSCodeshift,
33 ObjectExpression,
34 Property,
35} from 'jscodeshift'
36
37const FRAMEWORK_USE_CHAT_PACKAGES = new Set([
38 '@tanstack/ai-react',
39 '@tanstack/ai-react/ui',
40 '@tanstack/ai-vue',
41 '@tanstack/ai-vue/ui',
42 '@tanstack/ai-solid',
43 '@tanstack/ai-solid/ui',
44 '@tanstack/ai-preact',
45])
46
47const SVELTE_PACKAGE = '@tanstack/ai-svelte'
48const CLIENT_PACKAGE = '@tanstack/ai-client'
49const CORE_PACKAGE = '@tanstack/ai'
50
51interface ImportFacts {
52 /** Whether `useChat` is imported from a framework package. */
53 hasUseChat: boolean
54 /** Whether `ChatClient` is imported from `@tanstack/ai-client`. */
55 hasChatClient: boolean
56 /** Whether `createChat` is imported from `@tanstack/ai-svelte`. */
57 hasCreateChat: boolean
58 /** Whether `chat` is imported from `@tanstack/ai`. */
59 hasChat: boolean
60}
61
62function collectImportFacts(j: JSCodeshift, root: Collection): ImportFacts {
63 const facts: ImportFacts = {
64 hasUseChat: false,
65 hasChatClient: false,
66 hasCreateChat: false,
67 hasChat: false,
68 }
69
70 root.find(j.ImportDeclaration).forEach((path: ASTPath<ImportDeclaration>) => {
71 const source = path.node.source.value
72 if (typeof source !== 'string') return
73
74 const specifiers = path.node.specifiers ?? []
75 const importedNames = new Set<string>()
76 for (const spec of specifiers) {
77 if (spec.type === 'ImportSpecifier') {
78 importedNames.add(spec.imported.name)
79 }
80 }
81
82 if (
83 FRAMEWORK_USE_CHAT_PACKAGES.has(source) &&
84 importedNames.has('useChat')
85 ) {
86 facts.hasUseChat = true
87 }
88 if (source === CLIENT_PACKAGE && importedNames.has('ChatClient')) {
89 facts.hasChatClient = true
90 }
91 // Gate the Svelte `updateBody` rename on the specific `createChat`
92 // import name, not "any import from the package" — otherwise an
93 // unrelated `.updateBody(...)` call elsewhere in the same file
94 // (a form helper, custom store, etc.) would be silently rewritten.
95 if (source === SVELTE_PACKAGE && importedNames.has('createChat')) {
96 facts.hasCreateChat = true
97 }
98 if (source === CORE_PACKAGE && importedNames.has('chat')) {
99 facts.hasChat = true
100 }
101 })
102
103 return facts
104}
105
106/**
107 * Find a Property by its (Identifier) key name on an ObjectExpression.
108 * Skips spread elements, computed keys, and non-Identifier shorthand keys.
109 */
110function findKey(obj: ObjectExpression, name: string): Property | undefined {
111 for (const prop of obj.properties) {
112 if (prop.type !== 'Property' && prop.type !== 'ObjectProperty') continue
113 if (prop.computed) continue
114 const key = prop.key
115 if (key.type === 'Identifier' && key.name === name) {
116 return prop as Property
117 }
118 }
119 return undefined
120}
121
122/**
123 * Rename a property `oldName` → `newName` on the given object expression
124 * iff `oldName` is present and `newName` is not. Returns
125 * - `'renamed'` when the rename was applied,
126 * - `'conflict'` when both keys were already present and the rename was
127 * skipped (caller should surface this to the user — silently leaving
128 * it alone hides intentional decisions that still need a human merge),
129 * - `'skipped'` otherwise (no `oldName` key found, or the key was not
130 * an Identifier we can safely rewrite).
131 */
132function renameProperty(
133 obj: ObjectExpression,
134 oldName: string,
135 newName: string,
136): 'renamed' | 'conflict' | 'skipped' {
137 const oldProp = findKey(obj, oldName)
138 if (!oldProp) return 'skipped'
139 if (findKey(obj, newName)) {
140 return 'conflict'
141 }
142 if (oldProp.key.type === 'Identifier') {
143 // For shorthand `{ body }`, the AST stores `key === value === Identifier('body')`
144 // (or two equal-named Identifier nodes plus `shorthand: true`). Mutating
145 // only the key would leave the printer emitting `{ forwardedProps }`,
146 // which silently references an undefined identifier in the user's
147 // scope. Expand to long form so the original `body` reference survives:
148 // `{ body }` → `{ forwardedProps: body }`.
149 const propAsAny = oldProp as unknown as {
150 shorthand?: boolean
151 value?: { type?: string; name?: string }
152 }
153 if (
154 propAsAny.shorthand &&
155 propAsAny.value?.type === 'Identifier' &&
156 propAsAny.value.name === oldName
157 ) {
158 // Leave value pointing at the original identifier; only flip
159 // `shorthand` off and rename the key.
160 propAsAny.shorthand = false
161 }
162 oldProp.key.name = newName
163 return 'renamed'
164 }
165 return 'skipped'
166}
167
168interface RenameStats {
169 renamed: number
170 conflicts: Array<{ filePath: string; line?: number; site: string }>
171}
172
173/**
174 * Rename `oldKey` → `newKey` on the first object-literal argument of every
175 * call site whose callee matches `predicate`. Conflicts (both keys already
176 * present) are recorded so the caller can surface them via `api.report`.
177 */
178function renameKeyOnCalls(
179 j: JSCodeshift,
180 root: Collection,
181 filePath: string,
182 predicate: (path: ASTPath<any>) => boolean,
183 oldKey: string,
184 newKey: string,
185 siteLabel: string,
186 stats: RenameStats,
187): void {
188 root
189 .find(j.CallExpression)
190 .filter(predicate)
191 .forEach((path) => {
192 const args = path.node.arguments
193 const objArg = args.find(
194 (a): a is ObjectExpression => a.type === 'ObjectExpression',
195 )
196 if (!objArg) return
197 const outcome = renameProperty(objArg, oldKey, newKey)
198 if (outcome === 'renamed') {
199 stats.renamed++
200 } else if (outcome === 'conflict') {
201 stats.conflicts.push({
202 filePath,
203 line: path.node.loc?.start.line,
204 site: siteLabel,
205 })
206 }
207 })
208}
209
210export default function transform(
211 file: FileInfo,
212 api: API,
213): string | null | undefined {
214 const j = api.jscodeshift
215 const root = j(file.source)
216 const facts = collectImportFacts(j, root)
217
218 // Bail out early if no relevant imports — keeps the codemod a no-op
219 // on files that just happen to use a `body` key in unrelated code.
220 if (
221 !facts.hasUseChat &&
222 !facts.hasChatClient &&
223 !facts.hasCreateChat &&
224 !facts.hasChat
225 ) {
226 return file.source
227 }
228
229 const stats: RenameStats = { renamed: 0, conflicts: [] }
230
231 // 1. useChat({ body }) → useChat({ forwardedProps })
232 if (facts.hasUseChat) {
233 renameKeyOnCalls(
234 j,
235 root,
236 file.path,
237 (path) => {
238 const callee = path.node.callee
239 return callee.type === 'Identifier' && callee.name === 'useChat'
240 },
241 'body',
242 'forwardedProps',
243 'useChat({ body })',
244 stats,
245 )
246 }
247
248 // 2. new ChatClient({ body }) → new ChatClient({ forwardedProps })
249 if (facts.hasChatClient) {
250 root.find(j.NewExpression).forEach((path) => {
251 const callee = path.node.callee
252 if (callee.type !== 'Identifier' || callee.name !== 'ChatClient') return
253 const objArg = path.node.arguments.find(
254 (a): a is ObjectExpression => a.type === 'ObjectExpression',
255 )
256 if (!objArg) return
257 const outcome = renameProperty(objArg, 'body', 'forwardedProps')
258 if (outcome === 'renamed') {
259 stats.renamed++
260 } else if (outcome === 'conflict') {
261 stats.conflicts.push({
262 filePath: file.path,
263 line: path.node.loc?.start.line,
264 site: 'new ChatClient({ body })',
265 })
266 }
267 })
268
269 // 3. <client>.updateOptions({ body }) → { forwardedProps }
270 //
271 // We can't always tell statically that `<client>` is a ChatClient
272 // instance, so we gate the whole transform on the file importing
273 // ChatClient (already checked) and pattern-match on the method
274 // name. `updateOptions` is distinctive enough that false matches
275 // are unlikely in a TanStack AI codebase.
276 renameKeyOnCalls(
277 j,
278 root,
279 file.path,
280 (path) => {
281 const callee = path.node.callee
282 return (
283 callee.type === 'MemberExpression' &&
284 !callee.computed &&
285 callee.property.type === 'Identifier' &&
286 callee.property.name === 'updateOptions'
287 )
288 },
289 'body',
290 'forwardedProps',
291 'updateOptions({ body })',
292 stats,
293 )
294 }
295
296 // 4. chat.updateBody(x) → chat.updateForwardedProps(x)
297 if (facts.hasCreateChat) {
298 root.find(j.MemberExpression).forEach((path) => {
299 if (path.node.computed) return
300 if (path.node.property.type !== 'Identifier') return
301 if (path.node.property.name !== 'updateBody') return
302 path.node.property.name = 'updateForwardedProps'
303 stats.renamed++
304 })
305 }
306
307 // 5. chat({ conversationId }) → chat({ threadId })
308 if (facts.hasChat) {
309 renameKeyOnCalls(
310 j,
311 root,
312 file.path,
313 (path) => {
314 const callee = path.node.callee
315 return callee.type === 'Identifier' && callee.name === 'chat'
316 },
317 'conversationId',
318 'threadId',
319 'chat({ conversationId })',
320 stats,
321 )
322 }
323
324 // Surface conflicts so users can resolve them by hand. The codemod
325 // intentionally leaves `{ body, forwardedProps }` (or other dual-key)
326 // objects alone — silently swallowing them would either drop one
327 // value or produce a duplicate-key object literal.
328 for (const conflict of stats.conflicts) {
329 const where =
330 conflict.line !== undefined
331 ? `${conflict.filePath}:${conflict.line}`
332 : conflict.filePath
333 api.report(
334 `[ag-ui-compliance] ${where} — ${conflict.site}: both legacy and canonical keys are already present; left alone. Merge by hand.`,
335 )
336 }
337
338 return stats.renamed > 0 ? root.toSource() : file.source
339}
340
341// jscodeshift inspects `.parser` on the default export to choose its
342// AST flavor. We support both .ts and .tsx out of the box.
343;(transform as unknown as { parser: string }).parser = 'tsx'