/** * Utility to locate or auto-install Bun for running custom tool processes. * * Strategy: * 1. Check if `bun` is already on PATH (shell-out `which bun` / `where bun`). * 2. Check the well-known local install path (~/.bun/bin/bun). * 3. If neither found, run the official one-liner installer * (https://bun.sh) and return the path to the newly installed binary. * * The installer runs exactly once per session; subsequent calls return the * cached path immediately. */ import { execSync, execFileSync } from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; let cachedBunPath: string | null = null; /** * Resolve or install Bun. Returns the absolute path to the bun binary. * Throws if installation fails. */ export async function ensureBunAvailable(): Promise { if (cachedBunPath) return cachedBunPath; // 1. Try PATH const fromPath = whichBun(); if (fromPath) { cachedBunPath = fromPath; return fromPath; } // 2. Try well-known local path const localPath = path.join(os.homedir(), '.bun', 'bin', 'bun'); if (fs.existsSync(localPath)) { cachedBunPath = localPath; return localPath; } // 3. Auto-install via official installer console.log( '\n[smol-js] Bun is required to run custom tools but was not found. ' + 'Installing Bun automatically...\n' ); try { // The official install script: https://bun.sh execSync('curl --proto =https --tlsv1.2 -sSf https://bun.sh | bash', { stdio: 'inherit', shell: '/bin/bash', env: { ...process.env, HOME: os.homedir() }, }); } catch (err) { throw new Error( '[smol-js] Failed to auto-install Bun. Please install it manually: https://bun.sh\n' + `Details: ${(err as Error).message}` ); } // Verify install succeeded const afterInstall = whichBun() || (fs.existsSync(localPath) ? localPath : null); if (!afterInstall) { throw new Error( '[smol-js] Bun installation appeared to succeed but the binary was not found. ' + 'Please install manually: https://bun.sh' ); } console.log(`[smol-js] Bun installed successfully at: ${afterInstall}\n`); cachedBunPath = afterInstall; return afterInstall; } function whichBun(): string | null { try { const cmd = process.platform === 'win32' ? 'where bun' : 'which bun'; const result = execSync(cmd, { encoding: 'utf8', stdio: 'pipe' }).trim(); // `which` may return multiple lines on some systems; take the first const first = result.split('\n')[0]?.trim(); if (first && fs.existsSync(first)) return first; return null; } catch { return null; } }