@@ -243,6 +243,7 @@ export function inlineFunctionAliases(binding: Binding): { changes: number } {
243243export function inlineVariableAliases (
244244 binding : Binding ,
245245 targetName = binding . identifier . name ,
246+ rootTargetName = targetName ,
246247) : { changes : number } {
247248 const state = { changes : 0 }
248249 const refs = [ ...binding . referencePaths ]
@@ -267,8 +268,9 @@ export function inlineVariableAliases(
267268 // Avoid infinite loop from `alias = alias;` (caused by dead code injection?)
268269 if ( ref . isIdentifier ( { name : varBinding . identifier . name } ) ) continue
269270
270- // Check all further aliases (`var alias2 = alias;`)
271- state . changes += inlineVariableAliases ( varBinding , targetName ) . changes
271+ // Use current var name when recursing so we only unwind one level (e.g. alias2 -> alias).
272+ // Pass rootTargetName so refs in same scope can be renamed to the root (e.g. decoder).
273+ state . changes += inlineVariableAliases ( varBinding , varName . current ! , rootTargetName ) . changes
272274
273275 if ( ref . parentPath ?. isAssignmentExpression ( ) ) {
274276 // Remove `var alias;` when the assignment happens separately
@@ -279,8 +281,11 @@ export function inlineVariableAliases(
279281 ref . parentPath . remove ( )
280282 }
281283 else {
282- // Replace `(alias = decoder)(1);` with `decoder(1);`
283- ref . parentPath . replaceWith ( t . identifier ( targetName ) )
284+ // Replace `(alias = decoder)(1);` with `decoder(1);` or `(alias2 = alias)(4)` with `alias(4)`.
285+ // When we're the RHS of an assignment that is a callee, use targetName so the call keeps the alias (e.g. alias(4)).
286+ const isCalleeAssignment = ref . parentKey === 'right' && ref . parentPath ?. parentPath ?. isCallExpression ( )
287+ const nameToUse = isCalleeAssignment ? targetName : ( binding . identifier . name === targetName ? rootTargetName : targetName )
288+ ref . parentPath . replaceWith ( t . identifier ( nameToUse ) )
284289 }
285290 }
286291 else if ( ref . parentPath ?. isVariableDeclarator ( ) ) {
@@ -290,9 +295,15 @@ export function inlineVariableAliases(
290295 state . changes ++
291296 }
292297 else {
293- // Rename the reference
294- ref . replaceWith ( t . identifier ( targetName ) )
295- state . changes ++
298+ // Only rename when the reference is in the same scope as the binding.
299+ // Direct alias of root (binding.name === targetName): use rootTargetName so alias(2) -> decoder(2).
300+ // Deeper alias (e.g. alias2): use targetName so alias2(4) -> alias(4).
301+ // Refs in nested scopes are left as-is so alias(4) stays.
302+ if ( ref . scope === binding . scope ) {
303+ const nameToUse = binding . identifier . name === targetName ? rootTargetName : targetName
304+ ref . replaceWith ( t . identifier ( nameToUse ) )
305+ state . changes ++
306+ }
296307 }
297308 }
298309
0 commit comments