import { spawn } from 'node:child_process'
* @param {string} command
* @param {string[]} args
* @param {{input?: string | Buffer, timeoutMs?: number, env?: NodeJS.ProcessEnv, cwd?: string,
* signal?: AbortSignal, onLine?: (line: string, fromStderr: boolean) => void | 'stop'}} [options]
* @returns {Promise<{code: number, stdout: string, stderr: string, timedOut: boolean}>}
*/
export function run(command, args, options = {}) {
const { input, timeoutMs = 120_000, env = process.env, cwd, onLine, signal } = options
if (signal?.aborted) return Promise.resolve({ code: -3, stdout: '', stderr: 'Connection cancelled', timedOut: false })
return new Promise((resolve) => {
let settled = false
let timer = null
let child
try {
child = spawn(command, args, {
cwd,
env,
windowsHide: true,
stdio: ['pipe', 'pipe', 'pipe'],
})
} catch (error) {
resolve({ code: -1, stdout: '', stderr: String(error && error.message ? error.message : error), timedOut: false })
return
}
let stdout = ''
let stderr = ''
let stoppedByCaller = false
let inputFailed = false
const inputError = () => {
if (settled || inputFailed || stoppedByCaller) return
inputFailed = true
stderr += `${stderr && !stderr.endsWith('\n') ? '\n' : ''}stdin write failed\n`
}
child.stdin.on('error', inputError)
const finish = (code, timedOut) => {
if (settled) return
settled = true
if (timer) clearTimeout(timer)
signal?.removeEventListener('abort', abort)
const finalCode = stoppedByCaller ? 0 : (code === 0 && inputFailed ? -1 : code)
resolve({ code: finalCode, stdout, stderr, timedOut: Boolean(timedOut) })
}
const abort = () => {
stoppedByCaller = false
try { child.kill() } catch { }
finish(-3, false)
}
signal?.addEventListener('abort', abort, { once: true })
if (signal?.aborted) { abort(); return }
const pump = (chunk, fromStderr) => {
if (!onLine) return
const text = chunk.toString('utf8')
for (const line of text.split(/\r?\n/)) {
if (!line) continue
if (onLine(line, fromStderr) === 'stop') {
stoppedByCaller = true
try { child.kill() } catch { }
return
}
}
}
child.stdout.on('data', (chunk) => {
stdout += chunk.toString('utf8')
pump(chunk, false)
})
child.stderr.on('data', (chunk) => {
stderr += chunk.toString('utf8')
pump(chunk, true)
})
child.on('error', (error) => {
stderr += String(error && error.message ? error.message : error)
finish(-1, false)
})
child.on('close', (code) => finish(code === null ? -1 : code, false))
if (timeoutMs > 0) {
timer = setTimeout(() => {
try { child.kill() } catch { }
finish(-2, true)
}, timeoutMs)
if (typeof timer.unref === 'function') timer.unref()
}
try {
if (input) child.stdin.end(input)
else child.stdin.end()
} catch { inputError() }
})
}
export function shQuote(value) {
return `'${String(value).replace(/'/g, `'\\''`)}'`
}