import { Observable } from 'rxjs'; import { createSourceFile, ScriptTarget, SourceFile } from 'typescript'; import { InsertChange } from '../ast-utils/change'; import { addImportToModule } from './../ast-utils/ast-utils'; import { rxReadTextFile } from './rx.file'; import { map } from 'rxjs/operators'; export interface TypescriptFile { source: string; path: string; ast: SourceFile; } export function rxReadTypescriptFile(aPath: string): Observable { // read return rxReadTextFile(aPath).pipe( map(src => ({ source: src, path: aPath, ast: createSourceFile(aPath, src, ScriptTarget.Latest, true) })) ); } function _insertLeft(aPos: number, aChange: string, aTotal: string): string { return aTotal.substr(0, aPos) + aChange + aTotal.substr(aPos); } export function importModule(aName: string, aIdentifier: string, aFile: TypescriptFile): TypescriptFile { const declarationChanges = addImportToModule( aFile.ast, aFile.path, aName, aIdentifier); let result = aFile.source; for (const change of declarationChanges) { if (change instanceof InsertChange) { result = _insertLeft(change.pos, change.toAdd, result); } } return { path: aFile.path, source: result, ast: createSourceFile(aFile.path, result, ScriptTarget.Latest, true) }; }