import{signals as t}from"./signals.mjs";const e=t=>!!t&&"object"==typeof t&&"function"==typeof t.removeListener&&"function"==typeof t.emit&&"function"==typeof t.reallyExit&&"function"==typeof t.listeners&&"function"==typeof t.kill&&"number"==typeof t.pid&&"function"==typeof t.on,i=Symbol.for("signal-exit emitter"),s=globalThis,o=Object.defineProperty.bind(Object);class r{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(s[i])return s[i];o(s,i,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(t,e){this.listeners[t].push(e)}removeListener(t,e){const i=this.listeners[t],s=i.indexOf(e);-1!==s&&(0===s&&1===i.length?i.length=0:i.splice(s,1))}emit(t,e,i){if(this.emitted[t])return!1;this.emitted[t]=!0;let s=!1;for(const o of this.listeners[t])s=!0===o(e,i)||s;return"exit"===t&&(s=this.emit("afterExit",e,i)||s),s}}class n{}const l=globalThis.process,{onExit:c}=(h=e(l)?new class extends n{#t="win32"===l.platform?"SIGINT":"SIGHUP";#e=new r;#i;#s;#o;#r={};#n=!1;constructor(e){super(),this.#i=e,this.#r={};for(const i of t)this.#r[i]=()=>{const t=this.#i.listeners(i);let{count:s}=this.#e;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(s+=o.__signal_exit_emitter__.count),t.length===s){this.unload();const t=this.#e.emit("exit",null,i),s="SIGHUP"===i?this.#t:i;t||e.kill(e.pid,s)}};this.#o=e.reallyExit,this.#s=e.emit}onExit(t,i){if(!e(this.#i))return()=>{};!1===this.#n&&this.load();const s=i?.alwaysLast?"afterExit":"exit";return this.#e.on(s,t),()=>{this.#e.removeListener(s,t),0===this.#e.listeners.exit.length&&0===this.#e.listeners.afterExit.length&&this.unload()}}load(){if(!this.#n){this.#n=!0,this.#e.count+=1;for(const e of t)try{const t=this.#r[e];t&&this.#i.on(e,t)}catch(t){}this.#i.emit=(t,...e)=>this.#l(t,...e),this.#i.reallyExit=t=>this.#c(t)}}unload(){this.#n&&(this.#n=!1,t.forEach(t=>{const e=this.#r[t];if(!e)throw new Error("Listener not defined for signal: "+t);try{this.#i.removeListener(t,e)}catch(t){}}),this.#i.emit=this.#s,this.#i.reallyExit=this.#o,this.#e.count-=1)}#c(t){return e(this.#i)?(this.#i.exitCode=t||0,this.#e.emit("exit",this.#i.exitCode,null),this.#o.call(this.#i,this.#i.exitCode)):0}#l(t,...i){const s=this.#s;if("exit"===t&&e(this.#i)){"number"==typeof i[0]&&(this.#i.exitCode=i[0]);const e=s.call(this.#i,t,...i);return this.#e.emit("exit",this.#i.exitCode,null),e}return s.call(this.#i,t,...i)}}(l):new class extends n{onExit(){return()=>{}}load(){}unload(){}},{onExit:(t,e)=>h.onExit(t,e),load:()=>h.load(),unload:()=>h.unload()});var h;export{c as onExit,t as signals};