Files
bare-operating-system/packages/bare-os-booter/lib/bare-os-bin-offload-worker.cjs
T
Raven Scott f8a0dad897 feat: kernel roadmap wave — bits4, policy v4, Pear/Bare compatibility
- protocol/booter: bits4 handshake, proc surfaces, boot policy v4, telemetry v4
- coreutils: nohup + ensure-man-pages; seed-man-pages fixes for extra pages
- kernel-runner: no static node:module (Pear); bare-module createRequire
- docs: handbook, reference, ADR, compatibility matrix, verify scripts
2026-04-04 02:51:33 -04:00

66 lines
1.8 KiB
JavaScript

'use strict'
/**
* Optional bare-worker thread for heavy `/bin` utilities when
* `BARE_OS_BIN_WORKER_OFFLOAD=1` (Bare runtime only; Node falls back to in-process).
*/
const Worker = require('bare-worker')
if (Worker.isMainThread) {
/**
* @param {{ source: string, argv: string[] }} workerData
* @returns {Promise<Record<string, unknown> | null>}
*/
exports.runBinOffloaded = function runBinOffloaded(workerData) {
return new Promise((resolve) => {
let w
try {
w = new Worker(__filename, { workerData })
} catch {
resolve(null)
return
}
w.on('message', (msg) => resolve(msg))
w.on('error', () => resolve(null))
})
}
} else {
const { source, argv } = Worker.workerData || {}
;(async () => {
try {
const AsyncFunction = Object.getPrototypeOf(async function () {})
.constructor
/** @type {string[]} */
const logs = []
/** @type {string[]} */
const errs = []
const ctx = {
exitCode: 0,
console: {
log: (...a) => logs.push(a.map(String).join(' ')),
error: (...a) => errs.push(a.map(String).join(' '))
}
}
const raw = typeof source === 'string' ? source : ''
const body = raw.startsWith('#!') ? raw.replace(/^#[^\n]*\n/, '') : raw
const fn = new AsyncFunction(
'ctx',
'argv',
`${body}\nif (typeof run === 'function') await run(ctx, argv)\n`
)
await fn(ctx, Array.isArray(argv) ? argv : [])
Worker.parentPort.postMessage({
ok: true,
exitCode:
ctx.exitCode != null ? Number(ctx.exitCode) || 0 : 0,
logs,
errs
})
} catch (e) {
Worker.parentPort.postMessage({
ok: false,
error: e && e.message ? e.message : String(e)
})
}
})()
}