|
| 1 | +/** |
| 2 | + * tools/bun-runner.ts – Run workspace Bun scripts directly without a shell. |
| 3 | + * |
| 4 | + * Spawns the Bun runtime with a script path + argv array, keeps cwd/script |
| 5 | + * resolution inside the workspace, tracks the child process for abort/shutdown, |
| 6 | + * discards stdout, and captures stderr only. |
| 7 | + */ |
| 8 | + |
| 9 | +import { spawn } from "child_process"; |
| 10 | +import { existsSync, statSync } from "fs"; |
| 11 | +import path from "path"; |
| 12 | + |
| 13 | +import { WORKSPACE_DIR } from "../core/config.js"; |
| 14 | +import { killProcessTree, registerProcess, unregisterProcess } from "../utils/process-tracker.js"; |
| 15 | + |
| 16 | +const DEFAULT_TIMEOUT_SEC = 120; |
| 17 | +const MAX_TIMEOUT_SEC = 3600; |
| 18 | +const MAX_CAPTURED_STDERR_BYTES = 64 * 1024; |
| 19 | + |
| 20 | +export interface RunBunScriptParams { |
| 21 | + script: string; |
| 22 | + args?: string[]; |
| 23 | + cwd?: string; |
| 24 | + timeoutSec?: number; |
| 25 | +} |
| 26 | + |
| 27 | +export interface ResolvedBunScriptTarget { |
| 28 | + scriptPath: string; |
| 29 | + scriptDisplayPath: string; |
| 30 | + cwd: string; |
| 31 | + cwdDisplayPath: string; |
| 32 | + args: string[]; |
| 33 | + timeoutSec: number; |
| 34 | +} |
| 35 | + |
| 36 | +export interface RunBunScriptResult extends ResolvedBunScriptTarget { |
| 37 | + bunPath: string; |
| 38 | + exitCode: number | null; |
| 39 | + stderr: string; |
| 40 | + stderrBytes: number; |
| 41 | + stderrTruncated: boolean; |
| 42 | +} |
| 43 | + |
| 44 | +function resolveWorkspacePath(input: string): string | null { |
| 45 | + const raw = String(input || "").trim(); |
| 46 | + if (!raw) return null; |
| 47 | + const resolved = path.resolve(WORKSPACE_DIR, raw); |
| 48 | + const rel = path.relative(WORKSPACE_DIR, resolved); |
| 49 | + if (rel.startsWith("..") || path.isAbsolute(rel)) return null; |
| 50 | + return resolved; |
| 51 | +} |
| 52 | + |
| 53 | +function displayWorkspacePath(absPath: string): string { |
| 54 | + const rel = path.relative(WORKSPACE_DIR, absPath); |
| 55 | + if (!rel || rel === ".") return "."; |
| 56 | + return rel.split(path.sep).join("/"); |
| 57 | +} |
| 58 | + |
| 59 | +function normalizeArgs(input: unknown): string[] { |
| 60 | + if (input === undefined || input === null) return []; |
| 61 | + if (!Array.isArray(input)) { |
| 62 | + throw new Error("args must be an array of strings."); |
| 63 | + } |
| 64 | + return input.map((value, index) => { |
| 65 | + if (typeof value !== "string") { |
| 66 | + throw new Error(`args[${index}] must be a string.`); |
| 67 | + } |
| 68 | + if (value.includes("\0")) { |
| 69 | + throw new Error(`args[${index}] contains an invalid null byte.`); |
| 70 | + } |
| 71 | + return value; |
| 72 | + }); |
| 73 | +} |
| 74 | + |
| 75 | +export function resolveBunScriptTarget(params: RunBunScriptParams): ResolvedBunScriptTarget { |
| 76 | + const resolvedScript = resolveWorkspacePath(params.script); |
| 77 | + if (!resolvedScript) { |
| 78 | + throw new Error("script must resolve to a file inside the workspace."); |
| 79 | + } |
| 80 | + if (!existsSync(resolvedScript)) { |
| 81 | + throw new Error(`Script not found: ${params.script}`); |
| 82 | + } |
| 83 | + |
| 84 | + let scriptStats; |
| 85 | + try { |
| 86 | + scriptStats = statSync(resolvedScript); |
| 87 | + } catch { |
| 88 | + throw new Error(`Failed to stat script: ${params.script}`); |
| 89 | + } |
| 90 | + if (!scriptStats.isFile()) { |
| 91 | + throw new Error("script must be a file, not a directory."); |
| 92 | + } |
| 93 | + |
| 94 | + const resolvedCwd = params.cwd && String(params.cwd).trim() |
| 95 | + ? resolveWorkspacePath(params.cwd) |
| 96 | + : WORKSPACE_DIR; |
| 97 | + if (!resolvedCwd) { |
| 98 | + throw new Error("cwd must stay within the workspace."); |
| 99 | + } |
| 100 | + if (!existsSync(resolvedCwd)) { |
| 101 | + throw new Error(`cwd does not exist: ${params.cwd}`); |
| 102 | + } |
| 103 | + |
| 104 | + let cwdStats; |
| 105 | + try { |
| 106 | + cwdStats = statSync(resolvedCwd); |
| 107 | + } catch { |
| 108 | + throw new Error(`Failed to stat cwd: ${params.cwd}`); |
| 109 | + } |
| 110 | + if (!cwdStats.isDirectory()) { |
| 111 | + throw new Error("cwd must be a directory."); |
| 112 | + } |
| 113 | + |
| 114 | + const timeoutSec = Number.isFinite(params.timeoutSec) |
| 115 | + ? Math.min(Math.max(Number(params.timeoutSec), 1), MAX_TIMEOUT_SEC) |
| 116 | + : DEFAULT_TIMEOUT_SEC; |
| 117 | + |
| 118 | + return { |
| 119 | + scriptPath: resolvedScript, |
| 120 | + scriptDisplayPath: displayWorkspacePath(resolvedScript), |
| 121 | + cwd: resolvedCwd, |
| 122 | + cwdDisplayPath: displayWorkspacePath(resolvedCwd), |
| 123 | + args: normalizeArgs(params.args), |
| 124 | + timeoutSec, |
| 125 | + }; |
| 126 | +} |
| 127 | + |
| 128 | +export async function runBunScript( |
| 129 | + params: RunBunScriptParams, |
| 130 | + signal?: AbortSignal, |
| 131 | +): Promise<RunBunScriptResult> { |
| 132 | + const target = resolveBunScriptTarget(params); |
| 133 | + const bunPath = process.execPath || "bun"; |
| 134 | + |
| 135 | + return await new Promise<RunBunScriptResult>((resolve, reject) => { |
| 136 | + let settled = false; |
| 137 | + let child: ReturnType<typeof spawn> | null = null; |
| 138 | + let timedOut = false; |
| 139 | + let aborted = false; |
| 140 | + let stderrBytes = 0; |
| 141 | + let stderrTruncated = false; |
| 142 | + const stderrChunks: string[] = []; |
| 143 | + |
| 144 | + const cleanup = (timeoutHandle?: NodeJS.Timeout) => { |
| 145 | + if (timeoutHandle) clearTimeout(timeoutHandle); |
| 146 | + if (signal) signal.removeEventListener("abort", onAbort); |
| 147 | + if (child?.pid) unregisterProcess(child.pid); |
| 148 | + }; |
| 149 | + |
| 150 | + const finish = (result: RunBunScriptResult) => { |
| 151 | + if (settled) return; |
| 152 | + settled = true; |
| 153 | + resolve(result); |
| 154 | + }; |
| 155 | + |
| 156 | + const fail = (error: Error, timeoutHandle?: NodeJS.Timeout) => { |
| 157 | + if (settled) return; |
| 158 | + settled = true; |
| 159 | + cleanup(timeoutHandle); |
| 160 | + reject(error); |
| 161 | + }; |
| 162 | + |
| 163 | + const onAbort = () => { |
| 164 | + aborted = true; |
| 165 | + if (child?.pid) killProcessTree(child.pid); |
| 166 | + }; |
| 167 | + |
| 168 | + const timeoutHandle = setTimeout(() => { |
| 169 | + timedOut = true; |
| 170 | + if (child?.pid) killProcessTree(child.pid); |
| 171 | + }, target.timeoutSec * 1000); |
| 172 | + |
| 173 | + if (signal) { |
| 174 | + if (signal.aborted) { |
| 175 | + onAbort(); |
| 176 | + } else { |
| 177 | + signal.addEventListener("abort", onAbort, { once: true }); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + child = spawn(bunPath, [target.scriptPath, ...target.args], { |
| 182 | + cwd: target.cwd, |
| 183 | + detached: true, |
| 184 | + env: process.env, |
| 185 | + stdio: ["ignore", "ignore", "pipe"], |
| 186 | + }); |
| 187 | + |
| 188 | + if (child.pid) registerProcess(child.pid); |
| 189 | + |
| 190 | + child.stderr?.on("data", (chunk) => { |
| 191 | + const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk); |
| 192 | + stderrBytes += Buffer.byteLength(text, "utf8"); |
| 193 | + const currentBytes = stderrChunks.reduce((sum, entry) => sum + Buffer.byteLength(entry, "utf8"), 0); |
| 194 | + const remaining = MAX_CAPTURED_STDERR_BYTES - currentBytes; |
| 195 | + if (remaining <= 0) { |
| 196 | + stderrTruncated = true; |
| 197 | + return; |
| 198 | + } |
| 199 | + if (Buffer.byteLength(text, "utf8") > remaining) { |
| 200 | + stderrTruncated = true; |
| 201 | + stderrChunks.push(Buffer.from(text, "utf8").subarray(0, remaining).toString("utf8")); |
| 202 | + return; |
| 203 | + } |
| 204 | + stderrChunks.push(text); |
| 205 | + }); |
| 206 | + |
| 207 | + child.on("error", (error) => { |
| 208 | + fail(error, timeoutHandle); |
| 209 | + }); |
| 210 | + |
| 211 | + child.on("close", (exitCode) => { |
| 212 | + cleanup(timeoutHandle); |
| 213 | + |
| 214 | + if (aborted || signal?.aborted) { |
| 215 | + reject(new Error("aborted")); |
| 216 | + return; |
| 217 | + } |
| 218 | + if (timedOut) { |
| 219 | + reject(new Error(`timeout:${target.timeoutSec}`)); |
| 220 | + return; |
| 221 | + } |
| 222 | + |
| 223 | + finish({ |
| 224 | + ...target, |
| 225 | + bunPath, |
| 226 | + exitCode, |
| 227 | + stderr: stderrChunks.join(""), |
| 228 | + stderrBytes, |
| 229 | + stderrTruncated, |
| 230 | + }); |
| 231 | + }); |
| 232 | + }); |
| 233 | +} |
0 commit comments