Open History to see the last commit
1/** Server/client folds must agree: only the last LIVE_LINES are cursor-addressable, with no wrapping.
2 * SGR resets at line boundaries for safe tail cuts; unfinished escapes carry through pending. */
3export interface TerminalOutputState {
4 /** Fixed lines followed by the live window; contains only SGR escapes. */
5 readonly text: string;
6 readonly truncated: boolean;
7 /** An unfinished escape sequence awaiting the next chunk. */
8 readonly pending: string;
9 readonly screen: TerminalScreen;
10}
11
12/** Canonical SGR parameters; empty means default style. */
13interface Run {
14 readonly pen: string;
15 readonly text: string;
16}
17type Line = ReadonlyArray<Run>;
18
19interface TerminalScreen {
20 /** Scrolled-out lines, each ending in newline. */
21 readonly settled: string;
22 /** Never empty. */
23 readonly lines: ReadonlyArray<Line>;
24 readonly row: number;
25 readonly col: number;
26 readonly pen: string;
27 readonly saved: { readonly row: number; readonly col: number } | null;
28}
29
30export const EMPTY_TERMINAL_OUTPUT: TerminalOutputState = {
31 text: "",
32 truncated: false,
33 pending: "",
34 screen: { settled: "", lines: [[]], row: 0, col: 0, pen: "", saved: null },
35};
36
37/** Default command tail, in UTF-16 code units. */
38export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024;
39
40const LIVE_LINES = 64;
41
42const MAX_PENDING_ESCAPE = 64;
43
44const ESC = "\u001b";
45
46function sgr(pen: string): string {
47 return pen === "" ? `${ESC}[0m` : `${ESC}[0;${pen}m`;
48}
49
50// Lines stay immutable after a feed, so their measured lengths can be cached.
51const lineLengths = new WeakMap<Line, number>();
52
53function lineLength(line: Line): number {
54 const cached = lineLengths.get(line);
55 if (cached !== undefined) return cached;
56 let length = 0;
57 for (const run of line) length += run.text.length;
58 lineLengths.set(line, length);
59 return length;
60}
61
62// Strip oldest styles to bound work on color-per-character output.
63const MAX_LINE_RUNS = 2_048;
64
65function sliceLine(line: Line, start: number, end: number): Array<Run> {
66 const out: Array<Run> = [];
67 let offset = 0;
68 for (const run of line) {
69 const runEnd = offset + run.text.length;
70 if (runEnd > start && offset < end) {
71 out.push({
72 pen: run.pen,
73 text: run.text.slice(Math.max(0, start - offset), Math.min(run.text.length, end - offset)),
74 });
75 }
76 offset = runEnd;
77 if (offset >= end) break;
78 }
79 return out;
80}
81
82function pushRun(runs: Array<Run>, run: Run): void {
83 if (run.text.length === 0) return;
84 const last = runs.at(-1);
85 if (last !== undefined && last.pen === run.pen) {
86 runs[runs.length - 1] = { pen: last.pen, text: last.text + run.text };
87 } else {
88 runs.push(run);
89 }
90}
91
92/** Mutates only lines owned by this feed. */
93function trimLineStart(runs: Array<Run>, count: number): void {
94 let dropped = 0;
95 let remaining = count;
96 while (remaining > 0 && dropped < runs.length) {
97 const run = runs[dropped]!;
98 if (run.text.length <= remaining) {
99 remaining -= run.text.length;
100 dropped += 1;
101 } else {
102 runs[dropped] = { pen: run.pen, text: run.text.slice(remaining) };
103 remaining = 0;
104 }
105 }
106 if (dropped > 0) runs.splice(0, dropped);
107}
108
109function writeLine(line: Line, col: number, text: string, pen: string): Line {
110 const length = lineLength(line);
111 if (col === length) {
112 const runs = line.slice();
113 pushRun(runs, { pen, text });
114 return runs;
115 }
116 const runs: Array<Run> = [];
117 for (const run of sliceLine(line, 0, Math.min(col, length))) pushRun(runs, run);
118 if (col > length) pushRun(runs, { pen: "", text: " ".repeat(col - length) });
119 pushRun(runs, { pen, text });
120 for (const run of sliceLine(line, col + text.length, length)) pushRun(runs, run);
121 return runs;
122}
123
124/** Erase in line: 0 cursor to end, 1 start to cursor, 2 whole line. */
125function eraseLine(line: Line, col: number, mode: number): Line {
126 const length = lineLength(line);
127 if (mode === 0) return sliceLine(line, 0, col);
128 if (mode === 1) {
129 const runs: Array<Run> = [];
130 pushRun(runs, { pen: "", text: " ".repeat(Math.min(col + 1, length)) });
131 for (const run of sliceLine(line, col + 1, length)) pushRun(runs, run);
132 return runs;
133 }
134 return [];
135}
136
137function serializeLine(line: Line): string {
138 let out = "";
139 let current = "";
140 for (const run of line) {
141 if (run.pen !== current) {
142 out += sgr(run.pen);
143 current = run.pen;
144 }
145 out += run.text;
146 }
147 return current === "" ? out : out + sgr("");
148}
149
150interface Attributes {
151 bold: boolean;
152 dim: boolean;
153 italic: boolean;
154 underline: boolean;
155 strike: boolean;
156 inverse: boolean;
157 fg: string;
158 bg: string;
159}
160
161function parsePen(pen: string): Attributes {
162 const attributes: Attributes = {
163 bold: false,
164 dim: false,
165 italic: false,
166 underline: false,
167 strike: false,
168 inverse: false,
169 fg: "",
170 bg: "",
171 };
172 if (pen !== "") applySgr(attributes, pen.split(";").map(Number));
173 return attributes;
174}
175
176function formatPen(attributes: Attributes): string {
177 const parts: Array<string> = [];
178 if (attributes.bold) parts.push("1");
179 if (attributes.dim) parts.push("2");
180 if (attributes.italic) parts.push("3");
181 if (attributes.underline) parts.push("4");
182 if (attributes.inverse) parts.push("7");
183 if (attributes.strike) parts.push("9");
184 if (attributes.fg !== "") parts.push(attributes.fg);
185 if (attributes.bg !== "") parts.push(attributes.bg);
186 return parts.join(";");
187}
188
189/** Reads 5;n or 2;r;g;b colors; returns the code and next index. */
190function extendedColor(
191 code: number,
192 params: ReadonlyArray<number>,
193 index: number,
194): [string | undefined, number] {
195 const mode = params[index + 1];
196 if (mode === 5) {
197 const value = params[index + 2];
198 return value === undefined || value > 255
199 ? [undefined, index + 3]
200 : [`${code};5;${value}`, index + 3];
201 }
202 if (mode === 2) {
203 const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]];
204 if (r === undefined || g === undefined || b === undefined) return [undefined, index + 5];
205 return [`${code};2;${r & 255};${g & 255};${b & 255}`, index + 5];
206 }
207 return [undefined, index + 2];
208}
209
210function applySgr(attributes: Attributes, params: ReadonlyArray<number>): void {
211 if (params.length === 0) params = [0];
212 for (let index = 0; index < params.length;) {
213 const code = params[index]!;
214 if (code === 0 || Number.isNaN(code)) {
215 Object.assign(attributes, parsePen(""));
216 } else if (code === 1) attributes.bold = true;
217 else if (code === 2) attributes.dim = true;
218 else if (code === 3) attributes.italic = true;
219 else if (code === 4) attributes.underline = true;
220 else if (code === 7) attributes.inverse = true;
221 else if (code === 9) attributes.strike = true;
222 else if (code === 22) attributes.bold = attributes.dim = false;
223 else if (code === 23) attributes.italic = false;
224 else if (code === 24) attributes.underline = false;
225 else if (code === 27) attributes.inverse = false;
226 else if (code === 29) attributes.strike = false;
227 else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) attributes.fg = String(code);
228 else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
229 attributes.bg = String(code);
230 else if (code === 39) attributes.fg = "";
231 else if (code === 49) attributes.bg = "";
232 else if (code === 38 || code === 48) {
233 const [color, next] = extendedColor(code, params, index);
234 if (color !== undefined) attributes[code === 38 ? "fg" : "bg"] = color;
235 index = next;
236 continue;
237 }
238 index += 1;
239 }
240}
241
242const STRING_SEQUENCE_INTRODUCERS = new Set(["]", "P", "X", "_", "^"]);
243
244/** Length of a complete escape sequence starting at `index` (an ESC), or -1 if unfinished. */
245function escapeLength(input: string, index: number): number {
246 const next = input[index + 1];
247 if (next === undefined) return -1;
248 if (next === "[") {
249 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
250 const code = input.charCodeAt(cursor);
251 if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;
252 }
253 return -1;
254 }
255 if (STRING_SEQUENCE_INTRODUCERS.has(next)) {
256 // BEL/ST ends string sequences; also stop at newlines so stray binary introducers cannot hide later output.
257 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
258 if (input[cursor] === "\u0007") return cursor - index + 1;
259 if (input[cursor] === "\n") return cursor - index;
260 if (input[cursor] === ESC) {
261 if (cursor + 1 >= input.length) return -1;
262 if (input[cursor + 1] === "\\") return cursor - index + 2;
263 }
264 }
265 return -1;
266 }
267 // Charset designations take three bytes; other sequences take two.
268 if (next === "(" || next === ")" || next === "*" || next === "+") {
269 return index + 2 < input.length ? 3 : -1;
270 }
271 return 2;
272}
273
274const penTransitions = new Map<string, string>();
275
276// Colon color sub-parameters carry an optional color-space id absent from the semicolon form.
277function csiParams(params: string): Array<number> {
278 const numbers: Array<number> = [];
279 for (const part of params.split(";")) {
280 if (!part.includes(":")) {
281 numbers.push(Number(part));
282 continue;
283 }
284 const sub = part.split(":").map(Number);
285 if ((sub[0] === 38 || sub[0] === 48) && sub[1] === 2 && sub.length >= 6) sub.splice(2, 1);
286 numbers.push(...sub);
287 }
288 return numbers;
289}
290
291class Terminal {
292 settled: string;
293 lines: Array<Line>;
294 row: number;
295 col: number;
296 pen: string;
297 saved: { row: number; col: number } | null;
298 /** Output was discarded on purpose (scrollback cleared or window over budget). */
299 dropped = false;
300 readonly maxChars: number;
301 /** Lines created during this feed, which it may extend in place. */
302 private readonly owned = new WeakSet<Line>();
303
304 constructor(screen: TerminalScreen, maxChars: number) {
305 this.maxChars = maxChars;
306 this.settled = screen.settled;
307 this.lines = screen.lines.slice();
308 this.row = screen.row;
309 this.col = screen.col;
310 this.pen = screen.pen;
311 this.saved = screen.saved;
312 }
313
314 write(text: string): void {
315 let line = this.lines[this.row]!;
316 const length = lineLength(line);
317 if (this.col === length && this.owned.has(line)) {
318 pushRun(line as Array<Run>, { pen: this.pen, text });
319 lineLengths.set(line, length + text.length);
320 } else {
321 line = writeLine(line, this.col, text, this.pen);
322 this.owned.add(line);
323 }
324 this.col += text.length;
325 if (line.length > MAX_LINE_RUNS) {
326 // Flatten old runs so later trimming stays cheap.
327 const keep = line.length - MAX_LINE_RUNS / 8;
328 const plain = line
329 .slice(0, keep)
330 .map((run) => run.text)
331 .join("");
332 line = [{ pen: "", text: plain }, ...line.slice(keep)];
333 this.owned.add(line);
334 }
335 // Trim each write to maxChars columns so results do not depend on chunk boundaries.
336 let current = lineLength(line);
337 if (current > this.maxChars) {
338 let removed = current - this.maxChars;
339 if (!this.owned.has(line)) {
340 line = line.slice();
341 this.owned.add(line);
342 }
343 trimLineStart(line as Array<Run>, removed);
344 // Never start on a lone low surrogate.
345 const first = line[0]?.text.charCodeAt(0) ?? 0;
346 if (first >= 0xdc00 && first <= 0xdfff) {
347 trimLineStart(line as Array<Run>, 1);
348 removed += 1;
349 }
350 current -= removed;
351 this.dropped = true;
352 this.col = Math.max(0, this.col - removed);
353 if (this.saved !== null && this.saved.row === this.row) {
354 this.saved = { ...this.saved, col: Math.max(0, this.saved.col - removed) };
355 }
356 }
357 lineLengths.set(line, current);
358 this.lines[this.row] = line;
359 }
360
361 newline(): void {
362 this.row += 1;
363 this.col = 0;
364 if (this.row === this.lines.length) this.lines.push([]);
365 while (this.lines.length > LIVE_LINES) this.scrollOut();
366 }
367
368 scrollOut(): number {
369 const line = this.lines.shift()!;
370 this.settle(line);
371 this.row -= 1;
372 if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };
373 return lineLength(line);
374 }
375
376 settle(line: Line): void {
377 this.settled += `${serializeLine(line)}\n`;
378 if (this.settled.length > 2 * this.maxChars) {
379 this.settled = terminalOutputTail(this.settled, this.maxChars).text;
380 this.dropped = true;
381 }
382 }
383
384 moveTo(row: number, col: number): void {
385 this.row = Math.max(0, Math.min(this.lines.length - 1, row));
386 // A huge column (ESC[999999999C) would otherwise pad a line past any string limit.
387 this.col = Math.max(0, Math.min(TERMINAL_OUTPUT_TAIL_CHARS, col));
388 }
389
390 csi(params: string, final: string): void {
391 if (/^[?>=]/u.test(params)) return; // Mode switches (cursor visibility, bracketed paste).
392 const numbers = params === "" ? [] : csiParams(params);
393 const count = Math.max(1, numbers[0] || 1);
394 switch (final) {
395 case "m": {
396 const key = `${this.pen}|${params}`;
397 let pen = penTransitions.get(key);
398 if (pen === undefined) {
399 const attributes = parsePen(this.pen);
400 applySgr(attributes, numbers);
401 pen = formatPen(attributes);
402 if (penTransitions.size >= 512) penTransitions.clear();
403 penTransitions.set(key, pen);
404 }
405 this.pen = pen;
406 return;
407 }
408 case "A":
409 return this.moveTo(this.row - count, this.col);
410 case "B":
411 return this.moveTo(this.row + count, this.col);
412 case "C":
413 return this.moveTo(this.row, this.col + count);
414 case "D":
415 return this.moveTo(this.row, this.col - count);
416 case "E":
417 return this.moveTo(this.row + count, 0);
418 case "F":
419 return this.moveTo(this.row - count, 0);
420 case "G":
421 return this.moveTo(this.row, count - 1);
422 case "H":
423 case "f":
424 // Rows count from the top of the window: there is no fixed screen height.
425 return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);
426 case "K":
427 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);
428 return;
429 case "J": {
430 const mode = numbers[0] ?? 0;
431 if (mode === 0) {
432 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);
433 this.lines.length = this.row + 1;
434 } else if (mode === 1) {
435 for (let row = 0; row < this.row; row += 1) this.lines[row] = [];
436 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1);
437 } else if (mode === 3) {
438 if (this.settled !== "") this.dropped = true;
439 this.settled = "";
440 } else {
441 this.lines = [[]];
442 this.row = 0;
443 this.col = 0;
444 }
445 return;
446 }
447 case "s":
448 this.saved = { row: this.row, col: this.col };
449 return;
450 case "u":
451 if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
452 return;
453 default:
454 }
455 }
456
457 escape(sequence: string): void {
458 if (sequence[1] === "[") {
459 this.csi(sequence.slice(2, -1), sequence.at(-1)!);
460 } else if (sequence === `${ESC}7`) {
461 this.saved = { row: this.row, col: this.col };
462 } else if (sequence === `${ESC}8`) {
463 if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
464 } else if (sequence === `${ESC}M`) {
465 this.moveTo(this.row - 1, this.col);
466 }
467 }
468
469 /** Applies `input`; returns the unfinished escape left at its end. */
470 feed(input: string): string {
471 let printable = 0;
472 const flush = (end: number) => {
473 if (end > printable) this.write(input.slice(printable, end));
474 };
475 for (let index = 0; index < input.length; index += 1) {
476 const code = input.charCodeAt(index);
477 if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) {
478 continue;
479 }
480 flush(index);
481 printable = index + 1;
482 if (code === 0x0a) this.newline();
483 else if (code === 0x0d) this.col = 0;
484 else if (code === 0x08) this.col = Math.max(0, this.col - 1);
485 else if (code === 0x1b) {
486 const length = escapeLength(input, index);
487 if (length === -1) {
488 const fragment = input.slice(index);
489 if (fragment.length <= MAX_PENDING_ESCAPE) return fragment;
490 // Retain the introducer and possible ST prefix so long string payloads stay hidden until termination.
491 if (STRING_SEQUENCE_INTRODUCERS.has(fragment[1]!)) {
492 return fragment.slice(0, 2) + (fragment.endsWith(ESC) ? ESC : "");
493 }
494 return "";
495 }
496 this.escape(input.slice(index, index + length));
497 index += length - 1;
498 printable = index + 1;
499 }
500 }
501 flush(input.length);
502 return "";
503 }
504}
505
506/** The active style at `index` of `text` and where a cut there may safely start. */
507function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } {
508 const lineStart = text.lastIndexOf("\n", index - 1) + 1;
509 let prefix = "";
510 let cursor = lineStart;
511 while (cursor < index) {
512 const found = text.indexOf(`${ESC}[`, cursor);
513 if (found === -1 || found >= index) break;
514 const end = text.indexOf("m", found);
515 if (end === -1) break;
516 if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) };
517 prefix = text.slice(found, end + 1);
518 cursor = end + 1;
519 }
520 return { start: index, prefix: prefix === sgr("") ? "" : prefix };
521}
522
523/** Keeps the last `maxChars`, preferring to start on a fresh line. */
524export function terminalOutputTail(
525 text: string,
526 maxChars: number,
527): { readonly text: string; readonly truncated: boolean } {
528 if (text.length <= maxChars) return { text, truncated: false };
529 let start = text.length - maxChars;
530 const newline = text.indexOf("\n", start);
531 // Drop the partial first line unless that would discard most of the tail.
532 if (newline !== -1 && newline - start < maxChars / 4) {
533 return { text: text.slice(newline + 1), truncated: true };
534 }
535 // Cutting inside a line: never split an escape, and keep the colour in force.
536 const style = styleAt(text, start);
537 start = style.start;
538 // Never start on a lone low surrogate.
539 const first = text.charCodeAt(start);
540 if (first >= 0xdc00 && first <= 0xdfff) start += 1;
541 return { text: style.prefix + text.slice(start), truncated: true };
542}
543
544export function appendTerminalOutput(
545 state: TerminalOutputState,
546 chunk: string,
547 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
548): TerminalOutputState {
549 const input = state.pending + chunk;
550 if (input.length === 0) return state;
551 const terminal = new Terminal(state.screen, maxChars);
552 const pending = terminal.feed(input);
553 let truncated = state.truncated;
554 let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0);
555 while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut();
556 // Lines below a cursor that moved up can't scroll out; they keep only their ends.
557 if (windowChars > maxChars) {
558 let budget = maxChars;
559 for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!);
560 for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) {
561 const line = terminal.lines[row]!;
562 const length = lineLength(line);
563 const keep = Math.max(0, Math.min(length, budget));
564 if (keep < length) {
565 truncated = true;
566 terminal.lines[row] = sliceLine(line, length - keep, length);
567 if (terminal.saved !== null && terminal.saved.row === row) {
568 terminal.saved = {
569 ...terminal.saved,
570 col: Math.max(0, terminal.saved.col - (length - keep)),
571 };
572 }
573 }
574 budget -= keep;
575 }
576 }
577 if (terminal.dropped) truncated = true;
578 const settled = terminalOutputTail(terminal.settled, maxChars);
579 const window = terminal.lines.map(serializeLine).join("\n");
580 const tail = terminalOutputTail(settled.text + window, maxChars);
581 return {
582 text: tail.text,
583 truncated: truncated || settled.truncated || tail.truncated,
584 pending,
585 screen: {
586 settled: settled.text,
587 lines: terminal.lines,
588 row: terminal.row,
589 col: terminal.col,
590 pen: terminal.pen,
591 saved: terminal.saved,
592 },
593 };
594}
595
596/** Rebuilds state from empty, including cursor/style/pending escapes, so later raw chunks fold identically. */
597export function terminalOutputResumeText(state: TerminalOutputState): string {
598 const { screen } = state;
599 const lastRow = screen.lines.length - 1;
600 // Moves are relative to the last line, and a viewer only holds the lines in `text`.
601 const shownLines = state.text.split("\n").length;
602 const reachable = Math.min(LIVE_LINES, shownLines) - 1;
603 const up = (row: number) => Math.min(lastRow - row, reachable);
604 const goTo = (row: number, col: number) =>
605 (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`;
606 let suffix = "";
607 if (screen.saved !== null) {
608 suffix += `${goTo(screen.saved.row, screen.saved.col)}${ESC}7`;
609 if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`;
610 }
611 if (
612 screen.saved !== null ||
613 screen.row < lastRow ||
614 screen.col !== lineLength(screen.lines[screen.row]!)
615 ) {
616 suffix += goTo(screen.row, screen.col);
617 }
618 if (screen.pen !== "") suffix += sgr(screen.pen);
619 return state.text + suffix + state.pending;
620}
621
622export function normalizeTerminalOutput(
623 text: string,
624 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
625): { readonly text: string; readonly truncated: boolean } {
626 const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars);
627 return { text: state.text, truncated: state.truncated };
628}
629
630export interface TerminalSpan {
631 readonly text: string;
632 readonly style: TerminalSpanStyle | null;
633}
634
635export interface TerminalSpanStyle {
636 /** CSS colours, already resolved against the palette. */
637 readonly color?: string;
638 readonly backgroundColor?: string;
639 readonly fontWeight?: "600";
640 readonly opacity?: number;
641 readonly fontStyle?: "italic";
642 readonly textDecorationLine?: "underline" | "line-through" | "underline line-through";
643}
644
645export const TERMINAL_PALETTES = {
646 dark: [
647 "#3b4048",
648 "#f47067",
649 "#57ab5a",
650 "#c69026",
651 "#539bf5",
652 "#b083f0",
653 "#39c5cf",
654 "#adbac7",
655 "#768390",
656 "#ff938a",
657 "#6bc46d",
658 "#daaa3f",
659 "#6cb6ff",
660 "#dcbdfb",
661 "#56d4dd",
662 "#cdd9e5",
663 ],
664 light: [
665 "#24292f",
666 "#cf222e",
667 "#116329",
668 "#7d4e00",
669 "#0550ae",
670 "#8250df",
671 "#1b7c83",
672 "#6e7781",
673 "#57606a",
674 "#a40e26",
675 "#1a7f37",
676 "#633c01",
677 "#0969da",
678 "#6639ba",
679 "#3192aa",
680 "#8c959f",
681 ],
682} as const;
683
684function xtermColor(index: number, palette: ReadonlyArray<string>): string {
685 if (index < 16) return palette[index]!;
686 if (index >= 232) {
687 const level = 8 + (index - 232) * 10;
688 return `rgb(${level},${level},${level})`;
689 }
690 const cube = index - 16;
691 const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40);
692 return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`;
693}
694
695function resolveColor(
696 code: string,
697 base: number,
698 palette: ReadonlyArray<string>,
699): string | undefined {
700 const parts = code.split(";").map(Number);
701 const head = parts[0]!;
702 if (head === base + 8) {
703 if (parts[1] === 5) return xtermColor(parts[2]!, palette);
704 return `rgb(${parts[2]},${parts[3]},${parts[4]})`;
705 }
706 if (head >= base && head <= base + 7) return palette[head - base];
707 if (head >= base + 60 && head <= base + 67) return palette[head - base - 52];
708 return undefined;
709}
710
711type Rgb = readonly [number, number, number];
712
713function parseCssColor(color: string): Rgb | undefined {
714 if (color.startsWith("#") && color.length === 7) {
715 return [1, 3, 5].map((offset) =>
716 Number.parseInt(color.slice(offset, offset + 2), 16),
717 ) as unknown as Rgb;
718 }
719 const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color);
720 return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
721}
722
723function luminance([r, g, b]: Rgb): number {
724 const channel = (value: number) => {
725 const scaled = value / 255;
726 return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
727 };
728 return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
729}
730
731function contrastRatio(a: Rgb, b: Rgb): number {
732 const [first, second] = [luminance(a), luminance(b)];
733 return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
734}
735
736function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null {
737 if (pen === "") return null;
738 const attributes = parsePen(pen);
739 let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette);
740 let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette);
741 if (attributes.inverse) {
742 [color, backgroundColor] = [backgroundColor, color ?? palette[7]];
743 }
744 // Badges like "PASS" on green assume a terminal's own palette; keep their text readable.
745 if (backgroundColor !== undefined) {
746 const background = parseCssColor(backgroundColor);
747 const foreground = color === undefined ? undefined : parseCssColor(color);
748 if (
749 background !== undefined &&
750 (foreground === undefined || contrastRatio(foreground, background) < 3)
751 ) {
752 color = luminance(background) > 0.35 ? "#1f2328" : "#ffffff";
753 }
754 }
755 const textDecorationLine = attributes.underline
756 ? attributes.strike
757 ? "underline line-through"
758 : "underline"
759 : attributes.strike
760 ? "line-through"
761 : undefined;
762 return {
763 ...(color === undefined ? {} : { color }),
764 ...(backgroundColor === undefined ? {} : { backgroundColor }),
765 ...(attributes.bold ? { fontWeight: "600" } : {}),
766 ...(attributes.dim ? { opacity: 0.65 } : {}),
767 ...(attributes.italic ? { fontStyle: "italic" } : {}),
768 ...(textDecorationLine === undefined ? {} : { textDecorationLine }),
769 };
770}
771
772/** Caps styled spans at maxSpans, then emits one plain remainder to bound DOM/native nodes. */
773export function terminalOutputSpans(
774 text: string,
775 palette: ReadonlyArray<string>,
776 maxSpans = 2_000,
777): ReadonlyArray<TerminalSpan> {
778 const spans: Array<TerminalSpan> = [];
779 const styles = new Map<string, TerminalSpanStyle | null>();
780 let pen = "";
781 let cursor = 0;
782 const push = (end: number) => {
783 if (end <= cursor) return;
784 let style = styles.get(pen);
785 if (style === undefined) {
786 style = spanStyle(pen, palette);
787 styles.set(pen, style);
788 }
789 spans.push({ text: text.slice(cursor, end), style });
790 };
791 while (cursor < text.length) {
792 const escape = text.indexOf(`${ESC}[`, cursor);
793 if (escape === -1 || spans.length >= maxSpans) break;
794 push(escape);
795 const end = text.indexOf("m", escape);
796 if (end === -1) break;
797 const params = text.slice(escape + 2, end);
798 pen = params === "0" ? "" : params.replace(/^0;/u, "");
799 cursor = end + 1;
800 }
801 if (cursor < text.length) {
802 if (spans.length >= maxSpans) {
803 spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null });
804 } else {
805 push(text.length);
806 }
807 }
808 return spans;
809}
810
811const SGR_PATTERN = new RegExp(`${ESC}\\[[0-9;]*m`, "gu");
812
813export function terminalOutputPlainText(text: string): string {
814 return text.replace(SGR_PATTERN, "");
815}