import * as ts from 'typescript' ; import { Rule , Tree } from '@angular-devkit/schematics' ; import { findModule } from '@schematics/angular/utility/find-module' ; import { convertModulePathToPublicAPIImport , convertToAbsolutPath , getFolderPath } from '../shared/path-helper' ; import { logError } from '../shared/log-helper' ; interface Modification { startPosition : number ; endPosition : number ; content : string ; } export function updateImportPaths ( filePath ) { return ( tree ) => { let modifications = getImportPathModifications ( tree , filePath ) ; let source = tree . read ( filePath ) . toString ( ) ; for ( let modification of modifications . reverse ( ) ) { source = source . slice ( 0 , modification . startPosition ) + modification . content + source . slice ( modification . endPosition ) ; } tree . overwrite ( filePath , source ) ; return tree ; } ; } function getImportPathModifications ( tree , filePath ) { const sourceCode = tree . read ( filePath ) . toString ( ) ; const rootNode = ts . createSourceFile ( filePath , sourceCode , ts . ScriptTarget . Latest , true ) ; const modifications = [ ] ; const modulePathFileBelongsTo = findModule ( tree , getFolderPath ( filePath ) ) ; function updatePaths ( node ) { if ( ts . isImportDeclaration ( node ) ) { const importSegments = node . getChildren ( ) ; const importNode = importSegments . find ( segment => segment . kind === ts . SyntaxKind . StringLiteral ) ; if ( importNode && ! isThirdPartyLibImport ( importNode ) && importsForeignModuleCode ( importNode , modulePathFileBelongsTo , filePath , tree ) ) { const moduleFromImportPath = getModulePathFromImport ( importNode . getText ( ) , filePath , tree ) ; modifications . push ( { startPosition : importNode . pos + 1 , endPosition : importNode . end + 1 , content : `'${ convertModulePathToPublicAPIImport ( moduleFromImportPath ) }';` } ) ; } } } rootNode . forEachChild ( updatePaths ) ; return modifications ; } function isThirdPartyLibImport ( importNode ) { return ! importNode . getText ( ) . startsWith ( `'.` ) ; } function importsForeignModuleCode ( importNode , modulePathFileBelongsToPath , filePath , tree ) { const importStringLiteral = importNode . getText ( ) ; return ( modulePathFileBelongsToPath !== getModulePathFromImport ( importStringLiteral , filePath , tree ) ) ; } function getModulePathFromImport ( importLiteral , filePath , tree ) { try { return findModule ( tree , convertToAbsolutPath ( filePath , importLiteral ) ) ; } catch ( e ) { logError ( `Could not find a module for the import path ${ importLiteral } in ${ filePath }. 
    Please adjust the import path and rerun the schematics` ) ; process . exit ( ) ; } }