Open History to see the last commit
1import {
2 chunkTerminalWrite,
3 terminalWritePhase,
4 type TerminalWriteInput,
5} from "@t3tools/contracts";
6
7import { encodeTerminalPaste } from "./terminalInput";
8
9type WriteChunk = (data: string, phase?: TerminalWriteInput["plainWrite"]) => Promise<boolean>;
10
11interface TerminalPasteInput {
12 readonly readText: () => Promise<string>;
13 readonly write: WriteChunk;
14 readonly onReadError: (cause: unknown) => void;
15}
16
17export interface TerminalPasteSession {
18 readonly reset: (active: boolean) => void;
19 /** True until the terminal's liveness changes (stop, start or restart) after this call. */
20 readonly liveness: () => () => boolean;
21 readonly write: (data: string, send: WriteChunk) => Promise<void>;
22 readonly paste: (input: TerminalPasteInput) => Promise<void>;
23}
24
25export function createTerminalPasteSession(): TerminalPasteSession {
26 let liveTarget: object | null = null;
27 let latestRequest = 0;
28 let writeTail: Promise<void> | null = null;
29
30 const writeChunks = (
31 data: string,
32 send: WriteChunk,
33 isCurrent: () => boolean,
34 queueSingle: boolean,
35 ) => {
36 const chunks = chunkTerminalWrite(data);
37 const run = async () => {
38 let started = false;
39 try {
40 for (const [index, chunk] of chunks.entries()) {
41 if (!isCurrent()) return;
42 const phase = terminalWritePhase(index, chunks.length);
43 started ||= phase === "start";
44 if (!(await send(chunk, phase))) return;
45 }
46 started = false;
47 } finally {
48 if (started) await send("", "abort");
49 }
50 };
51 if (writeTail === null && !queueSingle && chunks.length <= 1) return run();
52 const pending = (writeTail ?? Promise.resolve()).then(run, run);
53 writeTail = pending;
54 const clear = () => {
55 if (writeTail === pending) writeTail = null;
56 };
57 void pending.then(clear, clear);
58 return pending;
59 };
60
61 return {
62 reset(active) {
63 liveTarget = active ? {} : null;
64 },
65
66 liveness() {
67 const target = liveTarget;
68 return () => liveTarget === target;
69 },
70
71 async write(data, send) {
72 // Input can arrive before the first attach snapshot sets liveness; the caller gates on running.
73 const target = liveTarget;
74 await writeChunks(data, send, () => liveTarget === target, false);
75 },
76
77 async paste({ readText, write, onReadError }) {
78 const target = liveTarget;
79 if (target === null) {
80 return;
81 }
82 const request = ++latestRequest;
83 const isCurrent = () => liveTarget === target && latestRequest === request;
84
85 let text: string;
86 try {
87 text = await readText();
88 } catch (cause) {
89 onReadError(cause);
90 return;
91 }
92
93 if (!isCurrent()) {
94 return;
95 }
96
97 await writeChunks(encodeTerminalPaste(text), write, isCurrent, true);
98 },
99 };
100}