"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_primordials_error = require('../../primordials/error.js');
const require_events_exit__internal = require('./_internal.js');
const require_events_exit_lifecycle = require('./lifecycle.js');

//#region src/events/exit/handler.ts
/**
* @file `onExit` — register a callback for process exit / signal. Triggers
*   `load()` on first call. Returns a remover that unregisters the callback and
*   calls `unload()` once both `exit` and `afterexit` listener lists empty
*   out.
*/
/**
* Register a callback to run on process exit or signal.
*
* @example
*   ```typescript
*   const remove = onExit((code, signal) => {
*   console.log(`Exiting with code ${code}, signal ${signal}`)
*   })
*   // Later, to unregister:
*   remove()
*   ```
*/
/*@__NO_SIDE_EFFECTS__*/
function onExit(cb, options) {
	/* c8 ignore start */
	if (!require_events_exit__internal.globalProcess) return function remove() {};
	/* c8 ignore stop */
	if (typeof cb !== "function") throw new require_primordials_error.TypeErrorCtor("a callback must be provided for exit handler");
	if (require_events_exit__internal.isLoaded() === false) /* @__PURE__ */ require_events_exit_lifecycle.load();
	const { alwaysLast } = {
		__proto__: null,
		...options
	};
	let eventName = "exit";
	if (alwaysLast) eventName = "afterexit";
	const emitter = /* @__PURE__ */ require_events_exit__internal.getEmitter();
	emitter.on(eventName, cb);
	return function remove() {
		emitter.removeListener(eventName, cb);
		/* c8 ignore start */
		if (!emitter.listeners("exit").length && !emitter.listeners("afterexit").length) /* @__PURE__ */ require_events_exit_lifecycle.unload();
		/* c8 ignore stop */
	};
}

//#endregion
exports.onExit = onExit;