'use strict'; const node_events = require('node:events'); const emitter = new node_events.EventEmitter(); const context = { triggered: false, terminate: "kill", exit: void 0, kill: void 0 }; const handlers = { SIGINT: makeHandler("SIGINT"), SIGTERM: makeHandler("SIGTERM"), SIGQUIT: makeHandler("SIGQUIT") }; function onDeath(callback, { SIGINT = true, SIGTERM = true, SIGQUIT = true } = {}) { const cleanUps = []; if (SIGINT) { registerCallback("SIGINT", handlers.SIGINT); cleanUps.push(handlers.SIGINT.addCallback(callback)); } if (SIGTERM) { registerCallback("SIGTERM", handlers.SIGTERM); cleanUps.push(handlers.SIGTERM.addCallback(callback)); } if (SIGQUIT) { registerCallback("SIGQUIT", handlers.SIGQUIT); cleanUps.push(handlers.SIGQUIT.addCallback(callback)); } return () => { for (const cleanUp of cleanUps) { cleanUp(); } }; } function useDeath(callback, options = {}) { const cancel = onDeath(callback, options); return { [Symbol.dispose]: () => { cancel(); } }; } function registerCallback(signal, handler) { if (handler.count === 0) { handler.count += 1; process.addListener(signal, handler.listener); } } function makeHandler(signal) { const callbacks = /* @__PURE__ */ new WeakMap(); return { count: 0, callbacks, addCallback(callback) { { const count = callbacks.get(callback); if (count !== void 0) { callbacks.set(callback, count + 1); } else { callbacks.set(callback, 1); emitter.addListener(signal, callback); } } return () => { const count = callbacks.get(callback); if (count === void 0 || count <= 1) { callbacks.delete(callback); emitter.removeListener(signal, callback); } else { callbacks.set(callback, count - 1); } }; }, async listener(signal2) { if (context.triggered) { return; } context.triggered = true; context.kill = signal2; const listeners = [...emitter.listeners(signal2)]; for (const listener of listeners.reverse()) { await listener(signal2, context); } if (context.terminate === "kill" || context.terminate === "exit") { process.removeListener("SIGINT", handlers.SIGINT.listener); process.removeListener("SIGTERM", handlers.SIGTERM.listener); process.removeListener("SIGQUIT", handlers.SIGQUIT.listener); if (context.terminate === "kill") { process.kill(process.pid, context.kill); } else { process.exit(context.exit); } } context.triggered = false; context.kill = void 0; } }; } exports.onDeath = onDeath; exports.useDeath = useDeath;