import { sameImport } from '@codemods/named-import/sameImport' ; import { membersMatchingPred } from '@codemods/members-matching-pred' ; import { unique , makeImport } from '@codemods/utils' ; import { findImportFilter } from '@codemods/find-import' ; type AddNamedImport = { root : any ; j : any ; importName : string ; specifier : string ; localName : string ; } ; export const addNamedImport = ( { root , j , importName , specifier , localName , defaultName , } ) => { const importNameDeclaration = findImportFilter ( root , j , importName ) ; if ( importNameDeclaration . length > 0 ) { const importSpecifiers = importNameDeclaration . find ( j . ImportSpecifier ) . filter ( ( path ) => path . node . imported . name === specifier ) ; if ( importSpecifiers . length === 0 ) { const existingMembers = membersMatchingPred ( j , importNameDeclaration , ( ) => true ) ; const newImports = specifier || localName ? [ ... existingMembers , { imported : specifier , local : localName } , ] : existingMembers ; const targetMembers = unique ( newImports , sameImport ) ; let oldDefaultImport = null ; root . find ( j . ImportDeclaration ) . filter ( ( path ) => path . node . source . value === importName ) . forEach ( ( path ) => { path . node . specifiers . forEach ( ( s ) => { if ( s . type === 'ImportDefaultSpecifier' ) { oldDefaultImport = s . local . name ; } } ) ; } ) ; const newImport = makeImport ( j , { members : targetMembers , module : importName , defaultName : defaultName || oldDefaultImport } ) ; importNameDeclaration . replaceWith ( newImport ) ; } } else { const imports = root . find ( j . ImportDeclaration ) ; const specifiers = defaultName ? [ j . importDefaultSpecifier ( j . identifier ( defaultName ) ) ] : [ j . importSpecifier ( j . identifier ( specifier ) , j . identifier ( localName || specifier ) ) , ] ; const newNamedImport = j . importDeclaration ( specifiers , j . literal ( importName ) ) ; if ( imports . length > 0 ) { j ( imports . at ( imports . length - 1 ) . get ( ) ) . insertAfter ( newNamedImport ) ; } else { root . get ( ) . node . program . body . unshift ( newNamedImport ) ; } } } ;