import ts from 'typescript' ; import Logger from './logger' ; import { convertErrors , outputErrors } from './format-errors' ; import { CompilerHost } from './compiler-host' ; import { resolveOptions } from './resolve-options' ; import { transpile } from './transpiler' ; import { isTypescript , isTypescriptDeclaration , isJson , stripDoubleExtension } from './utils' ; const logger = new Logger ( { debug : false } ) ; const host = getHost ( ) ; function getHost ( ) { const __global = typeof ( self ) !== 'undefined' ? self : global ; __global . tsHost = __global . tsHost || new CompilerHost ( ) ; return __global . tsHost ; } export async function translate ( load ) { const loader = this ; logger . debug ( `systemjs translating ${ load . address }` ) ; if ( isJson ( load . address ) ) return load . source ; const options = await resolveOptions ( SystemJS . typescriptOptions , load . metadata . typescriptOptions , load . address , _fetchJson ) ; host . addFile ( load . address , load . source , options . target ) ; if ( isTypescriptDeclaration ( load . address ) ) { load . source = '' ; } else { const result = transpile ( load . address , options , host ) ; load . metadata . tserrors = convertErrors ( result . diags ) ; outputErrors ( load . metadata . tserrors , logger ) ; if ( result . failure ) throw new Error ( 'TypeScript transpilation failed' ) ; load . source = result . js ; if ( isTypescript ( load . address ) ) { if ( options . module === ts . ModuleKind . System ) load . metadata . format = 'register' ; else if ( options . module === ts . ModuleKind . ES2015 ) load . metadata . format = 'esm' ; else if ( options . module === ts . ModuleKind . CommonJS ) load . metadata . format = 'cjs' ; else if ( options . module === ts . ModuleKind . AMD ) load . metadata . format = 'amd' ; } if ( result . sourceMap ) load . metadata . sourceMap = JSON . parse ( result . sourceMap ) ; } return load . source ; } export function instantiate ( load , origInstantiate ) { logger . debug ( `systemjs instantiating ${ load . address }` ) ; return isJson ( load . address ) ? JSON . parse ( load . source ) : origInstantiate ( load ) ; } async function _fetchJson ( fileName , parentAddress ) { const address = await SystemJS . normalize ( fileName , parentAddress ) ; const json = await SystemJS . import ( stripDoubleExtension ( address ) + '!' + __moduleName , parentAddress ) ; logger . debug ( `fetched ${ fileName }` ) ; return JSON . stringify ( json ) ; }