2026-04-11 23:04:03 +09:00
|
|
|
import type { SpawnOptions } from "../../shared/spawn-with-windows-hide"
|
|
|
|
|
import { spawnWithWindowsHide } from "../../shared/spawn-with-windows-hide"
|
|
|
|
|
|
|
|
|
|
const DEFAULT_SPAWN_TIMEOUT_MS = 10_000
|
|
|
|
|
|
2026-04-11 23:10:58 +09:00
|
|
|
export interface SpawnWithTimeoutResult {
|
|
|
|
|
stdout: string
|
|
|
|
|
stderr: string
|
|
|
|
|
exitCode: number
|
|
|
|
|
timedOut: boolean
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-11 23:04:03 +09:00
|
|
|
export async function spawnWithTimeout(
|
|
|
|
|
command: string[],
|
|
|
|
|
options: SpawnOptions,
|
|
|
|
|
timeoutMs: number = DEFAULT_SPAWN_TIMEOUT_MS
|
2026-04-11 23:10:58 +09:00
|
|
|
): Promise<SpawnWithTimeoutResult> {
|
2026-04-11 23:04:03 +09:00
|
|
|
let proc: ReturnType<typeof spawnWithWindowsHide>
|
|
|
|
|
try {
|
|
|
|
|
proc = spawnWithWindowsHide(command, options)
|
|
|
|
|
} catch {
|
2026-04-11 23:10:58 +09:00
|
|
|
return { stdout: "", stderr: "", exitCode: 1, timedOut: false }
|
2026-04-11 23:04:03 +09:00
|
|
|
}
|
|
|
|
|
|
2026-04-11 23:10:58 +09:00
|
|
|
let timer: ReturnType<typeof setTimeout> | undefined
|
2026-04-11 23:04:03 +09:00
|
|
|
const timeoutPromise = new Promise<"timeout">((resolve) => {
|
2026-04-11 23:10:58 +09:00
|
|
|
timer = setTimeout(() => resolve("timeout"), timeoutMs)
|
2026-04-11 23:04:03 +09:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const processPromise = (async (): Promise<"done"> => {
|
|
|
|
|
await proc.exited
|
|
|
|
|
return "done"
|
|
|
|
|
})()
|
|
|
|
|
|
|
|
|
|
const race = await Promise.race([processPromise, timeoutPromise])
|
|
|
|
|
|
|
|
|
|
if (race === "timeout") {
|
|
|
|
|
proc.kill("SIGTERM")
|
2026-04-11 23:10:58 +09:00
|
|
|
await proc.exited.catch(() => {})
|
|
|
|
|
return { stdout: "", stderr: "", exitCode: 1, timedOut: true }
|
2026-04-11 23:04:03 +09:00
|
|
|
}
|
|
|
|
|
|
2026-04-11 23:10:58 +09:00
|
|
|
clearTimeout(timer)
|
2026-04-11 23:04:03 +09:00
|
|
|
const stdout = proc.stdout ? await new Response(proc.stdout).text() : ""
|
2026-04-11 23:10:58 +09:00
|
|
|
const stderr = proc.stderr ? await new Response(proc.stderr).text() : ""
|
|
|
|
|
return { stdout, stderr, exitCode: proc.exitCode ?? 1, timedOut: false }
|
2026-04-11 23:04:03 +09:00
|
|
|
}
|