pal-code 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,973 @@
1
+ /**
2
+ * tty-width — pi-tui-free terminal text-width primitives.
3
+ *
4
+ * Design-system seed: this file is the first building block of a pi-tui-free
5
+ * rendering layer under `packages/cli/src/tui/`, which is the future home of
6
+ * markdown and code-block rendering.
7
+ *
8
+ * Directory rule: no imports from `@earendil-works/pi-tui` anywhere under
9
+ * `packages/cli/src/tui/`.
10
+ *
11
+ * The four exports are drop-in replacements for the pi-tui utilities of the
12
+ * same names: identical signatures and edge-case semantics (ANSI/OSC/APC
13
+ * sequence skipping, East Asian wide characters, emoji, tabs, empty strings,
14
+ * truncation rounding). The algorithms are adapted from
15
+ * @earendil-works/pi-tui's `dist/utils.js` (MIT, © Mario Zechner,
16
+ * https://github.com/earendil-works/pi).
17
+ */
18
+ import {eastAsianWidth} from 'get-east-asian-width';
19
+
20
+ const graphemeSegmenter = new Intl.Segmenter(undefined, {granularity: 'grapheme'});
21
+
22
+ /**
23
+ * Check if a grapheme cluster (after segmentation) could possibly be an RGI
24
+ * emoji. Fast heuristic to avoid running the expensive rgiEmojiRegex test.
25
+ * The tested Unicode blocks are deliberately broad to account for future
26
+ * Unicode additions.
27
+ */
28
+ function couldBeEmoji(segment: string): boolean {
29
+ const cp = segment.codePointAt(0) ?? -1;
30
+ if (cp >= 0x1f000 && cp <= 0x1fbff) return true; // Emoji and Pictograph
31
+ if (cp >= 0x2300 && cp <= 0x23ff) return true; // Misc technical
32
+ if (cp >= 0x2600 && cp <= 0x27bf) return true; // Misc symbols, dingbats
33
+ if (cp >= 0x2b50 && cp <= 0x2b55) return true; // Specific stars/circles
34
+ if (segment.includes('\uFE0F')) return true; // VS16 (emoji presentation selector)
35
+ return segment.length > 2; // Multi-codepoint sequences (ZWJ, skin tones, etc.)
36
+ }
37
+
38
+ // Regexes for character classification (aligned with the string-width library).
39
+ const zeroWidthRegex =
40
+ /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
41
+ const leadingNonPrintingRegex =
42
+ /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
43
+ const nonPrintingCharRegex =
44
+ /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})$/v;
45
+ const markCharRegex = /^\p{Mark}$/v;
46
+ // Marks that terminals allocate cells for when attached to a base character.
47
+ // This includes Unicode spacing marks and non-spacing exceptions in legacy
48
+ // wcwidth tables.
49
+ const terminalSpacingMarkRegex =
50
+ /^(?:[\p{Spacing_Mark}--[\u1734\u302E\u302F]]|[\u065F\u0F7F\u102B\u102C\u1031\u1033-\u1035\u1038\u103A-\u103E])+$/v;
51
+ const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
52
+ // Cache for non-ASCII strings
53
+ const WIDTH_CACHE_SIZE = 512;
54
+ const widthCache = new Map<string, number>();
55
+ const cjkBreakRegex =
56
+ /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u;
57
+
58
+ function isPrintableAscii(str: string): boolean {
59
+ for (let i = 0; i < str.length; i++) {
60
+ const code = str.charCodeAt(i);
61
+ if (code < 0x20 || code > 0x7e) {
62
+ return false;
63
+ }
64
+ }
65
+ return true;
66
+ }
67
+
68
+ /** An OSC 8 hyperlink's params/url/terminator (null terminator => closed link). */
69
+ interface Osc8Hyperlink {
70
+ params: string;
71
+ url: string;
72
+ terminator: string;
73
+ }
74
+
75
+ /**
76
+ * Extract ANSI escape sequences from a string at the given position.
77
+ * Handles CSI (ESC [ ... m/G/K/H/J), OSC (ESC ] ... BEL/ST), and
78
+ * APC (ESC _ ... BEL/ST) sequences.
79
+ */
80
+ function extractAnsiCode(str: string, pos: number): {code: string; length: number} | null {
81
+ if (pos >= str.length || str[pos] !== '\x1b') return null;
82
+ const next = str[pos + 1];
83
+ // CSI sequence: ESC [ ... m/G/K/H/J
84
+ if (next === '[') {
85
+ let j = pos + 2;
86
+ while (j < str.length && !/[mGKHJ]/.test(str[j])) j++;
87
+ if (j < str.length) return {code: str.substring(pos, j + 1), length: j + 1 - pos};
88
+ return null;
89
+ }
90
+ // OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \)
91
+ // Used for hyperlinks (OSC 8), window titles, etc.
92
+ if (next === ']') {
93
+ let j = pos + 2;
94
+ while (j < str.length) {
95
+ if (str[j] === '\x07') return {code: str.substring(pos, j + 1), length: j + 1 - pos};
96
+ if (str[j] === '\x1b' && str[j + 1] === '\\')
97
+ return {code: str.substring(pos, j + 2), length: j + 2 - pos};
98
+ j++;
99
+ }
100
+ return null;
101
+ }
102
+ // APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \)
103
+ // Used for cursor marker and application-specific commands
104
+ if (next === '_') {
105
+ let j = pos + 2;
106
+ while (j < str.length) {
107
+ if (str[j] === '\x07') return {code: str.substring(pos, j + 1), length: j + 1 - pos};
108
+ if (str[j] === '\x1b' && str[j + 1] === '\\')
109
+ return {code: str.substring(pos, j + 2), length: j + 2 - pos};
110
+ j++;
111
+ }
112
+ return null;
113
+ }
114
+ return null;
115
+ }
116
+
117
+ function parseOsc8Hyperlink(ansiCode: string): Osc8Hyperlink | null | undefined {
118
+ if (!ansiCode.startsWith('\x1b]8;')) {
119
+ return undefined;
120
+ }
121
+ const terminator = ansiCode.endsWith('\x07') ? '\x07' : '\x1b\\';
122
+ const body = ansiCode.slice(4, terminator === '\x07' ? -1 : -2);
123
+ const separatorIndex = body.indexOf(';');
124
+ if (separatorIndex === -1) {
125
+ return undefined;
126
+ }
127
+ const params = body.slice(0, separatorIndex);
128
+ const url = body.slice(separatorIndex + 1);
129
+ if (!url) {
130
+ return null;
131
+ }
132
+ return {params, url, terminator};
133
+ }
134
+
135
+ function formatOsc8Hyperlink(hyperlink: Osc8Hyperlink): string {
136
+ return `\x1b]8;${hyperlink.params};${hyperlink.url}${hyperlink.terminator}`;
137
+ }
138
+
139
+ function formatOsc8Close(terminator: string): string {
140
+ return `\x1b]8;;${terminator}`;
141
+ }
142
+
143
+ function getActiveOsc8Close(prefix: string): string {
144
+ if (!prefix.includes('\x1b]8;')) {
145
+ return '';
146
+ }
147
+ let activeHyperlink: Osc8Hyperlink | null = null;
148
+ let i = 0;
149
+ while (i < prefix.length) {
150
+ const ansi = extractAnsiCode(prefix, i);
151
+ if (ansi) {
152
+ const hyperlink = parseOsc8Hyperlink(ansi.code);
153
+ if (hyperlink !== undefined) {
154
+ activeHyperlink = hyperlink;
155
+ }
156
+ i += ansi.length;
157
+ } else {
158
+ i++;
159
+ }
160
+ }
161
+ return activeHyperlink ? formatOsc8Close(activeHyperlink.terminator) : '';
162
+ }
163
+
164
+ function truncateFragmentToWidth(text: string, maxWidth: number): {text: string; width: number} {
165
+ if (maxWidth <= 0 || text.length === 0) {
166
+ return {text: '', width: 0};
167
+ }
168
+ if (isPrintableAscii(text)) {
169
+ const clipped = text.slice(0, maxWidth);
170
+ return {text: clipped, width: clipped.length};
171
+ }
172
+ const hasAnsi = text.includes('\x1b');
173
+ const hasTabs = text.includes('\t');
174
+ if (!hasAnsi && !hasTabs) {
175
+ let result = '';
176
+ let width = 0;
177
+ for (const {segment} of graphemeSegmenter.segment(text)) {
178
+ const w = graphemeWidth(segment);
179
+ if (width + w > maxWidth) {
180
+ break;
181
+ }
182
+ result += segment;
183
+ width += w;
184
+ }
185
+ return {text: result, width};
186
+ }
187
+ let result = '';
188
+ let width = 0;
189
+ let i = 0;
190
+ let pendingAnsi = '';
191
+ while (i < text.length) {
192
+ const ansi = extractAnsiCode(text, i);
193
+ if (ansi) {
194
+ pendingAnsi += ansi.code;
195
+ i += ansi.length;
196
+ continue;
197
+ }
198
+ if (text[i] === '\t') {
199
+ if (width + 3 > maxWidth) {
200
+ break;
201
+ }
202
+ if (pendingAnsi) {
203
+ result += pendingAnsi;
204
+ pendingAnsi = '';
205
+ }
206
+ result += '\t';
207
+ width += 3;
208
+ i++;
209
+ continue;
210
+ }
211
+ let end = i;
212
+ while (end < text.length && text[end] !== '\t') {
213
+ const nextAnsi = extractAnsiCode(text, end);
214
+ if (nextAnsi) {
215
+ break;
216
+ }
217
+ end++;
218
+ }
219
+ for (const {segment} of graphemeSegmenter.segment(text.slice(i, end))) {
220
+ const w = graphemeWidth(segment);
221
+ if (width + w > maxWidth) {
222
+ return {text: result, width};
223
+ }
224
+ if (pendingAnsi) {
225
+ result += pendingAnsi;
226
+ pendingAnsi = '';
227
+ }
228
+ result += segment;
229
+ width += w;
230
+ }
231
+ i = end;
232
+ }
233
+ return {text: result, width};
234
+ }
235
+
236
+ function finalizeTruncatedResult(
237
+ prefix: string,
238
+ prefixWidth: number,
239
+ ellipsis: string,
240
+ ellipsisWidth: number,
241
+ maxWidth: number,
242
+ pad: boolean,
243
+ ): string {
244
+ const reset = '\x1b[0m';
245
+ const hyperlinkClose = getActiveOsc8Close(prefix);
246
+ const totalWidth = prefixWidth + ellipsisWidth;
247
+ let result: string;
248
+ if (ellipsis.length > 0) {
249
+ result = `${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`;
250
+ } else {
251
+ result = `${prefix}${hyperlinkClose}${reset}`;
252
+ }
253
+ return pad ? result + ' '.repeat(Math.max(0, maxWidth - totalWidth)) : result;
254
+ }
255
+
256
+ /**
257
+ * Calculate the terminal width of a single grapheme cluster.
258
+ * Based on code from the string-width library, but includes a possible-emoji
259
+ * check to avoid running the RGI_Emoji regex unnecessarily.
260
+ */
261
+ function graphemeWidth(segment: string): number {
262
+ if (segment === '\t') {
263
+ return 3;
264
+ }
265
+ // Some marks occupy cells even without a base character.
266
+ if (terminalSpacingMarkRegex.test(segment)) {
267
+ return [...segment].length;
268
+ }
269
+ // Zero-width clusters
270
+ if (zeroWidthRegex.test(segment)) {
271
+ return 0;
272
+ }
273
+ // Emoji check with pre-filter
274
+ if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {
275
+ return 2;
276
+ }
277
+ // Get base visible codepoint
278
+ const base = segment.replace(leadingNonPrintingRegex, '');
279
+ const cp = base.codePointAt(0);
280
+ if (cp === undefined) {
281
+ return 0;
282
+ }
283
+ // Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as
284
+ // full-width emoji in terminals, even when isolated during streaming.
285
+ // Keep width conservative (2) to avoid terminal auto-wrap drift artifacts.
286
+ if (cp >= 0x1f1e6 && cp <= 0x1f1ff) {
287
+ return 2;
288
+ }
289
+ let width: number = eastAsianWidth(cp);
290
+ // Intl.Segmenter can group multiple terminal-spacing code points into one
291
+ // grapheme. Count trailing visible code points that terminals may allocate
292
+ // cells for: Indic consonants after marks, halfwidth/fullwidth forms, and
293
+ // Thai/Lao AM vowels.
294
+ let followsMark = false;
295
+ const chars = [...base];
296
+ for (const char of chars.slice(1)) {
297
+ if (terminalSpacingMarkRegex.test(char)) {
298
+ width += 1;
299
+ followsMark = false;
300
+ } else if (markCharRegex.test(char)) {
301
+ followsMark = true;
302
+ } else if (!nonPrintingCharRegex.test(char)) {
303
+ const c = char.codePointAt(0) ?? -1;
304
+ if (followsMark || (c >= 0xff00 && c <= 0xffef)) {
305
+ // halfwidth + fullwidth forms
306
+ width += eastAsianWidth(c);
307
+ } else if (c === 0x0e33 || c === 0x0eb3) {
308
+ width += 1;
309
+ }
310
+ followsMark = false;
311
+ }
312
+ }
313
+ return width;
314
+ }
315
+
316
+ /** Calculate the visible width of a string in terminal columns. */
317
+ export function visibleWidth(str: string): number {
318
+ if (str.length === 0) {
319
+ return 0;
320
+ }
321
+ // Fast path: pure ASCII printable
322
+ if (isPrintableAscii(str)) {
323
+ return str.length;
324
+ }
325
+ // Check cache
326
+ const cached = widthCache.get(str);
327
+ if (cached !== undefined) {
328
+ return cached;
329
+ }
330
+ // Normalize: tabs to 3 spaces, strip ANSI escape codes
331
+ let clean = str;
332
+ if (str.includes('\t')) {
333
+ clean = clean.replace(/\t/g, ' ');
334
+ }
335
+ if (clean.includes('\x1b')) {
336
+ // Strip supported ANSI/OSC/APC escape sequences in one pass.
337
+ // This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,
338
+ // and APC sequences like CURSOR_MARKER.
339
+ let stripped = '';
340
+ let i = 0;
341
+ while (i < clean.length) {
342
+ const ansi = extractAnsiCode(clean, i);
343
+ if (ansi) {
344
+ i += ansi.length;
345
+ continue;
346
+ }
347
+ stripped += clean[i];
348
+ i++;
349
+ }
350
+ clean = stripped;
351
+ }
352
+ // Calculate width
353
+ let width = 0;
354
+ for (const {segment} of graphemeSegmenter.segment(clean)) {
355
+ width += graphemeWidth(segment);
356
+ }
357
+ // Cache result
358
+ if (widthCache.size >= WIDTH_CACHE_SIZE) {
359
+ const firstKey = widthCache.keys().next().value;
360
+ if (firstKey !== undefined) {
361
+ widthCache.delete(firstKey);
362
+ }
363
+ }
364
+ widthCache.set(str, width);
365
+ return width;
366
+ }
367
+
368
+ /** Remove ANSI, OSC, and APC control sequences while preserving visible text. */
369
+ export function stripTerminalSequences(str: string): string {
370
+ if (!str.includes('\x1b')) return str;
371
+ let result = '';
372
+ let i = 0;
373
+ while (i < str.length) {
374
+ const ansi = extractAnsiCode(str, i);
375
+ if (ansi) {
376
+ i += ansi.length;
377
+ continue;
378
+ }
379
+ result += str[i];
380
+ i++;
381
+ }
382
+ return result;
383
+ }
384
+
385
+ /**
386
+ * Track active ANSI SGR codes to preserve styling across line breaks.
387
+ */
388
+ class AnsiCodeTracker {
389
+ bold = false;
390
+ dim = false;
391
+ italic = false;
392
+ underline = false;
393
+ blink = false;
394
+ inverse = false;
395
+ hidden = false;
396
+ strikethrough = false;
397
+ /** Full SGR foreground code like "31" or "38;5;240". */
398
+ fgColor: string | null = null;
399
+ /** Full SGR background code like "41" or "48;5;240". */
400
+ bgColor: string | null = null;
401
+ activeHyperlink: Osc8Hyperlink | null = null;
402
+
403
+ process(ansiCode: string): void {
404
+ // OSC 8 hyperlink: \x1b]8;;<url>\x1b\\ (open) or \x1b]8;;\x1b\\ (close).
405
+ // Preserve the original terminator because some terminals only make
406
+ // BEL-terminated links clickable. OAuth login URLs use BEL, so reopening
407
+ // wrapped lines with ST made only the first physical line clickable there.
408
+ const hyperlink = parseOsc8Hyperlink(ansiCode);
409
+ if (hyperlink !== undefined) {
410
+ this.activeHyperlink = hyperlink;
411
+ return;
412
+ }
413
+ if (!ansiCode.endsWith('m')) return;
414
+ // Extract the parameters between \x1b[ and m (digits and semicolons only)
415
+ if (!ansiCode.startsWith('\x1b[')) return;
416
+ const params = ansiCode.slice(2, -1);
417
+ if (!/^[\d;]*$/.test(params)) return;
418
+ if (params === '' || params === '0') {
419
+ // Full reset
420
+ this.reset();
421
+ return;
422
+ }
423
+ // Parse parameters (can be semicolon-separated)
424
+ const parts = params.split(';');
425
+ let i = 0;
426
+ while (i < parts.length) {
427
+ const code = Number.parseInt(parts[i], 10);
428
+ // Handle 256-color and RGB codes which consume multiple parameters
429
+ if (code === 38 || code === 48) {
430
+ if (parts[i + 1] === '5' && parts[i + 2] !== undefined) {
431
+ // 256 color: 38;5;N or 48;5;N
432
+ const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;
433
+ if (code === 38) {
434
+ this.fgColor = colorCode;
435
+ } else {
436
+ this.bgColor = colorCode;
437
+ }
438
+ i += 3;
439
+ continue;
440
+ } else if (parts[i + 1] === '2' && parts[i + 4] !== undefined) {
441
+ // RGB color: 38;2;R;G;B or 48;2;R;G;B
442
+ const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;
443
+ if (code === 38) {
444
+ this.fgColor = colorCode;
445
+ } else {
446
+ this.bgColor = colorCode;
447
+ }
448
+ i += 5;
449
+ continue;
450
+ }
451
+ }
452
+ // Standard SGR codes
453
+ switch (code) {
454
+ case 0:
455
+ this.reset();
456
+ break;
457
+ case 1:
458
+ this.bold = true;
459
+ break;
460
+ case 2:
461
+ this.dim = true;
462
+ break;
463
+ case 3:
464
+ this.italic = true;
465
+ break;
466
+ case 4:
467
+ this.underline = true;
468
+ break;
469
+ case 5:
470
+ this.blink = true;
471
+ break;
472
+ case 7:
473
+ this.inverse = true;
474
+ break;
475
+ case 8:
476
+ this.hidden = true;
477
+ break;
478
+ case 9:
479
+ this.strikethrough = true;
480
+ break;
481
+ case 21:
482
+ this.bold = false; // Some terminals
483
+ break;
484
+ case 22:
485
+ this.bold = false;
486
+ this.dim = false;
487
+ break;
488
+ case 23:
489
+ this.italic = false;
490
+ break;
491
+ case 24:
492
+ this.underline = false;
493
+ break;
494
+ case 25:
495
+ this.blink = false;
496
+ break;
497
+ case 27:
498
+ this.inverse = false;
499
+ break;
500
+ case 28:
501
+ this.hidden = false;
502
+ break;
503
+ case 29:
504
+ this.strikethrough = false;
505
+ break;
506
+ case 39:
507
+ this.fgColor = null; // Default fg
508
+ break;
509
+ case 49:
510
+ this.bgColor = null; // Default bg
511
+ break;
512
+ default:
513
+ if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
514
+ // Standard foreground colors 30-37, 90-97
515
+ this.fgColor = String(code);
516
+ } else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
517
+ // Standard background colors 40-47, 100-107
518
+ this.bgColor = String(code);
519
+ }
520
+ break;
521
+ }
522
+ i++;
523
+ }
524
+ }
525
+
526
+ reset(): void {
527
+ this.bold = false;
528
+ this.dim = false;
529
+ this.italic = false;
530
+ this.underline = false;
531
+ this.blink = false;
532
+ this.inverse = false;
533
+ this.hidden = false;
534
+ this.strikethrough = false;
535
+ this.fgColor = null;
536
+ this.bgColor = null;
537
+ // SGR reset does not affect OSC 8 hyperlink state
538
+ }
539
+
540
+ getActiveCodes(): string {
541
+ const codes: string[] = [];
542
+ if (this.bold) codes.push('1');
543
+ if (this.dim) codes.push('2');
544
+ if (this.italic) codes.push('3');
545
+ if (this.underline) codes.push('4');
546
+ if (this.blink) codes.push('5');
547
+ if (this.inverse) codes.push('7');
548
+ if (this.hidden) codes.push('8');
549
+ if (this.strikethrough) codes.push('9');
550
+ if (this.fgColor) codes.push(this.fgColor);
551
+ if (this.bgColor) codes.push(this.bgColor);
552
+ let result = codes.length > 0 ? `\x1b[${codes.join(';')}m` : '';
553
+ if (this.activeHyperlink) {
554
+ result += formatOsc8Hyperlink(this.activeHyperlink);
555
+ }
556
+ return result;
557
+ }
558
+
559
+ /**
560
+ * Get reset codes for attributes that need to be turned off at line end.
561
+ * Underline must be closed to prevent bleeding into padding.
562
+ * Active OSC 8 hyperlinks must be closed and re-opened on the next line.
563
+ * Returns empty string if no attributes need closing.
564
+ */
565
+ getLineEndReset(): string {
566
+ let result = '';
567
+ if (this.underline) {
568
+ result += '\x1b[24m'; // Underline off only
569
+ }
570
+ if (this.activeHyperlink) {
571
+ // Re-opened at line start via getActiveCodes()
572
+ result += formatOsc8Close(this.activeHyperlink.terminator);
573
+ }
574
+ return result;
575
+ }
576
+ }
577
+
578
+ function updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void {
579
+ let i = 0;
580
+ while (i < text.length) {
581
+ const ansiResult = extractAnsiCode(text, i);
582
+ if (ansiResult) {
583
+ tracker.process(ansiResult.code);
584
+ i += ansiResult.length;
585
+ } else {
586
+ i++;
587
+ }
588
+ }
589
+ }
590
+
591
+ /**
592
+ * Split text into words while keeping ANSI codes attached.
593
+ * CJK characters become their own tokens so they can break anywhere.
594
+ */
595
+ function splitIntoTokensWithAnsi(text: string): string[] {
596
+ const tokens: string[] = [];
597
+ let current = '';
598
+ let pendingAnsi = ''; // ANSI codes waiting to be attached to next visible content
599
+ let currentKind: 'space' | 'word' | null = null;
600
+ let i = 0;
601
+ const flushCurrent = (): void => {
602
+ if (!current) {
603
+ return;
604
+ }
605
+ tokens.push(current);
606
+ current = '';
607
+ currentKind = null;
608
+ };
609
+ while (i < text.length) {
610
+ const ansiResult = extractAnsiCode(text, i);
611
+ if (ansiResult) {
612
+ // Hold ANSI codes separately - they'll be attached to the next visible char
613
+ pendingAnsi += ansiResult.code;
614
+ i += ansiResult.length;
615
+ continue;
616
+ }
617
+ let end = i;
618
+ while (end < text.length && !extractAnsiCode(text, end)) {
619
+ end++;
620
+ }
621
+ for (const {segment} of graphemeSegmenter.segment(text.slice(i, end))) {
622
+ const segmentIsSpace = segment === ' ';
623
+ if (!segmentIsSpace && cjkBreakRegex.test(segment)) {
624
+ flushCurrent();
625
+ const token = pendingAnsi + segment;
626
+ pendingAnsi = '';
627
+ tokens.push(token);
628
+ continue;
629
+ }
630
+ const segmentKind = segmentIsSpace ? 'space' : 'word';
631
+ if (current && currentKind !== segmentKind) {
632
+ flushCurrent();
633
+ }
634
+ // Attach any pending ANSI codes to this visible character
635
+ if (pendingAnsi) {
636
+ current += pendingAnsi;
637
+ pendingAnsi = '';
638
+ }
639
+ currentKind = segmentKind;
640
+ current += segment;
641
+ }
642
+ i = end;
643
+ }
644
+ // Handle any remaining pending ANSI codes (attach to last token)
645
+ if (pendingAnsi) {
646
+ if (current) {
647
+ current += pendingAnsi;
648
+ } else if (tokens.length > 0) {
649
+ tokens[tokens.length - 1] += pendingAnsi;
650
+ } else {
651
+ current = pendingAnsi;
652
+ }
653
+ }
654
+ if (current) {
655
+ tokens.push(current);
656
+ }
657
+ return tokens;
658
+ }
659
+
660
+ /**
661
+ * Wrap text with ANSI codes preserved.
662
+ *
663
+ * ONLY does word wrapping - NO padding, NO background colors.
664
+ * Returns lines where each line is <= width visible chars.
665
+ * Active ANSI codes are preserved across line breaks.
666
+ *
667
+ * @param text - Text to wrap (may contain ANSI codes and newlines)
668
+ * @param width - Maximum visible width per line
669
+ * @returns Array of wrapped lines (NOT padded to width)
670
+ */
671
+ export function wrapTextWithAnsi(text: string, width: number): string[] {
672
+ if (!text) {
673
+ return [''];
674
+ }
675
+ // Handle newlines by processing each line separately
676
+ // Track ANSI state across lines so styles carry over after literal newlines
677
+ const inputLines = text.split(/\r\n|\r|\n/);
678
+ const result: string[] = [];
679
+ const tracker = new AnsiCodeTracker();
680
+ for (const inputLine of inputLines) {
681
+ // Prepend active ANSI codes from previous lines (except for first line)
682
+ const prefix = result.length > 0 ? tracker.getActiveCodes() : '';
683
+ const wrappedLines = wrapSingleLine(prefix + inputLine, width);
684
+ for (const wrappedLine of wrappedLines) {
685
+ result.push(wrappedLine);
686
+ }
687
+ // Update tracker with codes from this line for next iteration
688
+ updateTrackerFromText(inputLine, tracker);
689
+ }
690
+ return result.length > 0 ? result : [''];
691
+ }
692
+
693
+ function wrapSingleLine(line: string, width: number): string[] {
694
+ if (!line) {
695
+ return [''];
696
+ }
697
+ const visibleLength = visibleWidth(line);
698
+ if (visibleLength <= width) {
699
+ return [line];
700
+ }
701
+ const wrapped: string[] = [];
702
+ const tracker = new AnsiCodeTracker();
703
+ const tokens = splitIntoTokensWithAnsi(line);
704
+ let currentLine = '';
705
+ let currentVisibleLength = 0;
706
+ for (const token of tokens) {
707
+ const tokenVisibleLength = visibleWidth(token);
708
+ const isWhitespace = token.trim() === '';
709
+ // Token itself is too long - break it character by character
710
+ if (tokenVisibleLength > width && !isWhitespace) {
711
+ if (currentLine) {
712
+ // Add specific reset for underline only (preserves background)
713
+ const lineEndReset = tracker.getLineEndReset();
714
+ if (lineEndReset) {
715
+ currentLine += lineEndReset;
716
+ }
717
+ wrapped.push(currentLine);
718
+ currentLine = '';
719
+ currentVisibleLength = 0;
720
+ }
721
+ // Break long token - breakLongWord handles its own resets
722
+ const broken = breakLongWord(token, width, tracker);
723
+ for (let i = 0; i < broken.length - 1; i++) {
724
+ wrapped.push(broken[i]);
725
+ }
726
+ currentLine = broken[broken.length - 1];
727
+ currentVisibleLength = visibleWidth(currentLine);
728
+ continue;
729
+ }
730
+ // Check if adding this token would exceed width
731
+ const totalNeeded = currentVisibleLength + tokenVisibleLength;
732
+ if (totalNeeded > width && currentVisibleLength > 0) {
733
+ // Trim trailing whitespace, then add underline reset (not full reset,
734
+ // to preserve background)
735
+ let lineToWrap = currentLine.trimEnd();
736
+ const lineEndReset = tracker.getLineEndReset();
737
+ if (lineEndReset) {
738
+ lineToWrap += lineEndReset;
739
+ }
740
+ wrapped.push(lineToWrap);
741
+ if (isWhitespace) {
742
+ // Don't start new line with whitespace
743
+ currentLine = tracker.getActiveCodes();
744
+ currentVisibleLength = 0;
745
+ } else {
746
+ currentLine = tracker.getActiveCodes() + token;
747
+ currentVisibleLength = tokenVisibleLength;
748
+ }
749
+ } else {
750
+ // Add to current line
751
+ currentLine += token;
752
+ currentVisibleLength += tokenVisibleLength;
753
+ }
754
+ updateTrackerFromText(token, tracker);
755
+ }
756
+ if (currentLine) {
757
+ // No reset at end of final line - let caller handle it
758
+ wrapped.push(currentLine);
759
+ }
760
+ // Trailing whitespace can cause lines to exceed the requested width
761
+ return wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [''];
762
+ }
763
+
764
+ function breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] {
765
+ const lines: string[] = [];
766
+ let currentLine = tracker.getActiveCodes();
767
+ let currentWidth = 0;
768
+ // First, separate ANSI codes from visible content
769
+ // We need to handle ANSI codes specially since they're not graphemes
770
+ let i = 0;
771
+ const segments: Array<{type: 'ansi' | 'grapheme'; value: string}> = [];
772
+ while (i < word.length) {
773
+ const ansiResult = extractAnsiCode(word, i);
774
+ if (ansiResult) {
775
+ segments.push({type: 'ansi', value: ansiResult.code});
776
+ i += ansiResult.length;
777
+ } else {
778
+ // Find the next ANSI code or end of string
779
+ let end = i;
780
+ while (end < word.length) {
781
+ const nextAnsi = extractAnsiCode(word, end);
782
+ if (nextAnsi) break;
783
+ end++;
784
+ }
785
+ // Segment this non-ANSI portion into graphemes
786
+ const textPortion = word.slice(i, end);
787
+ for (const seg of graphemeSegmenter.segment(textPortion)) {
788
+ segments.push({type: 'grapheme', value: seg.segment});
789
+ }
790
+ i = end;
791
+ }
792
+ }
793
+ // Now process segments
794
+ for (const seg of segments) {
795
+ if (seg.type === 'ansi') {
796
+ currentLine += seg.value;
797
+ tracker.process(seg.value);
798
+ continue;
799
+ }
800
+ const grapheme = seg.value;
801
+ // Skip empty graphemes to avoid issues with string-width calculation
802
+ if (!grapheme) continue;
803
+ const glyphWidth = visibleWidth(grapheme);
804
+ if (currentWidth + glyphWidth > width) {
805
+ // Add specific reset for underline only (preserves background)
806
+ const lineEndReset = tracker.getLineEndReset();
807
+ if (lineEndReset) {
808
+ currentLine += lineEndReset;
809
+ }
810
+ lines.push(currentLine);
811
+ currentLine = tracker.getActiveCodes();
812
+ currentWidth = 0;
813
+ }
814
+ currentLine += grapheme;
815
+ currentWidth += glyphWidth;
816
+ }
817
+ if (currentLine) {
818
+ // No reset at end of final segment - caller handles continuation
819
+ lines.push(currentLine);
820
+ }
821
+ return lines.length > 0 ? lines : [''];
822
+ }
823
+
824
+ /**
825
+ * Truncate text to fit within a maximum visible width, adding ellipsis if needed.
826
+ * Optionally pad with spaces to reach exactly maxWidth.
827
+ * Properly handles ANSI escape codes (they don't count toward width).
828
+ *
829
+ * @param text - Text to truncate (may contain ANSI codes)
830
+ * @param maxWidth - Maximum visible width
831
+ * @param ellipsis - Ellipsis string to append when truncating (default: "...")
832
+ * @param pad - If true, pad result with spaces to exactly maxWidth (default: false)
833
+ * @returns Truncated text, optionally padded to exactly maxWidth
834
+ */
835
+ export function truncateToWidth(
836
+ text: string,
837
+ maxWidth: number,
838
+ ellipsis = '...',
839
+ pad = false,
840
+ ): string {
841
+ if (maxWidth <= 0) {
842
+ return '';
843
+ }
844
+ if (text.length === 0) {
845
+ return pad ? ' '.repeat(maxWidth) : '';
846
+ }
847
+ const ellipsisWidth = visibleWidth(ellipsis);
848
+ if (ellipsisWidth >= maxWidth) {
849
+ const textWidth = visibleWidth(text);
850
+ if (textWidth <= maxWidth) {
851
+ return pad ? text + ' '.repeat(maxWidth - textWidth) : text;
852
+ }
853
+ const clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);
854
+ if (clippedEllipsis.width === 0) {
855
+ return pad ? ' '.repeat(maxWidth) : '';
856
+ }
857
+ return finalizeTruncatedResult(
858
+ '',
859
+ 0,
860
+ clippedEllipsis.text,
861
+ clippedEllipsis.width,
862
+ maxWidth,
863
+ pad,
864
+ );
865
+ }
866
+ if (isPrintableAscii(text)) {
867
+ if (text.length <= maxWidth) {
868
+ return pad ? text + ' '.repeat(maxWidth - text.length) : text;
869
+ }
870
+ const targetWidth = maxWidth - ellipsisWidth;
871
+ return finalizeTruncatedResult(
872
+ text.slice(0, targetWidth),
873
+ targetWidth,
874
+ ellipsis,
875
+ ellipsisWidth,
876
+ maxWidth,
877
+ pad,
878
+ );
879
+ }
880
+ const targetWidth = maxWidth - ellipsisWidth;
881
+ let result = '';
882
+ let pendingAnsi = '';
883
+ let visibleSoFar = 0;
884
+ let keptWidth = 0;
885
+ let keepContiguousPrefix = true;
886
+ let overflowed = false;
887
+ let exhaustedInput = false;
888
+ const hasAnsi = text.includes('\x1b');
889
+ const hasTabs = text.includes('\t');
890
+ if (!hasAnsi && !hasTabs) {
891
+ for (const {segment} of graphemeSegmenter.segment(text)) {
892
+ const width = graphemeWidth(segment);
893
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
894
+ result += segment;
895
+ keptWidth += width;
896
+ } else {
897
+ keepContiguousPrefix = false;
898
+ }
899
+ visibleSoFar += width;
900
+ if (visibleSoFar > maxWidth) {
901
+ overflowed = true;
902
+ break;
903
+ }
904
+ }
905
+ exhaustedInput = !overflowed;
906
+ } else {
907
+ let i = 0;
908
+ while (i < text.length) {
909
+ const ansi = extractAnsiCode(text, i);
910
+ if (ansi) {
911
+ pendingAnsi += ansi.code;
912
+ i += ansi.length;
913
+ continue;
914
+ }
915
+ if (text[i] === '\t') {
916
+ if (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {
917
+ if (pendingAnsi) {
918
+ result += pendingAnsi;
919
+ pendingAnsi = '';
920
+ }
921
+ result += '\t';
922
+ keptWidth += 3;
923
+ } else {
924
+ keepContiguousPrefix = false;
925
+ pendingAnsi = '';
926
+ }
927
+ visibleSoFar += 3;
928
+ if (visibleSoFar > maxWidth) {
929
+ overflowed = true;
930
+ break;
931
+ }
932
+ i++;
933
+ continue;
934
+ }
935
+ let end = i;
936
+ while (end < text.length && text[end] !== '\t') {
937
+ const nextAnsi = extractAnsiCode(text, end);
938
+ if (nextAnsi) {
939
+ break;
940
+ }
941
+ end++;
942
+ }
943
+ for (const {segment} of graphemeSegmenter.segment(text.slice(i, end))) {
944
+ const width = graphemeWidth(segment);
945
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
946
+ if (pendingAnsi) {
947
+ result += pendingAnsi;
948
+ pendingAnsi = '';
949
+ }
950
+ result += segment;
951
+ keptWidth += width;
952
+ } else {
953
+ keepContiguousPrefix = false;
954
+ pendingAnsi = '';
955
+ }
956
+ visibleSoFar += width;
957
+ if (visibleSoFar > maxWidth) {
958
+ overflowed = true;
959
+ break;
960
+ }
961
+ }
962
+ if (overflowed) {
963
+ break;
964
+ }
965
+ i = end;
966
+ }
967
+ exhaustedInput = i >= text.length;
968
+ }
969
+ if (!overflowed && exhaustedInput) {
970
+ return pad ? text + ' '.repeat(Math.max(0, maxWidth - visibleSoFar)) : text;
971
+ }
972
+ return finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);
973
+ }