-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplayableStdin.ts
More file actions
342 lines (294 loc) · 8.77 KB
/
Copy pathReplayableStdin.ts
File metadata and controls
342 lines (294 loc) · 8.77 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { Buffer } from 'node:buffer';
import { readFile } from 'node:fs/promises';
import process from 'node:process';
import {
BufferedStdin,
type InputChunk,
type StdinSource,
} from './BufferedStdin.ts';
import { InputRecording } from './InputRecording.ts';
import type { InputEvent, Session } from './RecordableStdin.ts';
/**
ReplayableStdin - Replays recorded user input, then switches to interactive mode once session replay finishes.
How it works:
1. Loads a session file created by RecordableStdin
2. Emits the recorded keystrokes at the right times
3. When replay finishes, seamlessly switches to real stdin
4. User can continue interacting normally
Usage:
```ts
const stdin = new ReplayableStdin('session.json');
await stdin.startReplay();
// Session plays back, then becomes interactive!
* ```
*/
export class ReplayableStdin extends BufferedStdin
{
/** Enable debug logging */
static DEBUG = false;
private queue: InputEvent[];
private index = 0;
private isReplaying = true;
private sessionTimestamp: string;
private startTime: number;
private replayTimeout?: ReturnType<typeof setTimeout>;
private interactiveListenersAttached = false;
private pendingRawMode?: boolean;
private replayWithOriginalTiming = false;
private echoStream?: NodeJS.WriteStream | NodeJS.WritableStream;
private didResumeSource = false;
private readonly handleInteractiveData = (data: InputChunk): void =>
{
if (this.destroyed)
{
return;
}
this.enqueueChunk(data);
};
private readonly handleEnd = (): void =>
{
this.emit('end');
};
private readonly handleError = (error: Error): void =>
{
this.emit('error', error);
};
private readonly handleClose = (): void =>
{
this.emitClose();
};
private constructor(
session: Session,
sessionPath: string,
stdinSource: StdinSource,
)
{
super(stdinSource);
this.queue = session.events;
this.sessionTimestamp = session.timestamp;
this.startTime = Date.now();
if (ReplayableStdin.DEBUG)
{
console.log(`[ReplayableStdin] 📼 Loaded session from: ${sessionPath}`);
console.log(`[ReplayableStdin] 📅 Recorded: ${this.sessionTimestamp}`);
console.log(`[ReplayableStdin] 🎬 Replaying ${this.queue.length} events...\n`);
}
}
/**
Create a ReplayableStdin by loading a session file
@param sessionPath - Path to the session JSON file
@param stdinSource - The underlying stdin stream (default: process.stdin)
@param echoStream - If provided, replayed input data is written here during replay to simulate terminal echo (the visual appearance of the user typing). Pass stdout to make replay look like an interactive session.
*/
static async create(
sessionPath: string,
stdinSource: StdinSource = process.stdin,
echoStream?: NodeJS.WriteStream | NodeJS.WritableStream,
): Promise<ReplayableStdin>
{
const sessionContent = await readFile(sessionPath, 'utf-8');
const session = JSON.parse(sessionContent) as Session;
const instance = new ReplayableStdin(session, sessionPath, stdinSource);
instance.echoStream = echoStream;
return instance;
}
private attachInteractiveListeners(): void
{
if (this.interactiveListenersAttached)
{
return;
}
this.interactiveListenersAttached = true;
this.stdinSource.on('data', this.handleInteractiveData);
this.stdinSource.on('end', this.handleEnd);
this.stdinSource.on('error', this.handleError);
this.stdinSource.on('close', this.handleClose);
}
private detachInteractiveListeners(): void
{
if (!this.interactiveListenersAttached)
{
return;
}
this.interactiveListenersAttached = false;
this.stdinSource.off('data', this.handleInteractiveData);
this.stdinSource.off('end', this.handleEnd);
this.stdinSource.off('error', this.handleError);
this.stdinSource.off('close', this.handleClose);
}
private clearReplayTimeout(): void
{
if (this.replayTimeout)
{
clearTimeout(this.replayTimeout);
this.replayTimeout = undefined;
}
}
/**
Start replaying the session
@param startupDelay - Milliseconds to wait before starting replay (default: 100ms). This gives the UI time to mount and start listening to stdin.
@param useOriginalTiming - If true, replay events with the original wall-clock delays from the recording. If false (default), fire events with minimal delays (10ms between each). Original timing is rarely useful for replay — it just makes the replay take as long as the original human interaction.
*/
startReplay(startupDelay = 100, useOriginalTiming = false): void
{
this.replayWithOriginalTiming = useOriginalTiming;
if (this.destroyed)
{
return;
}
if (ReplayableStdin.DEBUG) console.log(`[ReplayableStdin] ⏳ Waiting ${startupDelay}ms for UI to mount...\n`);
this.clearReplayTimeout();
this.replayTimeout = setTimeout(() =>
{
this.replayTimeout = undefined;
this.replayNextEvent();
}, startupDelay);
}
private replayNextEvent(): void
{
if (this.destroyed)
{
return;
}
if (this.index >= this.queue.length)
{
this.switchToInteractive();
return;
}
const event = this.queue[this.index];
if (!event)
{
this.switchToInteractive();
return;
}
let delay: number;
if (this.replayWithOriginalTiming)
{
const elapsedTime = Date.now() - this.startTime;
delay = Math.max(0, event.timestamp - elapsedTime);
}
else
{
// Fire events with minimal delays — just enough for the event loop to
// process each one before the next arrives.
delay = 10;
}
this.replayTimeout = setTimeout(() =>
{
this.replayTimeout = undefined;
if (this.destroyed)
{
return;
}
if (ReplayableStdin.DEBUG)
{
console.log(`[ReplayableStdin] ⚡ Event ${this.index + 1}/${this.queue.length}: ${JSON.stringify(event.data)}`);
console.log(`[ReplayableStdin] 🔍 'readable' listener count: ${this.listenerCount('readable')}`);
}
// Echo the replayed data to the output stream so it looks like someone
// is typing — simulates the terminal echo that happens in interactive mode.
if (this.echoStream && !InputRecording.disabled)
{
this.echoStream.write(event.data);
}
this.enqueueChunk(Buffer.from(event.data, this.encoding));
if (ReplayableStdin.DEBUG) console.log(`[ReplayableStdin] ✅ replay event emitted`);
this.index += 1;
this.replayNextEvent();
}, delay);
}
private switchToInteractive(): void
{
if (this.destroyed || !this.isReplaying)
{
return;
}
if (ReplayableStdin.DEBUG) console.log('\n[ReplayableStdin] ✅ Replay complete!');
if (ReplayableStdin.DEBUG) console.log('[ReplayableStdin] 🎮 Switching to interactive mode...\n');
this.isReplaying = false;
if (this.pendingRawMode !== undefined && this.stdinSource.isTTY && this.stdinSource.setRawMode)
{
this.stdinSource.setRawMode(this.pendingRawMode);
}
this.stdinSource.resume();
this.didResumeSource = true;
this.attachInteractiveListeners();
}
/**
Check if currently replaying
*/
isReplayActive(): boolean
{
return this.isReplaying;
}
protected override onRead(buffer: Buffer): void
{
if (ReplayableStdin.DEBUG)
{
console.log(`[ReplayableStdin] 📖 read() called, returning: ${JSON.stringify(buffer.toString())}`);
}
}
protected override onRef(): void
{
if (ReplayableStdin.DEBUG)
{
console.log('[ReplayableStdin] 🔗 ref() called');
}
}
protected override onUnref(): void
{
if (ReplayableStdin.DEBUG)
{
console.log('[ReplayableStdin] 🔓 unref() called');
}
}
protected override onDestroy(): void
{
this.clearReplayTimeout();
this.detachInteractiveListeners();
// If switchToInteractive() resumed the underlying stdin source, pause it
// back so it doesn't keep the event loop alive after the program is done.
if (this.didResumeSource)
{
this.stdinSource.pause();
this.didResumeSource = false;
}
}
setRawMode(mode: boolean): this
{
if (this.isReplaying)
{
this.pendingRawMode = mode;
return this;
}
if (this.stdinSource.isTTY && this.stdinSource.setRawMode)
{
this.stdinSource.setRawMode(mode);
}
return this;
}
pause(): this
{
if (!this.isReplaying)
{
this.stdinSource.pause();
}
return this;
}
resume(): this
{
if (!this.isReplaying)
{
this.stdinSource.resume();
}
return this;
}
override get isRaw(): boolean
{
if (this.isReplaying && this.pendingRawMode !== undefined)
{
return this.pendingRawMode;
}
return super.isRaw;
}
}