-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessRunner.ts
More file actions
79 lines (67 loc) · 1.91 KB
/
Copy pathprocessRunner.ts
File metadata and controls
79 lines (67 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { spawn } from 'child_process';
import * as path from 'path';
export interface ProcessOptions {
command: string;
args: string[];
cwd: string;
timeoutMs: number;
signal?: AbortSignal;
onStdout?: (data: string) => void;
onStderr?: (data: string) => void;
}
export interface ProcessResult {
exitCode: number;
stdout: string;
stderr: string;
timedOut: boolean;
}
export async function runProcess(options: ProcessOptions): Promise<ProcessResult> {
const { command, args, cwd, timeoutMs, signal, onStdout, onStderr } = options;
// Normalize and validate: only allow absolute paths to prevent path traversal.
const resolvedCommand = path.resolve(command);
if (!path.isAbsolute(resolvedCommand)) {
return { exitCode: 1, stdout: '', stderr: `Invalid command path: ${command}`, timedOut: false };
}
return new Promise((resolve) => {
const stdout: string[] = [];
const stderr: string[] = [];
let timedOut = false;
const proc = spawn(resolvedCommand, args, { cwd, shell: false });
const timer = setTimeout(() => {
timedOut = true;
proc.kill('SIGTERM');
}, timeoutMs);
signal?.addEventListener('abort', () => {
clearTimeout(timer);
proc.kill('SIGTERM');
});
proc.stdout.on('data', (chunk: Buffer) => {
const text = chunk.toString();
stdout.push(text);
onStdout?.(text);
});
proc.stderr.on('data', (chunk: Buffer) => {
const text = chunk.toString();
stderr.push(text);
onStderr?.(text);
});
proc.on('close', (code) => {
clearTimeout(timer);
resolve({
exitCode: code ?? 1,
stdout: stdout.join(''),
stderr: stderr.join(''),
timedOut,
});
});
proc.on('error', (err) => {
clearTimeout(timer);
resolve({
exitCode: 1,
stdout: stdout.join(''),
stderr: err.message,
timedOut: false,
});
});
});
}