-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpty-manager.ts
More file actions
228 lines (192 loc) · 6.11 KB
/
Copy pathpty-manager.ts
File metadata and controls
228 lines (192 loc) · 6.11 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import pty, { IPty, IPtyForkOptions } from "node-pty";
import stripAnsi from "strip-ansi";
interface OnDataProps
{
name: string;
history: string[];
proc: IPty;
data: string;
}
interface OnExitProps
{
name: string;
history: string[];
proc: IPty;
exitCode: number;
signal?: number;
}
interface IOptions
{
readTimeout?: number;
sessionTimeout?: number;
onData?: (props: OnDataProps) => void;
onExit?: (props: OnExitProps) => void;
spawnOptions?: IPtyForkOptions;
}
interface Session
{
proc: IPty;
buffer: string[];
history: string[];
exitCode?: number;
signal?: number;
}
export class PtyManager
{
private sessions: Map<string, Session> = new Map();
constructor() { }
createSession(name: string, command: string, args: string[] = [], options: IOptions = {}): string
{
if (this.sessions.has(name))
{
throw new Error(`Session "${name}" already exists`);
}
const proc = pty.spawn(command, args, {
name: "xterm-color",
cols: 80,
rows: 30,
cwd: process.cwd(),
env: process.env as { [key: string]: string },
...options.spawnOptions,
});
const buffer: string[] = []; // recent unread output
const history: string[] = []; // full output history
const handleTimeout = () =>
{
proc.kill();
};
if (options.sessionTimeout && options.sessionTimeout > 0)
{
setTimeout(handleTimeout, options.sessionTimeout);
}
let readTimeout: NodeJS.Timeout | null = null;
if (options.readTimeout && options.readTimeout > 0)
{
readTimeout = setTimeout(handleTimeout, options.readTimeout);
}
proc.onData((data: string) =>
{
if (readTimeout)
{
clearTimeout(readTimeout);
readTimeout = setTimeout(handleTimeout, options.readTimeout);
}
options.onData?.({ name, history, proc, data });
buffer.push(data);
history.push(data);
});
proc.onExit(({ exitCode, signal }) =>
{
if (readTimeout)
{
clearTimeout(readTimeout);
}
options.onExit?.({ name, history, proc, exitCode, signal });
const session = this.sessions.get(name);
if (session)
{
session.exitCode = exitCode;
session.signal = signal;
}
// this.sessions.delete(name); // Remove session on exit
});
this.sessions.set(name, { proc, buffer, history });
return name;
}
/** Writes a line of text to the session, automatically adding a newline. */
writeLine(name: string, input: string): void
{
const session = this.sessions.get(name);
if (!session) { throw new Error(`Session "${name}" not found`); }
session.proc.write(input.endsWith("\n") ? input : input + "\n");
}
/** Writes raw data to the session's stdin without modification. */
writeRaw(name: string, data: string, eof?: boolean): void
{
const session = this.sessions.get(name);
if (!session) { throw new Error(`Session "${name}" not found`); }
session.proc.write(data);
eof && session.proc.write("\x04");
}
/** Get unread output since last call */
read(name: string): string
{
const session = this.sessions.get(name);
if (!session) { throw new Error(`Session "${name}" not found`); }
const output = session.buffer.join("");
session.buffer.length = 0; // Clear unread buffer
return output;
}
readText(name: string): string
{
return stripAnsi(this.read(name));
}
/** Get full history of the session */
getHistory(name: string): string
{
const session = this.sessions.get(name);
if (!session) { throw new Error(`Session "${name}" not found`); }
return session.history.join("");
}
getHistoryText(name: string): string
{
return stripAnsi(this.getHistory(name));
}
resize(name: string, cols: number, rows: number): void
{
const session = this.sessions.get(name);
if (!session) { throw new Error(`Session "${name}" not found`); }
session.proc.resize(cols, rows);
}
kill(name: string, signal: string = "SIGTERM"): void
{
const session = this.sessions.get(name);
if (!session) { throw new Error(`Session "${name}" not found`); }
session.proc.kill(signal);
// this.sessions.delete(name);
}
get(name: string)
{
return this.sessions.get(name);
}
/**
* Waits for a session to exit.
*
* @param name The name of the session.
* @param timeout Optional timeout in milliseconds.
* @returns A promise that resolves with the exit code and signal, or rejects on timeout.
*/
waitForExit(name: string, timeout?: number): Promise<{ exitCode: number, signal?: number }>
{
const session = this.sessions.get(name);
if (!session)
{
return Promise.reject(new Error(`Session "${name}" not found`));
}
if (typeof session.exitCode === "number")
{
return Promise.resolve({ exitCode: session.exitCode, signal: session.signal });
}
return new Promise((resolve, reject) =>
{
let timeoutId: NodeJS.Timeout | null = null;
const disposable = session.proc.onExit(({ exitCode, signal }) =>
{
if (timeoutId)
{
clearTimeout(timeoutId);
}
disposable.dispose();
resolve({ exitCode, signal });
});
if (timeout && timeout > 0)
{
timeoutId = setTimeout(() =>
{
disposable.dispose();
reject(new Error(`Timeout waiting for session "${name}" to exit`));
}, timeout);
}
});
}
}