import ts from 'typescript' ; import { CompilerHost , TranspileResult } from './compiler-host' ; import { isJavaScript , isJSX , isSourceMap , hasError } from './utils' ; import Logger from './logger' ; const logger = new Logger ( { debug : false } ) ; export function transpile ( sourceName , options , host ) { logger . debug ( `transpiling ${ sourceName }` ) ; const file = host . getSourceFile ( sourceName ) ; if ( ! file ) throw new Error ( `file [${ sourceName }] has not been added` ) ; if ( ! file . output ) { const transpileOptions = getTranspileOptions ( options ) ; const program = ts . createProgram ( [ sourceName ] , transpileOptions , host ) ; let jstext = undefined ; let maptext = undefined ; const emitResult = program . emit ( undefined , ( outputName , output ) => { if ( isJavaScript ( outputName ) || isJSX ( outputName ) ) jstext = output . slice ( 0 , output . lastIndexOf ( "//#" ) ) ; else if ( isSourceMap ( outputName ) ) maptext = output ; else throw new Error ( `unexpected ouput file ${ outputName }` ) ; } ) ; const diagnostics = emitResult . diagnostics . concat ( program . getOptionsDiagnostics ( ) ) . concat ( program . getSyntacticDiagnostics ( ) ) ; file . output = { failure : hasError ( diagnostics ) , diags : diagnostics , js : jstext , sourceMap : maptext } ; } return file . output ; } function getTranspileOptions ( options ) { const result = ( < any > ts ) . clone ( options ) as ts . CompilerOptions ; result . isolatedModules = true ; if ( result . sourceMap === undefined ) result . sourceMap = result . inlineSourceMap ; if ( result . sourceMap === undefined ) result . sourceMap = true ; result . inlineSourceMap = false ; result . declaration = false ; result . noEmitOnError = false ; result . out = undefined ; result . outFile = undefined ; result . noLib = true ; result . lib = undefined ; result . types = [ ] ; result . suppressOutputPathCheck = true ; result . noEmit = false ; return result ; }