Open History to see the last commit
1export interface TerminalOutputChunk {
2 readonly startOffset: number;
3 readonly data: string;
4 readonly byteLength: number;
5}
6
7export interface TerminalOutputState {
8 readonly generation: number;
9 readonly chunks: ReadonlyArray<TerminalOutputChunk>;
10 readonly retainedBytes: number;
11 readonly resetVersion: number;
12 readonly nextOffset: number;
13}
14
15export interface TerminalOutputCursor {
16 readonly generation: number;
17 readonly resetVersion: number;
18 readonly offset: number;
19}
20
21export const INITIAL_TERMINAL_OUTPUT_CURSOR = Object.freeze<TerminalOutputCursor>({
22 generation: -1,
23 resetVersion: -1,
24 offset: 0,
25});
26
27export type TerminalOutputUpdate =
28 | {
29 readonly type: "none";
30 readonly cursor: TerminalOutputCursor;
31 }
32 | {
33 readonly type: "reset";
34 readonly data: string;
35 readonly cursor: TerminalOutputCursor;
36 }
37 | {
38 readonly type: "append";
39 readonly cursor: TerminalOutputCursor;
40 readonly data: string;
41 };
42
43export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024;
44const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024;
45const MAX_TERMINAL_OUTPUT_CHUNKS = 1_024;
46const textEncoder = new TextEncoder();
47// A BOM at a retained chunk boundary is terminal data, not an encoding marker.
48const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
49
50export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze<TerminalOutputState>({
51 generation: 0,
52 chunks: Object.freeze([]),
53 retainedBytes: 0,
54 resetVersion: 0,
55 nextOffset: 0,
56});
57
58interface Utf8Chunk {
59 readonly data: string;
60 readonly byteLength: number;
61}
62
63function splitStringByUtf8Bytes(data: string, maxBytes: number): ReadonlyArray<Utf8Chunk> {
64 if (data.length === 0) return [];
65
66 const encoded = textEncoder.encode(data);
67 if (encoded.byteLength <= maxBytes) {
68 return [{ data, byteLength: encoded.byteLength }];
69 }
70
71 const chunks: Utf8Chunk[] = [];
72 let offset = 0;
73 while (offset < encoded.byteLength) {
74 let end = Math.min(offset + maxBytes, encoded.byteLength);
75 while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) {
76 end -= 1;
77 }
78 // A degenerate budget smaller than one code point still has to advance:
79 // include the whole code point rather than looping forever.
80 if (end === offset) {
81 end = Math.min(offset + maxBytes, encoded.byteLength);
82 while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) {
83 end += 1;
84 }
85 }
86 const bytes = encoded.subarray(offset, end);
87 chunks.push({ data: textDecoder.decode(bytes), byteLength: bytes.byteLength });
88 offset = end;
89 }
90
91 return chunks;
92}
93
94function trimBufferToBytes(buffer: string, maxBufferBytes: number): string {
95 if (maxBufferBytes <= 0) {
96 return "";
97 }
98
99 const encoded = textEncoder.encode(buffer);
100 if (encoded.byteLength <= maxBufferBytes) {
101 return buffer;
102 }
103
104 let start = encoded.byteLength - maxBufferBytes;
105 while (start < encoded.length) {
106 const byte = encoded[start];
107 if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000) {
108 break;
109 }
110 start += 1;
111 }
112
113 return textDecoder.decode(encoded.subarray(start));
114}
115
116function splitOutputChunks(
117 data: string,
118 firstOffset: number,
119 maxChunkBytes = DEFAULT_TERMINAL_CHUNK_BYTES,
120): {
121 readonly chunks: ReadonlyArray<TerminalOutputChunk>;
122 readonly nextOffset: number;
123 readonly byteLength: number;
124} {
125 const split = splitStringByUtf8Bytes(data, maxChunkBytes);
126 let byteLength = 0;
127 let nextOffset = firstOffset;
128 const chunks = split.map((chunk) => {
129 byteLength += chunk.byteLength;
130 const startOffset = nextOffset;
131 nextOffset += chunk.data.length;
132 return {
133 startOffset,
134 data: chunk.data,
135 byteLength: chunk.byteLength,
136 };
137 });
138
139 return {
140 chunks,
141 nextOffset,
142 byteLength,
143 };
144}
145
146function compactRetainedChunks(chunks: ReadonlyArray<TerminalOutputChunk>) {
147 const compacted: TerminalOutputChunk[] = [];
148 for (const chunk of chunks) {
149 const previous = compacted.at(-1);
150 if (
151 previous !== undefined &&
152 previous.startOffset + previous.data.length === chunk.startOffset &&
153 previous.byteLength + chunk.byteLength <= DEFAULT_TERMINAL_CHUNK_BYTES
154 ) {
155 compacted[compacted.length - 1] = {
156 startOffset: previous.startOffset,
157 data: `${previous.data}${chunk.data}`,
158 byteLength: previous.byteLength + chunk.byteLength,
159 };
160 } else {
161 compacted.push(chunk);
162 }
163 }
164 return compacted;
165}
166
167function trimOutputChunkStart(
168 chunk: TerminalOutputChunk,
169 bytesToDrop: number,
170): TerminalOutputChunk {
171 let offset = 0;
172 let droppedBytes = 0;
173 while (droppedBytes < bytesToDrop && offset < chunk.data.length) {
174 const codepoint = chunk.data.codePointAt(offset)!;
175 droppedBytes += codepoint <= 0x7f ? 1 : codepoint <= 0x7ff ? 2 : codepoint <= 0xffff ? 3 : 4;
176 offset += codepoint <= 0xffff ? 1 : 2;
177 }
178 return {
179 ...chunk,
180 startOffset: chunk.startOffset + offset,
181 data: chunk.data.slice(offset),
182 byteLength: chunk.byteLength - droppedBytes,
183 };
184}
185
186function appendOutput(
187 current: TerminalOutputState,
188 data: string,
189 maxBufferBytes: number,
190): TerminalOutputState {
191 if (data.length === 0) return current;
192 if (maxBufferBytes <= 0) {
193 return {
194 generation: current.generation,
195 chunks: [],
196 retainedBytes: 0,
197 resetVersion: current.resetVersion + 1,
198 nextOffset: current.nextOffset + data.length,
199 };
200 }
201 const appended = splitOutputChunks(
202 data,
203 current.nextOffset,
204 Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)),
205 );
206
207 const chunks = [...current.chunks, ...appended.chunks];
208 let retainedBytes = current.retainedBytes + appended.byteLength;
209 let firstRetainedIndex = 0;
210 while (retainedBytes > maxBufferBytes && firstRetainedIndex < chunks.length) {
211 const first = chunks[firstRetainedIndex]!;
212 const bytesToDrop = retainedBytes - maxBufferBytes;
213 if (bytesToDrop < first.byteLength) {
214 const trimmed = trimOutputChunkStart(first, bytesToDrop);
215 retainedBytes -= first.byteLength - trimmed.byteLength;
216 if (trimmed.byteLength > 0) {
217 chunks[firstRetainedIndex] = trimmed;
218 } else {
219 firstRetainedIndex += 1;
220 }
221 break;
222 }
223 retainedBytes -= first.byteLength;
224 firstRetainedIndex += 1;
225 }
226
227 let retainedChunks = firstRetainedIndex === 0 ? chunks : chunks.slice(firstRetainedIndex);
228 if (retainedChunks.length > MAX_TERMINAL_OUTPUT_CHUNKS) {
229 retainedChunks = compactRetainedChunks(retainedChunks);
230 const excessChunks = retainedChunks.length - MAX_TERMINAL_OUTPUT_CHUNKS;
231 if (excessChunks > 0) {
232 for (const chunk of retainedChunks.slice(0, excessChunks)) {
233 retainedBytes -= chunk.byteLength;
234 }
235 retainedChunks = retainedChunks.slice(excessChunks);
236 }
237 }
238
239 return {
240 generation: current.generation,
241 chunks: retainedChunks,
242 retainedBytes,
243 resetVersion: current.resetVersion,
244 nextOffset: appended.nextOffset,
245 };
246}
247
248function resetOutput(
249 current: TerminalOutputState,
250 data: string,
251 maxBufferBytes: number,
252): TerminalOutputState {
253 const retained = trimBufferToBytes(data, maxBufferBytes);
254 const reset = splitOutputChunks(
255 retained,
256 0,
257 Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)),
258 );
259 return {
260 generation: current.generation,
261 chunks: reset.chunks,
262 retainedBytes: reset.byteLength,
263 resetVersion: current.resetVersion + 1,
264 nextOffset: reset.nextOffset,
265 };
266}
267
268export function terminalOutputText(output: TerminalOutputState): string {
269 return output.chunks.map((chunk) => chunk.data).join("");
270}
271
272export function readTerminalOutputUpdate(
273 output: TerminalOutputState,
274 cursor: TerminalOutputCursor,
275): TerminalOutputUpdate {
276 const nextCursor = {
277 generation: output.generation,
278 resetVersion: output.resetVersion,
279 offset: output.nextOffset,
280 };
281 const firstChunk = output.chunks[0];
282 if (
283 cursor.generation !== output.generation ||
284 cursor.resetVersion !== output.resetVersion ||
285 cursor.offset < (firstChunk?.startOffset ?? output.nextOffset)
286 ) {
287 return { type: "reset", data: terminalOutputText(output), cursor: nextCursor };
288 }
289
290 const appended = output.chunks.filter(
291 (chunk) => chunk.startOffset + chunk.data.length > cursor.offset,
292 );
293 if (appended.length === 0) {
294 return { type: "none", cursor: nextCursor };
295 }
296 return {
297 type: "append",
298 data: appended
299 .map((chunk) => chunk.data.slice(Math.max(0, cursor.offset - chunk.startOffset)))
300 .join(""),
301 cursor: nextCursor,
302 };
303}
304
305export { appendOutput, resetOutput };