Files
bare-operating-system/kernel/bin/pear
T
2026-05-26 18:38:18 -04:00

257 lines
8.3 KiB
Plaintext

/* BARE_OS_BIN_API 1.0.0 — bump when staged /bin script semantics change (see developer guide). */
/** Shared helpers for drive-resident /bin scripts (prepended before each command). */
function bareStdin(ctx) {
return typeof ctx.shellStdin === 'string' ? ctx.shellStdin : ''
}
/** @param {number} mode @param {'file' | 'directory' | 'symlink'} type */
function bareFormatModeString(mode, type) {
const typeChar = type === 'directory' ? 'd' : type === 'symlink' ? 'l' : '-'
const perm = mode & 0o777
const r = (bit) => (perm & bit ? 'r' : '-')
const w = (bit) => (perm & bit ? 'w' : '-')
const x = (bit) => (perm & bit ? 'x' : '-')
return (
typeChar +
r(0o400) +
w(0o200) +
x(0o100) +
r(0o040) +
w(0o020) +
x(0o010) +
r(0o004) +
w(0o002) +
x(0o001)
)
}
/** @param {number} mtimeMs @param {number} [nowMs] */
function bareFormatLsMtime(mtimeMs, nowMs) {
const now = nowMs != null ? nowMs : Date.now()
const d = new Date(mtimeMs)
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
const mon = months[d.getMonth()]
const day = String(d.getDate()).padStart(2, ' ')
const sixMo = 180 * 24 * 3600 * 1000
if (Math.abs(now - mtimeMs) > sixMo) {
const yr = String(d.getFullYear()).padStart(4, ' ')
return mon + ' ' + day + ' ' + yr
}
const hh = String(d.getHours()).padStart(2, '0')
const mm = String(d.getMinutes()).padStart(2, '0')
return mon + ' ' + day + ' ' + hh + ':' + mm
}
/** @param {number} size */
function barePosixBlocks(size) {
return Math.ceil(Number(size) / 512) || 0
}
/**
* Raw stdout for NUL/binary when **`process.stdout.write`** is missing.
* If **`ctx.bareOsBinWrite(Uint8Array|string)`** is set (tests / host), use it.
* @param {Record<string, unknown>} ctx
* @param {string | Uint8Array} chunk
* @returns {boolean}
*/
function bareOsEmitRaw(ctx, chunk) {
if (typeof ctx.bareOsBinWrite === 'function') {
const b4 = ctx.b4a
const u8 =
typeof chunk === 'string'
? b4 && typeof b4.from === 'function'
? b4.from(chunk)
: new TextEncoder().encode(chunk)
: chunk
ctx.bareOsBinWrite(u8 instanceof Uint8Array ? u8 : new Uint8Array(u8))
return true
}
const w = globalThis.process?.stdout?.write
if (typeof w === 'function') {
w.call(globalThis.process.stdout, chunk)
return true
}
return false
}
/**
* pear — Pear development tools inside Bare OS.
*
* Provides access to the Pear runtime stack (build, bundle, stage, release, seed)
* from within a booted Bare OS guest via the new ctx.pear surface.
*
* See docs/design/ctx-pear-surface-and-bare-audit-plan.md for the full plan and design.
*/
async function run(ctx, argv = []) {
function printHelp(argv0 = 'pear') {
ctx.console.log(`${argv0} — Pear development surface for Bare OS
Usage:
${argv0} help
${argv0} info
${argv0} list
${argv0} stage [dir]
${argv0} build [dir]
${argv0} init [dir]
The ctx.pear surface exposes selected Pear and Bare build/bundling packages
(pear-build, pear-bundle, bare-bundle-compile, etc.) when BARE_OS_BARE_MODULES
is enabled.
Many operations (full release, seeding, live sidecar IPC) currently delegate to
a host Pear sidecar (when available) following the same pattern as peerctl and
the P2P App Store.
Pear apps you create here are natural citizens of the P2P App Store:
- Stage your app with Pear tooling
- Publish it via appstore (or directly as a pear:// package)
- Other users can discover and run it
Use the pear-dev agent skill together with the appstore skill for
autonomous "build Pear app → publish to my store" workflows.
`)
}
async function cmdInfo() {
ctx.console.log('pear — Pear development tools (ctx.pear surface)')
ctx.console.log('Bare OS version of selected Pear runtime packages.')
ctx.console.log('')
const bareModulesEnabled = !ctx.env || (ctx.env.BARE_OS_BARE_MODULES !== '0' && ctx.env.BARE_OS_BARE_MODULES !== 'false')
if (ctx.pear && typeof ctx.pear === 'object') {
const keys = Object.keys(ctx.pear).sort()
if (keys.length > 0) {
ctx.console.log(`Exposed on ctx.pear (${keys.length} packages):`)
for (const k of keys) {
const val = ctx.pear[k]
const type = typeof val
ctx.console.log(` ${k.padEnd(20)} ${type}`)
}
} else {
ctx.console.log('ctx.pear exists but is empty.')
ctx.console.log('')
if (!bareModulesEnabled) {
ctx.console.log('Reason: BARE_OS_BARE_MODULES is disabled.')
} else {
ctx.console.log('Reason: No Pear packages were successfully imported during boot.')
ctx.console.log(' This usually means the packages (pear-build, pear-bundle, pear-ref)')
ctx.console.log(' are not installed in the booter\'s node_modules.')
ctx.console.log('')
ctx.console.log('Fix: On the machine running the booter/seeder, run:')
ctx.console.log(' npm install')
ctx.console.log(' Then rebuild and restage the image.')
ctx.console.log('')
ctx.console.log('Note: On developer machines the local mirror may provide them.')
ctx.console.log(' On production servers they must come from npm (see optionalDependencies).')
}
}
} else {
ctx.console.log('ctx.pear property is missing from the guest context.')
if (!bareModulesEnabled) {
ctx.console.log('BARE_OS_BARE_MODULES is disabled.')
}
}
ctx.console.log('')
ctx.console.log('Run "pear list" for the same view.')
}
async function cmdList() {
if (!ctx.pear || typeof ctx.pear !== 'object') {
ctx.console.log('ctx.pear is not available in this environment.')
ctx.console.log('Run "pear info" for diagnostics.')
return
}
const keys = Object.keys(ctx.pear).sort()
if (keys.length === 0) {
ctx.console.log('ctx.pear exists but no packages loaded.')
ctx.console.log('Run "pear info" for detailed reasons and fix instructions.')
return
}
ctx.console.log(`ctx.pear — ${keys.length} package(s) available:\n`)
for (const k of keys) {
ctx.console.log(` ${k}`)
}
}
async function cmdInit(targetDir = '.') {
const name = 'my-pear-app'
const dir = targetDir === '.' ? `${(ctx.env?.HOME || '/home/guest')}/pear-projects/${name}` : targetDir
ctx.console.log(`pear init: creating minimal Pear app skeleton at ${dir}`)
try {
await ctx.vfs.mkdir(dir, { recursive: true })
const packageJson = {
name,
version: '0.1.0',
main: 'index.js',
type: 'module',
pear: {
name: 'my-pear-app',
type: 'desktop'
}
}
await ctx.vfs.writeFile(`${dir}/package.json`, ctx.b4a.from(JSON.stringify(packageJson, null, 2)))
await ctx.vfs.writeFile(`${dir}/index.js`, ctx.b4a.from('console.log("Hello from my Pear app!");\n'))
ctx.console.log('Created basic package.json + index.js')
ctx.console.log(`Next: run "pear stage ${dir}" (uses ctx.pear.pearBuild when available)`)
} catch (err) {
ctx.console.error('Failed to init:', err?.message || err)
}
}
const sub = (argv[1] || 'help').toLowerCase()
switch (sub) {
case 'help':
case '--help':
case '-h':
printHelp(argv[0] || 'pear')
break
case 'info':
await cmdInfo()
break
case 'list':
case 'ls':
await cmdList()
break
case 'stage':
case 'build':
const target = argv[2] || '.'
if (ctx.pear && ctx.pear.pearBuild) {
ctx.console.log(`Attempting stage of ${target} using ctx.pear.pearBuild...`)
ctx.console.log('ctx.pear.pearBuild is available. Full pipeline implementation in progress.')
ctx.console.log('Exposed build-related keys:', Object.keys(ctx.pear).filter(k =>
k.toLowerCase().includes('build') || k.toLowerCase().includes('bundle')
))
} else {
ctx.console.log('pear stage / build: ctx.pear.pearBuild not available.')
ctx.console.log('Run "pear info" for status and instructions on making Pear build tooling available.')
}
break
case 'init':
await cmdInit(argv[2])
break
default:
ctx.console.error(`Unknown subcommand: ${sub}`)
printHelp(argv[0] || 'pear')
break
}
}