mtcute/packages/node/src/common-internals-node/exit-hook.ts

55 lines
1.3 KiB
TypeScript
Raw Normal View History

// roughly based on https://github.com/sindresorhus/exit-hook/blob/main/index.js, MIT license
let installed = false
let handled = false
const callbacks = new Set<() => void>()
2024-07-01 01:50:43 +03:00
// eslint-disable-next-line func-call-spacing
const myHandlers = new Map<string, () => void>()
2024-07-01 01:50:43 +03:00
function register(shouldManuallyExit: boolean, signal: number, event: string) {
function eventHandler() {
if (handled) {
return
}
handled = true
for (const callback of callbacks) {
callback()
}
2024-07-01 01:50:43 +03:00
for (const [event, handler] of myHandlers) {
process.off(event, handler)
}
2024-07-01 01:50:43 +03:00
if (shouldManuallyExit) {
// send the signal again and let node handle it
process.kill(process.pid, signal)
}
}
2024-07-01 01:50:43 +03:00
process.on(event, eventHandler)
myHandlers.set(event, eventHandler)
}
export function beforeExit(fn: () => void): () => void {
// unsupported platform
if (typeof process === 'undefined') return () => {}
if (!installed) {
installed = true
2024-07-01 01:50:43 +03:00
register(true, 0, 'beforeExit')
register(true, 2, 'SIGINT')
register(true, 15, 'SIGTERM')
register(false, 15, 'exit')
}
callbacks.add(fn)
return () => {
callbacks.delete(fn)
}
}