Open History to see the last commit
1import {
2 chunkTerminalWrite,
3 terminalWritePhase,
4 type TerminalWriteInput,
5} from "@t3tools/contracts";
6
7/** Sends one chunk of terminal input; resolves false when it failed and the rest should drop. */
8type SendTerminalChunk = (
9 chunk: string,
10 framing?: Pick<TerminalWriteInput, "bracketedPaste" | "plainWrite">,
11) => Promise<boolean | "not-dispatched">;
12
13/**
14 * Orders one terminal's input into writes that fit `terminal.write`. A split write goes one chunk
15 * per round trip and later input waits behind it; other writes go out immediately, like keystrokes.
16 */
17export function createTerminalInputWriter(onIdle = () => {}) {
18 let pending: Promise<void> | null = null;
19 const immediate = new Set<Promise<void>>();
20
21 let closeInterruptedPaste: (() => Promise<boolean>) | null = null;
22 const closePaste = async () => {
23 if (closeInterruptedPaste === null) return true;
24 if (!(await closeInterruptedPaste())) return false;
25 closeInterruptedPaste = null;
26 return true;
27 };
28
29 const sendChunks = async (
30 data: string,
31 chunks: ReadonlyArray<string>,
32 send: SendTerminalChunk,
33 recover: (bracketed: boolean) => Promise<boolean>,
34 interrupted: () => void,
35 ) => {
36 if (closeInterruptedPaste !== null && !(await closePaste())) {
37 interrupted();
38 return;
39 }
40 const split = chunks.length > 1;
41 const bracketed = split && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~");
42 let opened = false;
43 try {
44 for (const [index, chunk] of chunks.entries()) {
45 const phase = terminalWritePhase(index, chunks.length);
46 const result = await send(
47 chunk,
48 phase ? (bracketed ? { bracketedPaste: phase } : { plainWrite: phase }) : undefined,
49 );
50 if (result !== true) {
51 if (result !== "not-dispatched") opened = split;
52 if (split) interrupted();
53 return;
54 }
55 opened = split;
56 }
57 opened = false;
58 } finally {
59 if (opened) {
60 if (bracketed) {
61 closeInterruptedPaste = () => recover(true);
62 await closePaste();
63 } else {
64 await recover(false);
65 }
66 }
67 }
68 };
69
70 return (
71 data: string,
72 send: SendTerminalChunk,
73 recover: (bracketed: boolean) => Promise<boolean> = async (bracketed) =>
74 (await (bracketed
75 ? send("\x1b[201~", { bracketedPaste: "abort" })
76 : send("", { plainWrite: "abort" }))) === true,
77 interrupted = () => {},
78 ): Promise<void> => {
79 const idle = () => {
80 if (pending === null && immediate.size === 0 && closeInterruptedPaste === null) onIdle();
81 };
82 const chunks = chunkTerminalWrite(data);
83 const run = () => sendChunks(data, chunks, send, recover, interrupted);
84 if (pending === null && closeInterruptedPaste === null && chunks.length === 1) {
85 const current = run();
86 immediate.add(current);
87 void current.then(
88 () => {
89 immediate.delete(current);
90 idle();
91 },
92 () => {
93 immediate.delete(current);
94 idle();
95 },
96 );
97 return current;
98 }
99 const previous = pending ?? (immediate.size > 0 ? Promise.allSettled(immediate) : null);
100 const current = previous === null ? run() : previous.then(run, run);
101 pending = current;
102 const reset = () => {
103 if (pending === current) pending = null;
104 idle();
105 };
106 void current.then(reset, reset);
107 return current;
108 };
109}
110
111const writers = new Map<string, ReturnType<typeof createTerminalInputWriter>>();
112
113/** Retain ordering and framing obligations until acknowledged, across terminal view remounts. */
114export function terminalInputWriter(key: string) {
115 const existing = writers.get(key);
116 if (existing) return existing;
117 const writer = createTerminalInputWriter(() => {
118 if (writers.get(key) === writer) writers.delete(key);
119 });
120 writers.set(key, writer);
121 return writer;
122}