Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalOutput.ts

390 lines12.5 KB

1import {
2 retainTerminalSnapshotHistory,
3 skipTerminalSnapshotContinuation,
4 TERMINAL_SEQUENCE_GROUND,
5 type TerminalSessionSnapshot,
6 terminalSequenceEnd,
7 terminalSequenceStateAfter,
8} from "@t3tools/contracts";
9​
10export interface TerminalOutputChunk {
11 readonly startOffset: number;
12 readonly data: string;
13 readonly byteLength: number;
15​
16export interface TerminalOutputState {
17 readonly generation: number;
18 readonly chunks: ReadonlyArray<TerminalOutputChunk>;
19 readonly retainedBytes: number;
20 readonly resetVersion: number;
21 readonly nextOffset: number;
22 // The terminal parser's state at the first retained code unit. Trimming can cut a control
23 // sequence, and a replay has to skip the rest of it instead of printing it.
24 readonly sequenceState: number;
25 /** Parser state of a prefix omitted after the snapshot history. */
26 readonly pendingSnapshotSequenceState?: number | undefined;
27 /** Chunks before this offset are replayed to emulators but are no longer displayed text. */
28 readonly textStartOffset: number;
30​
31export interface TerminalOutputCursor {
32 readonly generation: number;
33 readonly resetVersion: number;
34 readonly offset: number;
35 // The cut control sequence still open at `offset`, which the reader's terminal never entered.
36 readonly sequenceState: number;
38​
39export const INITIAL_TERMINAL_OUTPUT_CURSOR = Object.freeze<TerminalOutputCursor>({
40 generation: -1,
41 resetVersion: -1,
42 offset: 0,
43 sequenceState: TERMINAL_SEQUENCE_GROUND,
44});
45​
46export type TerminalOutputUpdate =
47 | {
48 readonly type: "none";
49 readonly cursor: TerminalOutputCursor;
50 }
51 | {
52 readonly type: "reset";
53 readonly data: string;
54 readonly cursor: TerminalOutputCursor;
55 }
56 | {
57 readonly type: "append";
58 readonly cursor: TerminalOutputCursor;
59 readonly data: string;
60 };
61​
62const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024;
63const MAX_TERMINAL_OUTPUT_CHUNKS = 1_024;
64const textEncoder = new TextEncoder();
65// A BOM at a retained chunk boundary is terminal data, not an encoding marker.
66const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
67​
68export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze<TerminalOutputState>({
69 generation: 0,
70 chunks: Object.freeze([]),
71 retainedBytes: 0,
72 resetVersion: 0,
73 nextOffset: 0,
74 sequenceState: TERMINAL_SEQUENCE_GROUND,
75 textStartOffset: 0,
76});
77​
78interface Utf8Chunk {
79 readonly data: string;
80 readonly byteLength: number;
82​
83function splitStringByUtf8Bytes(data: string, maxBytes: number): ReadonlyArray<Utf8Chunk> {
84 if (data.length === 0) return [];
85​
86 const encoded = textEncoder.encode(data);
87 if (encoded.byteLength <= maxBytes) {
88 return [{ data, byteLength: encoded.byteLength }];
89 }
90​
91 const chunks: Utf8Chunk[] = [];
92 let offset = 0;
93 while (offset < encoded.byteLength) {
94 let end = Math.min(offset + maxBytes, encoded.byteLength);
95 while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) {
96 end -= 1;
97 }
98 // A degenerate budget smaller than one code point still has to advance:
99 // include the whole code point rather than looping forever.
100 if (end === offset) {
101 end = Math.min(offset + maxBytes, encoded.byteLength);
102 while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) {
103 end += 1;
104 }
105 }
106 const bytes = encoded.subarray(offset, end);
107 chunks.push({ data: textDecoder.decode(bytes), byteLength: bytes.byteLength });
108 offset = end;
109 }
110​
111 return chunks;
113​
114function splitOutputChunks(
115 data: string,
116 firstOffset: number,
117 maxChunkBytes = DEFAULT_TERMINAL_CHUNK_BYTES,
118): {
119 readonly chunks: ReadonlyArray<TerminalOutputChunk>;
120 readonly nextOffset: number;
121 readonly byteLength: number;
122} {
123 const split = splitStringByUtf8Bytes(data, maxChunkBytes);
124 let byteLength = 0;
125 let nextOffset = firstOffset;
126 const chunks = split.map((chunk) => {
127 byteLength += chunk.byteLength;
128 const startOffset = nextOffset;
129 nextOffset += chunk.data.length;
130 return {
131 startOffset,
132 data: chunk.data,
133 byteLength: chunk.byteLength,
134 };
135 });
136​
137 return {
138 chunks,
139 nextOffset,
140 byteLength,
141 };
143​
144function compactRetainedChunks(chunks: ReadonlyArray<TerminalOutputChunk>) {
145 const compacted: TerminalOutputChunk[] = [];
146 for (const chunk of chunks) {
147 const previous = compacted.at(-1);
148 if (
149 previous !== undefined &&
150 previous.startOffset + previous.data.length === chunk.startOffset &&
151 previous.byteLength + chunk.byteLength <= DEFAULT_TERMINAL_CHUNK_BYTES
152 ) {
153 compacted[compacted.length - 1] = {
154 startOffset: previous.startOffset,
155 data: `${previous.data}${chunk.data}`,
156 byteLength: previous.byteLength + chunk.byteLength,
157 };
158 } else {
159 compacted.push(chunk);
160 }
161 }
162 return compacted;
164​
165function trimOutputChunkStart(
166 chunk: TerminalOutputChunk,
167 bytesToDrop: number,
168): TerminalOutputChunk {
169 let offset = 0;
170 let droppedBytes = 0;
171 while (droppedBytes < bytesToDrop && offset < chunk.data.length) {
172 const codepoint = chunk.data.codePointAt(offset)!;
173 droppedBytes += codepoint <= 0x7f ? 1 : codepoint <= 0x7ff ? 2 : codepoint <= 0xffff ? 3 : 4;
174 offset += codepoint <= 0xffff ? 1 : 2;
175 }
176 return {
177 ...chunk,
178 startOffset: chunk.startOffset + offset,
179 data: chunk.data.slice(offset),
180 byteLength: chunk.byteLength - droppedBytes,
181 };
183​
184function appendOutput(
185 current: TerminalOutputState,
186 data: string,
187 maxBufferBytes: number,
188): TerminalOutputState {
189 const pending = current.pendingSnapshotSequenceState;
190 if (pending === undefined || data.length === 0) {
191 return appendRetainedOutput(current, data, maxBufferBytes);
192 }
193 const continuation = skipTerminalSnapshotContinuation(pending, data);
194 return appendRetainedOutput(
195 {
196 ...current,
197 pendingSnapshotSequenceState:
198 continuation.state === TERMINAL_SEQUENCE_GROUND ? undefined : continuation.state,
199 },
200 continuation.data,
201 maxBufferBytes,
202 );
204​
205function appendRetainedOutput(
206 current: TerminalOutputState,
207 data: string,
208 maxBufferBytes: number,
209): TerminalOutputState {
210 if (data.length === 0) return current;
211 if (maxBufferBytes <= 0) {
212 return {
213 generation: current.generation,
214 chunks: [],
215 retainedBytes: 0,
216 resetVersion: current.resetVersion + 1,
217 nextOffset: current.nextOffset + data.length,
218 sequenceState: TERMINAL_SEQUENCE_GROUND,
219 textStartOffset: current.textStartOffset,
220 };
221 }
222 const appended = splitOutputChunks(
223 data,
224 current.nextOffset,
225 Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)),
226 );
227​
228 const chunks = [...current.chunks, ...appended.chunks];
229 let retainedBytes = current.retainedBytes + appended.byteLength;
230 let sequenceState = current.sequenceState;
231 let firstRetainedIndex = 0;
232 while (retainedBytes > maxBufferBytes && firstRetainedIndex < chunks.length) {
233 const first = chunks[firstRetainedIndex]!;
234 const bytesToDrop = retainedBytes - maxBufferBytes;
235 if (bytesToDrop < first.byteLength) {
236 const trimmed = trimOutputChunkStart(first, bytesToDrop);
237 sequenceState = terminalSequenceStateAfter(
238 sequenceState,
239 first.data,
240 0,
241 first.data.length - trimmed.data.length,
242 );
243 retainedBytes -= first.byteLength - trimmed.byteLength;
244 if (trimmed.byteLength > 0) {
245 chunks[firstRetainedIndex] = trimmed;
246 } else {
247 firstRetainedIndex += 1;
248 }
249 break;
250 }
251 sequenceState = terminalSequenceStateAfter(sequenceState, first.data);
252 retainedBytes -= first.byteLength;
253 firstRetainedIndex += 1;
254 }
255​
256 let retainedChunks = firstRetainedIndex === 0 ? chunks : chunks.slice(firstRetainedIndex);
257 if (retainedChunks.length > MAX_TERMINAL_OUTPUT_CHUNKS) {
258 retainedChunks = compactRetainedChunks(retainedChunks);
259 const excessChunks = retainedChunks.length - MAX_TERMINAL_OUTPUT_CHUNKS;
260 if (excessChunks > 0) {
261 for (const chunk of retainedChunks.slice(0, excessChunks)) {
262 sequenceState = terminalSequenceStateAfter(sequenceState, chunk.data);
263 retainedBytes -= chunk.byteLength;
264 }
265 retainedChunks = retainedChunks.slice(excessChunks);
266 }
267 }
268​
269 return {
270 generation: current.generation,
271 chunks: retainedChunks,
272 retainedBytes,
273 resetVersion: current.resetVersion,
274 nextOffset: appended.nextOffset,
275 sequenceState,
276 textStartOffset: current.textStartOffset,
277 };
279​
280function resetOutput(
281 current: TerminalOutputState,
282 snapshot: Pick<TerminalSessionSnapshot, "history" | "historySequenceState">,
283 maxBufferBytes: number,
284): TerminalOutputState {
285 const retained = retainTerminalSnapshotHistory(snapshot.history, maxBufferBytes);
286 const reset = splitOutputChunks(
287 retained.history,
288 0,
289 Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)),
290 );
291 return {
292 generation: current.generation,
293 chunks: reset.chunks,
294 retainedBytes: reset.byteLength,
295 resetVersion: current.resetVersion + 1,
296 nextOffset: reset.nextOffset,
297 sequenceState: TERMINAL_SEQUENCE_GROUND,
298 pendingSnapshotSequenceState: snapshot.historySequenceState ?? retained.historySequenceState,
299 textStartOffset: 0,
300 };
302​
303// Erases the screen and scrollback only. A full emulator reset would drop the
304// screen and input modes the still-running program negotiated.
305const CLEAR_TERMINAL_TEXT = "\u001b[H\u001b[2J\u001b[3J";
306​
307/** Earlier output stays retained so a replay from the start restores those modes. */
308function clearOutput(
309 current: TerminalOutputState,
310 maxBufferBytes: number,
311 pendingControlSequence = "",
312): TerminalOutputState {
313 const data = CLEAR_TERMINAL_TEXT + pendingControlSequence;
314 // The erase rides over the budget: trimming here would evict the output that set those modes.
315 const cleared = appendOutput(
316 { ...current, pendingSnapshotSequenceState: undefined },
317 data,
318 maxBufferBytes <= 0
319 ? maxBufferBytes
320 : Math.max(maxBufferBytes, current.retainedBytes + textEncoder.encode(data).byteLength),
321 );
322 return { ...cleared, textStartOffset: cleared.nextOffset };
324​
325/** Everything a fresh emulator replays: retained output from outside any control sequence. */
326export function terminalOutputReplay(output: TerminalOutputState): string {
327 const text = output.chunks.map((chunk) => chunk.data).join("");
328 return text.slice(terminalSequenceEnd(output.sequenceState, text));
330​
331/** The output as plain text, for surfaces that do not interpret escape sequences. */
332export function terminalOutputText(output: TerminalOutputState): string {
333 const text = output.chunks.map((chunk) => chunk.data).join("");
334 const firstOffset = output.chunks[0]?.startOffset ?? output.nextOffset;
335 const start = Math.max(0, output.textStartOffset - firstOffset);
336 const sequenceState = terminalSequenceStateAfter(output.sequenceState, text, 0, start);
337 const visible = text.slice(start);
338 return visible.slice(terminalSequenceEnd(sequenceState, visible));
340​
341export function readTerminalOutputUpdate(
342 output: TerminalOutputState,
343 cursor: TerminalOutputCursor,
344): TerminalOutputUpdate {
345 const position = {
346 generation: output.generation,
347 resetVersion: output.resetVersion,
348 offset: output.nextOffset,
349 };
350 const firstChunk = output.chunks[0];
351 if (
352 cursor.generation !== output.generation ||
353 cursor.resetVersion !== output.resetVersion ||
354 cursor.offset < (firstChunk?.startOffset ?? output.nextOffset)
355 ) {
356 const text = output.chunks.map((chunk) => chunk.data).join("");
357 const start = terminalSequenceEnd(output.sequenceState, text);
358 return {
359 type: "reset",
360 data: text.slice(start),
361 cursor: {
362 ...position,
363 sequenceState: terminalSequenceStateAfter(output.sequenceState, text, 0, start),
364 },
365 };
366 }
367​
368 // Appends and compaction preserve offset order, so unread chunks form a suffix.
369 let firstUnread = output.chunks.length;
370 while (firstUnread > 0) {
371 const chunk = output.chunks[firstUnread - 1]!;
372 if (!(chunk.startOffset + chunk.data.length > cursor.offset)) break;
373 firstUnread -= 1;
374 }
375 const text = output.chunks
376 .slice(firstUnread)
377 .map((chunk) => chunk.data.slice(Math.max(0, cursor.offset - chunk.startOffset)))
378 .join("");
379 const start = terminalSequenceEnd(cursor.sequenceState, text);
380 const nextCursor = {
381 ...position,
382 sequenceState: terminalSequenceStateAfter(cursor.sequenceState, text, 0, start),
383 };
384 if (start === text.length) {
385 return { type: "none", cursor: nextCursor };
386 }
387 return { type: "append", data: text.slice(start), cursor: nextCursor };
389​
390export { appendOutput, clearOutput, resetOutput };