-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
87 lines (68 loc) · 1.88 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const process = require('process')
const safetyCatch = require('safety-catch')
module.exports = goodbye
const handlers = []
let exitCode = 0
let forceExit = false
goodbye.exiting = false
goodbye.exit = exit
const onsigint = onsignal.bind(null, 'SIGINT')
const onsigterm = onsignal.bind(null, 'SIGTERM')
function onsignal (name) {
forceExit = forceExit || process.listenerCount(name) === 1
process.removeListener('SIGINT', onsigint)
process.removeListener('SIGTERM', onsigterm)
exitCode = 130
onexit()
}
function onexit () {
if (goodbye.exiting) return
goodbye.exiting = true
process.removeListener('beforeExit', onexit)
const order = []
for (const h of handlers.sort((a, b) => b.position - a.position)) {
if (!order.length || order[order.length - 1][0].position !== h.position) order.push([])
order[order.length - 1].push(h)
}
loop()
function loop () {
if (!order.length) return done()
Promise.allSettled(order.pop().map(run)).then(loop, loop)
}
function done () {
if (forceExit) process.exit(exitCode)
}
}
async function run (h) {
try {
await h.fn()
} catch (e) {
safetyCatch(e)
}
}
function setup () {
process.prependListener('beforeExit', onexit)
process.prependListener('SIGINT', onsigint)
process.prependListener('SIGTERM', onsigterm)
}
function cleanup () {
process.removeListener('beforeExit', onexit)
process.removeListener('SIGINT', onsigint)
process.removeListener('SIGTERM', onsigterm)
}
function goodbye (fn, position = 0) {
if (handlers.length === 0) setup()
const handler = { position, fn }
handlers.push(handler)
return function unregister () {
const i = handlers.indexOf(handler)
if (i > -1) handlers.splice(i, 1)
if (!handlers.length) cleanup()
}
}
function exit () {
forceExit = true
process.removeListener('SIGINT', onsigint)
process.removeListener('SIGTERM', onsigterm)
onexit()
}