Files
bare-operating-system/packages/bare-os-booter/lib/services/bare-os-tui-sdk.js
T
2026-08-18 18:11:28 -04:00

56 lines
1.5 KiB
JavaScript

/**
* Attach first-party guest TUI / SDK onto ctx (raw-JS IIFE, no guest import).
*/
import { BARE_OS_TUI_SDK_SOURCE } from './bare-os-tui-sdk.data.mjs'
/**
* @param {Record<string, string> | null | undefined} env
*/
export function bareOsTuiEnabled(env) {
const v = env && env.BARE_OS_TUI
return v !== '0' && v !== 'false'
}
/**
* @param {Record<string, unknown>} ctx
* @param {{ source?: string }} [opts]
* @returns {boolean}
*/
export function attachBareOsTuiSdk(ctx, opts = {}) {
if (!ctx || typeof ctx !== 'object') return false
const env =
ctx.env && typeof ctx.env === 'object'
? /** @type {Record<string, string>} */ (ctx.env)
: {}
if (!bareOsTuiEnabled(env)) return false
if (
typeof ctx.bareOsIsCtxMethodAllowed === 'function' &&
ctx.bareOsIsCtxMethodAllowed('tui') === false
) {
return false
}
const src =
typeof opts.source === 'string' && opts.source
? opts.source
: BARE_OS_TUI_SDK_SOURCE
if (!src) return false
try {
const factory = new Function(
'ctx',
'"use strict"; return (' + src + ')(ctx)'
)
const boxed = factory(ctx)
if (!boxed || typeof boxed !== 'object' || !boxed.tui) return false
ctx.tui = Object.freeze(boxed.tui)
ctx.sdk = Object.freeze(boxed.sdk)
return true
} catch (e) {
if (typeof ctx.console?.error === 'function') {
ctx.console.error(
'bare-os-tui: attach failed: ' + (e && /** @type {Error} */ (e).message)
)
}
return false
}
}