import type { Diagnostic } from '../../declarations' ; import { IS_NODE_ENV } from './environment' ; import { loadTypeScriptDiagnostic , catchError } from '@utils' ; import ts from 'typescript' ; export const nodeRequire = ( id ) => { const results = { module : undefined as any , id , diagnostics : [ ] as Diagnostic [ ] , } ; if ( IS_NODE_ENV ) { try { const fs = require ( 'fs' ) ; const path = require ( 'path' ) ; results . id = path . resolve ( id ) ; delete require . cache [ results . id ] ; require . extensions [ '.ts' ] = ( module , fileName ) => { let sourceText = fs . readFileSync ( fileName , 'utf8' ) ; if ( fileName . endsWith ( '.ts' ) ) { const tsResults = ts . transpileModule ( sourceText , { fileName , compilerOptions : { module : ts . ModuleKind . CommonJS , moduleResolution : ts . ModuleResolutionKind . NodeJs , esModuleInterop : true , target : ts . ScriptTarget . ES2017 , allowJs : true , } , } ) ; sourceText = tsResults . outputText ; results . diagnostics . push ( ... tsResults . diagnostics . map ( loadTypeScriptDiagnostic ) ) ; } else { sourceText = sourceText . replace ( /export\s+\w+\s+(\w+)/gm , 'exports.$1' ) ; } try { module . _compile ( sourceText , fileName ) ; } catch ( e ) { catchError ( results . diagnostics , e ) ; } } ; results . module = require ( results . id ) ; require . extensions [ '.ts' ] = undefined ; } catch ( e ) { catchError ( results . diagnostics , e ) ; } } return results ; } ; interface NodeModuleWithCompile extends NodeModule { _compile ( code , filename ) : any ; }