Files
bare-operating-system/packages/bare-os-booter/lib/host/bare-os-host-signals-bridge.js
T
2026-08-18 18:11:28 -04:00

61 lines
1.3 KiB
JavaScript

/**
* Maps host SIGINT into a process event for guest cancellation (optional `bare-signals` on Bare).
*/
/**
* @param {{ onSigint?: () => void }} [opts]
* @returns {Promise<() => void>} disposer
*/
export async function installBareOsHostSignalsBridge(opts = {}) {
const onSigint = typeof opts.onSigint === 'function' ? opts.onSigint : () => {}
/** @type {(() => void)[]} */
const disposers = []
try {
const mod = await import('bare-signals')
const Signal = mod.default
if (typeof Signal === 'function') {
const h = new Signal('SIGINT')
const fn = () => {
onSigint()
}
h.on('signal', fn)
h.start()
disposers.push(() => {
try {
void h.close()
} catch {
/* ignore */
}
})
}
} catch {
/* bare-signals optional (native binding) */
}
if (
disposers.length === 0 &&
globalThis.process &&
typeof globalThis.process.on === 'function'
) {
const fn = () => {
onSigint()
}
globalThis.process.on('SIGINT', fn)
disposers.push(() => {
try {
globalThis.process.off('SIGINT', fn)
} catch {
/* ignore */
}
})
}
return () => {
for (const d of disposers) {
try {
d()
} catch {
/* ignore */
}
}
}
}