const DEFAULT_MESSAGES = { ctrlC : "[ctrl-C]" , uncaughtException : "Uncaught exception..." , } ; interface SignalMessages { ctrlC : string ; uncaughtException : string ; } interface CleanupHandler { ( code , signal ? ) : boolean ; } interface SignalHandle { ( signal ) : void ; } let inited = false ; let cleanupHandlers = [ ] ; let messages = null ; let sigintHandler ; let sighupHandler ; let sigquitHandler ; let sigtermHandler ; function exceptionHandler ( e ) { if ( messages && messages . uncaughtException !== "" ) { process . stderr . write ( messages . uncaughtException + "\n" ) ; } process . stderr . write ( e . stack + "\n" ) ; process . exit ( 1 ) ; } function exitHandler ( exitCode ) { cleanupHandlers . forEach ( function ( cleanup ) { cleanup ( exitCode ) ; } ) ; } function uninstall ( ) { if ( cleanupHandlers . length > 0 ) { process . removeListener ( "SIGINT" , sigintHandler ) ; process . removeListener ( "SIGHUP" , sighupHandler ) ; process . removeListener ( "SIGQUIT" , sigquitHandler ) ; process . removeListener ( "SIGTERM" , sigtermHandler ) ; process . removeListener ( "uncaughtException" , exceptionHandler ) ; process . removeListener ( "exit" , exitHandler ) ; cleanupHandlers = [ ] ; } } function createSignalHandler ( signal ) { return function ( ) : void { let exit = true ; cleanupHandlers . forEach ( function ( cleanup ) { exit = ! ! cleanup ( null , signal ) ; } ) ; if ( exit ) { if ( signal === "SIGINT" && messages && messages . ctrlC !== "" ) { process . stderr . write ( messages . ctrlC + "\n" ) ; } uninstall ( ) ; process . kill ( process . pid , signal ) ; } } ; } function install ( cleanupHandler , stderrMessages = DEFAULT_MESSAGES ) { if ( messages === null ) messages = { ctrlC : "" , uncaughtException : "" } ; if ( typeof stderrMessages . ctrlC === "string" ) messages . ctrlC = stderrMessages . ctrlC ; if ( typeof stderrMessages . uncaughtException === "string" ) messages . uncaughtException = stderrMessages . uncaughtException ; if ( ! inited ) { sigintHandler = createSignalHandler ( "SIGINT" ) ; sighupHandler = createSignalHandler ( "SIGHUP" ) ; sigquitHandler = createSignalHandler ( "SIGQUIT" ) ; sigtermHandler = createSignalHandler ( "SIGTERM" ) ; process . on ( "SIGINT" , sigintHandler ) ; process . on ( "SIGHUP" , sighupHandler ) ; process . on ( "SIGQUIT" , sigquitHandler ) ; process . on ( "SIGTERM" , sigtermHandler ) ; process . on ( "uncaughtException" , exceptionHandler ) ; process . on ( "exit" , exitHandler ) ; inited = true ; } cleanupHandlers . push ( cleanupHandler ) ; } export function onExit ( callback ) { install ( ( ) => { callback ( ) ; return true ; } ) ; }