import * as vscode from 'vscode' ; import jscodeshift , { ImportDeclaration , ASTPath } from 'jscodeshift' ; import { getParserSync } from 'babel-parse-wild-code' ; export default function getExistingImports ( document ) { const text = document . getText ( ) ; const parser = getParserSync ( document . uri . fsPath , { tokens : true } ) ; const j = parser ? jscodeshift . withParser ( parser ) : jscodeshift ; const components = new Set ( ) ; const icons = new Set ( ) ; let muiVersion = null ; let insertLine = 0 ; let coreInsertPosition = null ; let iconsInsertPosition = null ; let root ; try { root = j ( text ) ; } catch ( error ) { root = j . withParser ( 'flow' ) ( text ) ; } root . find ( j . ImportDeclaration ) . forEach ( ( { node } ) : void => { if ( ! node ) return ; if ( node . loc ) insertLine = node . loc . end . line ; const source = node . source . value ; if ( typeof source !== 'string' ) return ; if ( source . startsWith ( '@material-ui/' ) ) muiVersion = 4 ; else if ( source . startsWith ( '@mui/' ) ) muiVersion = 5 ; if ( source === '@material-ui/core' || source === '@mui/material' ) { for ( const specifier of node . specifiers ) { if ( specifier . type !== 'ImportSpecifier' ) continue ; const { loc } = specifier ; if ( loc ) { const { line , column } = loc . end ; coreInsertPosition = new vscode . Position ( line - 1 , column ) ; } const { imported , local } = specifier ; if ( imported && local && imported . name === local . name ) { components . add ( local . name ) ; } } } else if ( source === '@material-ui/icons' || source === '@mui/icons-material' ) { for ( const specifier of node . specifiers ) { if ( specifier . type !== 'ImportSpecifier' ) continue ; const { loc } = specifier ; if ( loc ) { const { line , column } = loc . end ; iconsInsertPosition = new vscode . Position ( line - 1 , column ) ; } const { imported , local } = specifier ; if ( imported && local && imported . name + 'Icon' === local . name ) { icons . add ( local . name ) ; } } } else { const match = /^(@material-ui\/core|@material-ui\/icons|@mui\/material|@mui\/icons-material)\/([^/]+)/ . exec ( source ) ; if ( match ) { if ( match [ 1 ] === '@material-ui/icons' || match [ 1 ] === '@mui/icons-material' ) { icons . add ( match [ 2 ] ) ; } else { components . add ( match [ 2 ] ) ; } } } } ) ; return { existingComponents : components , existingIcons : icons , insertPosition : new vscode . Position ( insertLine , 0 ) , coreInsertPosition , iconsInsertPosition , muiVersion , } ; }