inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
//! Port of [`wrap-ansi@10`](https://github.com/chalk/wrap-ansi) to Rust.
//!
//! Word-wraps a string to a given column width while keeping ANSI SGR styling
//! and OSC 8 hyperlinks intact across line breaks: styles are closed at the end
//! of each visual line and re-opened at the start of the next so that no line
//! "leaks" styling and every line renders independently.
//!
//! This is a faithful, line-by-line port of the upstream `index.js`. Width
//! measurement is delegated to the [`string-width@8`](crate::text::string_width)
//! port so the two crates agree byte-for-byte on visible width (ANSI-stripping,
//! grapheme-aware, CJK/emoji width). Grapheme segmentation uses
//! [`unicode-segmentation`]; input is NFC-normalised via
//! [`unicode-normalization`] to match JS `String#normalize()`.
//!
//! # Known divergences from JS
//!
//! - `columns == 0`: JS produces NaN-driven (effectively garbage) output and
//!   never panics. This port clamps `columns` to a minimum of 1 at the public
//!   entry point — the soft path would otherwise behave like `columns == 1`
//!   anyway, and the hard-wrap break math divides by `columns`. The clamp is
//!   the only intentional behavioural divergence and is outside the test
//!   matrix (JS's `columns == 0` output is not worth matching).

use std::sync::LazyLock;

use regex::Regex;
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;

use crate::text::string_width::string_width;

const ANSI_ESCAPE: char = '\u{1B}';
const ANSI_ESCAPE_CSI: char = '\u{9B}';
/// `]8;;` — the OSC 8 hyperlink introducer suffix (after the ESC/`]`).
const ANSI_ESCAPE_LINK: &str = "]8;;";

const ANSI_SGR_RESET: u32 = 0;
const ANSI_SGR_RESET_FOREGROUND: u32 = 39;
const ANSI_SGR_RESET_BACKGROUND: u32 = 49;
const ANSI_SGR_RESET_UNDERLINE_COLOR: u32 = 59;
const ANSI_SGR_FOREGROUND_EXTENDED: u32 = 38;
const ANSI_SGR_BACKGROUND_EXTENDED: u32 = 48;
const ANSI_SGR_UNDERLINE_COLOR_EXTENDED: u32 = 58;
const ANSI_SGR_COLOR_MODE_256: u32 = 5;
const ANSI_SGR_COLOR_MODE_RGB: u32 = 2;

const TAB_SIZE: usize = 8;

/// `^\x1B(?:\[(?<sgr>[0-9;]*)m|\]8;;(?<uri>[^\x07\x1B]*)(?:\x07|\x1B\\))`
///
/// Matches a leading SGR sequence (`ESC [ … m`) or an OSC 8 hyperlink
/// introducer (`ESC ] 8 ; ; uri BEL|ST`) at the start of a string. The literal
/// `ANSI_ESCAPE_LINK` introducer is `]8;;` (two semicolons: the empty params).
static ANSI_ESCAPE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\x1B(?:\[(?P<sgr>[0-9;]*)m|\]8;;(?P<uri>[^\x07\x1B]*)(?:\x07|\x1B\\))")
        .expect("ANSI_ESCAPE_REGEX is valid")
});

/// `^\x9B(?<sgr>[0-9;]*)m` — a C1 CSI SGR sequence (single-byte CSI opener).
static ANSI_ESCAPE_CSI_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\x{9B}(?P<sgr>[0-9;]*)m").expect("ANSI_ESCAPE_CSI_REGEX is valid")
});

/// Options controlling how [`wrap_ansi_with`] wraps text.
///
/// Mirrors the upstream `wrap-ansi` options object. Defaults match JS: `hard`
/// off, `word_wrap` on, `trim` on.
#[derive(Debug, Clone, Copy)]
pub struct WrapOptions {
    /// `hard` (default `false`): when `true`, a row is never allowed to exceed
    /// `columns` — long words are split mid-word. When `false` ("soft"), a long
    /// word is allowed to overflow past `columns` rather than being broken.
    pub hard: bool,
    /// `word_wrap` (default `true`): when `false`, words are only broken when a
    /// row is already full (no word-boundary wrapping).
    pub word_wrap: bool,
    /// `trim` (default `true`): trim whitespace at wrap points.
    pub trim: bool,
}

impl Default for WrapOptions {
    fn default() -> Self {
        Self {
            hard: false,
            word_wrap: true,
            trim: true,
        }
    }
}

/// Word-wraps `input` to `columns` columns using the default options
/// (`hard = false`, `word_wrap = true`, `trim = true`).
///
/// # Examples
///
/// ```
/// use inkferro_core::text::wrap_ansi::wrap_ansi;
///
/// assert_eq!(wrap_ansi("hello world foo bar", 10), "hello\nworld foo\nbar");
/// ```
pub fn wrap_ansi(input: &str, columns: usize) -> String {
    wrap_ansi_with(input, columns, WrapOptions::default())
}

/// Word-wraps `input` to `columns` columns using the given [`WrapOptions`].
///
/// The input is NFC-normalised, `\r\n` is converted to `\n`, and each line is
/// wrapped independently, mirroring upstream `wrap-ansi`.
///
/// `columns` is clamped to a minimum of 1: JS produces NaN-driven garbage for
/// `columns == 0` (not worth matching), and the hard-wrap break math divides
/// by `columns`. A terminal resized to 0 columns must not crash the renderer.
pub fn wrap_ansi_with(input: &str, columns: usize, opts: WrapOptions) -> String {
    let columns = columns.max(1);
    // String(string).normalize().replaceAll('\r\n', '\n').split('\n')
    //
    // Allocation fast paths (byte-identical output): `is_nfc_quick == Yes`
    // guarantees `input.nfc()` is the identity, so the normalize copy is
    // skipped; `replace` is skipped when no `\r\n` is present. `Maybe`/`No`
    // take the full normalize, exactly as before.
    let normalized: std::borrow::Cow<'_, str> =
        match unicode_normalization::is_nfc_quick(input.chars()) {
            unicode_normalization::IsNormalized::Yes => std::borrow::Cow::Borrowed(input),
            _ => std::borrow::Cow::Owned(input.nfc().collect()),
        };
    let normalized: std::borrow::Cow<'_, str> = if normalized.contains("\r\n") {
        std::borrow::Cow::Owned(normalized.replace("\r\n", "\n"))
    } else {
        normalized
    };

    normalized
        .split('\n')
        .map(|line| exec(&expand_tabs(line), columns, opts))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Which styles overwrite each other: a second foreground colour replaces the
/// first, but distinct modifiers coexist. JS models this with strings
/// (`'foreground'`, `'modifier-1'`, …); an enum gives the same identity
/// semantics without a per-token `format!` allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Family {
    Foreground,
    Background,
    UnderlineColor,
    Modifier(u32),
}

/// An active style family carried across line breaks.
///
/// `family` distinguishes which styles overwrite each other. `open` is the SGR
/// parameter string to re-open the style; `close` is the numeric SGR code that
/// closes it.
#[derive(Debug, Clone)]
struct ActiveStyle {
    family: Family,
    open: String,
    close: u32,
}

/// `expandTabs(line)`: replace each `\t` with spaces to the next 8-column stop,
/// measuring visible width with `string_width`.
///
/// Borrows the input when there is no tab (the common case) — the expansion
/// itself is unchanged.
fn expand_tabs(line: &str) -> std::borrow::Cow<'_, str> {
    if !line.contains('\t') {
        return std::borrow::Cow::Borrowed(line);
    }

    let segments: Vec<&str> = line.split('\t').collect();
    let mut visible = 0usize;
    let mut expanded = String::new();

    for (index, segment) in segments.iter().enumerate() {
        expanded.push_str(segment);
        visible += string_width(segment);

        if index < segments.len() - 1 {
            let spaces = TAB_SIZE - (visible % TAB_SIZE);
            for _ in 0..spaces {
                expanded.push(' ');
            }
            visible += spaces;
        }
    }

    std::borrow::Cow::Owned(expanded)
}

/// `wordLengths(string)`: visible width of each space-separated word.
fn word_lengths(string: &str) -> Vec<usize> {
    string.split(' ').map(string_width).collect()
}

/// `getSgrTokens(sgrParameters)`: split the SGR parameter string on `;`, map
/// empty to `0`, parse ints, and group extended colour tokens
/// (`38`/`48`/`58` ; `5;N` or `2;R;G;B`).
///
/// JS uses `Number.parseInt`/`Number.isFinite`; an unparseable parameter yields
/// `NaN` and is skipped (`continue`). Since the regex restricts parameters to
/// `[0-9;]*`, every non-empty parameter parses, but we still model the "not
/// finite → skip" path for fidelity.
fn get_sgr_tokens(sgr_parameters: &str) -> Vec<Vec<u32>> {
    // Parse each parameter: '' → Some(0), digits → Some(n), otherwise None (NaN).
    let codes: Vec<Option<u32>> = sgr_parameters
        .split(';')
        .map(|p| {
            if p.is_empty() {
                Some(ANSI_SGR_RESET)
            } else {
                p.parse::<u32>().ok()
            }
        })
        .collect();

    let mut tokens: Vec<Vec<u32>> = Vec::new();
    let mut index = 0;
    while index < codes.len() {
        let Some(code) = codes[index] else {
            // !Number.isFinite(code) → continue
            index += 1;
            continue;
        };

        if code == ANSI_SGR_FOREGROUND_EXTENDED
            || code == ANSI_SGR_BACKGROUND_EXTENDED
            || code == ANSI_SGR_UNDERLINE_COLOR_EXTENDED
        {
            if index + 1 >= codes.len() {
                break;
            }

            let mode = codes[index + 1];

            // mode === 5 && Number.isFinite(codes[index+2])
            let next = codes.get(index + 2).copied().flatten();
            if let (Some(ANSI_SGR_COLOR_MODE_256), Some(n)) = (mode, next) {
                tokens.push(vec![code, ANSI_SGR_COLOR_MODE_256, n]);
                index += 3;
                continue;
            }

            // mode === 2 && isFinite(red) && isFinite(green) && isFinite(blue)
            let red = codes.get(index + 2).copied().flatten();
            let green = codes.get(index + 3).copied().flatten();
            let blue = codes.get(index + 4).copied().flatten();
            if let (Some(ANSI_SGR_COLOR_MODE_RGB), Some(r), Some(g), Some(b)) =
                (mode, red, green, blue)
            {
                tokens.push(vec![code, ANSI_SGR_COLOR_MODE_RGB, r, g, b]);
                index += 5;
                continue;
            }

            break;
        }

        tokens.push(vec![code]);
        index += 1;
    }

    tokens
}

/// The `ansi-styles` close code for a modifier start code, or `None`.
///
/// Verified empirically against `ansi-styles@6` (see crate-level note in
/// `ansi_codes.rs`): the map has NO entries for 5, 6, 21, 25, 54, 59. Only the
/// modifier subset matters here (colours are handled by [`get_color_style`]).
///
/// Deliberate per-port duplicate of `end_code_for_num` in
/// `ansi_tokenize/ansi_codes.rs` — each port tracks its own upstream npm package.
/// Do not unify.
fn ansi_styles_close(code: u32) -> Option<u32> {
    Some(match code {
        0 => 0,
        1 | 2 => 22,
        3 => 23,
        4 => 24,
        53 => 55,
        7 => 27,
        8 => 28,
        9 => 29,
        30..=37 | 90..=97 => 39,
        40..=47 | 100..=107 => 49,
        _ => return None,
    })
}

/// `ANSI_SGR_MODIFIER_CLOSE_CODES`: the set of `ansi-styles` close codes minus
/// `0`. Empirically `{22, 23, 24, 27, 28, 29, 39, 49, 55}`. (In practice 39/49
/// are intercepted earlier as foreground/background resets, but we model the
/// faithful predicate.)
fn is_modifier_close_code(code: u32) -> bool {
    matches!(code, 22 | 23 | 24 | 27 | 28 | 29 | 39 | 49 | 55)
}

fn remove_active_style(active_styles: &mut Vec<ActiveStyle>, family: Family) {
    if let Some(pos) = active_styles.iter().position(|s| s.family == family) {
        active_styles.remove(pos);
    }
}

fn upsert_active_style(active_styles: &mut Vec<ActiveStyle>, next: ActiveStyle) {
    remove_active_style(active_styles, next.family);
    active_styles.push(next);
}

fn remove_modifier_styles_by_close(active_styles: &mut Vec<ActiveStyle>, close_code: u32) {
    active_styles.retain(|s| !(matches!(s.family, Family::Modifier(_)) && s.close == close_code));
}

/// `getColorStyle(code, sgrToken)`: classify a token as a foreground /
/// background / underline-colour style, or `None` if it is not a colour.
fn get_color_style(code: u32, sgr_token: &[u32]) -> Option<ActiveStyle> {
    let join = || {
        sgr_token
            .iter()
            .map(|n| n.to_string())
            .collect::<Vec<_>>()
            .join(";")
    };

    if (30..=37).contains(&code)
        || (90..=97).contains(&code)
        || (code == ANSI_SGR_FOREGROUND_EXTENDED && sgr_token.len() > 1)
    {
        return Some(ActiveStyle {
            family: Family::Foreground,
            open: join(),
            close: ANSI_SGR_RESET_FOREGROUND,
        });
    }

    if (40..=47).contains(&code)
        || (100..=107).contains(&code)
        || (code == ANSI_SGR_BACKGROUND_EXTENDED && sgr_token.len() > 1)
    {
        return Some(ActiveStyle {
            family: Family::Background,
            open: join(),
            close: ANSI_SGR_RESET_BACKGROUND,
        });
    }

    if code == ANSI_SGR_UNDERLINE_COLOR_EXTENDED && sgr_token.len() > 1 {
        return Some(ActiveStyle {
            family: Family::UnderlineColor,
            open: join(),
            close: ANSI_SGR_RESET_UNDERLINE_COLOR,
        });
    }

    None
}

/// `applySgrResetCode`: returns `true` if `code` is a reset code (and applies
/// its effect to `active_styles`), `false` otherwise.
fn apply_sgr_reset_code(code: u32, active_styles: &mut Vec<ActiveStyle>) -> bool {
    if code == ANSI_SGR_RESET {
        active_styles.clear();
        return true;
    }
    if code == ANSI_SGR_RESET_FOREGROUND {
        remove_active_style(active_styles, Family::Foreground);
        return true;
    }
    if code == ANSI_SGR_RESET_BACKGROUND {
        remove_active_style(active_styles, Family::Background);
        return true;
    }
    if code == ANSI_SGR_RESET_UNDERLINE_COLOR {
        remove_active_style(active_styles, Family::UnderlineColor);
        return true;
    }
    if is_modifier_close_code(code) {
        remove_modifier_styles_by_close(active_styles, code);
        return true;
    }
    false
}

/// `applySgrToken`: apply a single SGR token to the active style stack.
fn apply_sgr_token(sgr_token: &[u32], active_styles: &mut Vec<ActiveStyle>) {
    let code = sgr_token[0];

    if apply_sgr_reset_code(code, active_styles) {
        return;
    }

    if let Some(color_style) = get_color_style(code, sgr_token) {
        upsert_active_style(active_styles, color_style);
        return;
    }

    // const close = ansiStyles.codes.get(code);
    // if (close !== undefined && close !== ANSI_SGR_RESET) { ... }
    if let Some(close) = ansi_styles_close(code).filter(|&c| c != ANSI_SGR_RESET) {
        let open = sgr_token
            .iter()
            .map(|n| n.to_string())
            .collect::<Vec<_>>()
            .join(";");
        upsert_active_style(
            active_styles,
            ActiveStyle {
                family: Family::Modifier(code),
                open,
                close,
            },
        );
    }
}

/// `applySgrParameters`: apply every token in an SGR parameter string.
fn apply_sgr_parameters(sgr_parameters: &str, active_styles: &mut Vec<ActiveStyle>) {
    for token in get_sgr_tokens(sgr_parameters) {
        apply_sgr_token(&token, active_styles);
    }
}

/// `applySgrResets`: apply only the reset codes from an SGR parameter string.
fn apply_sgr_resets(sgr_parameters: &str, active_styles: &mut Vec<ActiveStyle>) {
    for token in get_sgr_tokens(sgr_parameters) {
        apply_sgr_reset_code(token[0], active_styles);
    }
}

/// `applyLeadingSgrResets(string, activeStyles)`: pre-apply any SGR *reset*
/// codes that immediately follow a newline so we don't re-open styles that are
/// about to be closed.
fn apply_leading_sgr_resets(string: &str, active_styles: &mut Vec<ActiveStyle>) {
    let mut remainder = string;

    while !remainder.is_empty() {
        if remainder.starts_with(ANSI_ESCAPE) && next_char_is_not_backslash(remainder) {
            let Some(m) = ANSI_ESCAPE_REGEX.captures(remainder) else {
                break;
            };
            if let Some(sgr) = m.name("sgr") {
                apply_sgr_resets(sgr.as_str(), active_styles);
            }
            remainder = &remainder[m.get(0).unwrap().end()..];
            continue;
        }

        if remainder.starts_with(ANSI_ESCAPE_CSI) {
            let Some(m) = ANSI_ESCAPE_CSI_REGEX.captures(remainder) else {
                break;
            };
            // JS: !match || match.groups.sgr === undefined → break. The regex
            // always captures `sgr` when it matches, so only the no-match case
            // breaks; that is handled by the `else` above.
            let sgr = m.name("sgr").expect("csi regex always captures sgr");
            apply_sgr_resets(sgr.as_str(), active_styles);
            remainder = &remainder[m.get(0).unwrap().end()..];
            continue;
        }

        break;
    }
}

/// Mirrors JS `string[1] !== '\\'`: the character *after* the leading ESC is not
/// a backslash. Used to avoid treating an ST terminator (`ESC \`) as an opener.
fn next_char_is_not_backslash(s: &str) -> bool {
    // s starts with ESC (1 byte). Peek the next char.
    s.chars().nth(1) != Some('\\')
}

/// `getClosingSgrSequence`: active styles reversed, each closed via `ESC [ close m`.
fn get_closing_sgr_sequence(active_styles: &[ActiveStyle]) -> String {
    let mut out = String::new();
    for style in active_styles.iter().rev() {
        out.push_str(&wrap_ansi_code(&style.close.to_string()));
    }
    out
}

/// `getOpeningSgrSequence`: active styles in order, each opened via `ESC [ open m`.
fn get_opening_sgr_sequence(active_styles: &[ActiveStyle]) -> String {
    let mut out = String::new();
    for style in active_styles {
        out.push_str(&wrap_ansi_code(&style.open));
    }
    out
}

/// `wrapAnsiCode(code)` → `ESC [ code m`.
fn wrap_ansi_code(code: &str) -> String {
    format!("\u{1B}[{code}m")
}

/// `wrapAnsiHyperlink(url)` → `ESC ] 8 ; ; url BEL`.
fn wrap_ansi_hyperlink(url: &str) -> String {
    format!("\u{1B}]8;;{url}\u{7}")
}

/// `wrapWord(rows, word, columns)`: break a long word across rows grapheme by
/// grapheme, preserving ANSI sequences (which do not count towards width).
fn wrap_word(rows: &mut Vec<String>, word: &str, columns: usize) {
    let characters: Vec<&str> = word.graphemes(true).collect();

    let mut is_inside_escape = false;
    let mut is_inside_link_escape = false;
    // stringWidth(stripAnsi(x)) === stringWidth(x): string_width's ANSI_RE already
    // skips escape sequences, so this matches JS `stringWidth(stripAnsi(rows.at(-1)))`.
    let mut visible = string_width(rows.last().expect("rows is non-empty"));

    for (index, character) in characters.iter().enumerate() {
        let character_length = string_width(character);

        if visible + character_length <= columns {
            let last = rows.last_mut().expect("rows is non-empty");
            last.push_str(character);
        } else {
            rows.push((*character).to_owned());
            visible = 0;
        }

        let is_escape_char = *character == "\u{1B}" || *character == "\u{9B}";
        let prev_is_escape = index > 0 && characters[index - 1] == "\u{1B}";
        // ESCAPES.has(character) && !(isInsideLinkEscape && character === ESC && next === '\\')
        if is_escape_char
            && !(is_inside_link_escape
                && *character == "\u{1B}"
                && characters.get(index + 1) == Some(&"\\"))
        {
            is_inside_escape = true;

            // characters.slice(index+1, index+1+ANSI_ESCAPE_LINK.length).join('')
            let link_len = ANSI_ESCAPE_LINK.chars().count();
            let candidate: String = characters
                .iter()
                .skip(index + 1)
                .take(link_len)
                .copied()
                .collect();
            is_inside_link_escape = candidate == ANSI_ESCAPE_LINK;
        }

        if is_inside_escape {
            if is_inside_link_escape {
                if *character == "\u{7}" || (*character == "\\" && prev_is_escape) {
                    is_inside_escape = false;
                    is_inside_link_escape = false;
                }
            } else if *character == "m" {
                is_inside_escape = false;
            }
            continue;
        }

        visible += character_length;

        if visible == columns && index < characters.len() - 1 {
            rows.push(String::new());
            visible = 0;
        }
    }

    // Edge case: the last row copied over is only ANSI escape characters.
    if visible == 0 && !rows.last().expect("rows is non-empty").is_empty() && rows.len() > 1 {
        let popped = rows.pop().expect("rows.len() > 1");
        let n = rows.len();
        rows[n - 1].push_str(&popped);
    }
}

/// `stringVisibleTrimSpacesRight(string)`: trim trailing spaces while keeping
/// trailing zero-width (ANSI-only) "words" concatenated onto the kept part.
fn string_visible_trim_spaces_right(string: &str) -> String {
    let words: Vec<&str> = string.split(' ').collect();
    let mut last = words.len();

    while last > 0 {
        if string_width(words[last - 1]) > 0 {
            break;
        }
        last -= 1;
    }

    if last == words.len() {
        return string.to_owned();
    }

    // words.slice(0, last).join(' ') + words.slice(last).join('')
    let kept = words[..last].join(" ");
    let trailing: String = words[last..].concat();
    format!("{kept}{trailing}")
}

/// `exec(string, columns, options)`: wrap a single (already tab-expanded) line.
fn exec(string: &str, columns: usize, opts: WrapOptions) -> String {
    // if options.trim !== false && string.trim() === '' → return ''
    if opts.trim && string.trim().is_empty() {
        return String::new();
    }

    let lengths = word_lengths(string);
    let mut rows: Vec<String> = vec![String::new()];

    for (index, word) in string.split(' ').enumerate() {
        if opts.trim {
            let n = rows.len();
            // rows[last] = rows.at(-1).trimStart()
            rows[n - 1] = rows[n - 1].trim_start().to_owned();
        }

        let mut row_length = string_width(rows.last().expect("rows is non-empty"));

        if index != 0 {
            // rowLength >= columns && (wordWrap === false || trim === false)
            if row_length >= columns && (!opts.word_wrap || !opts.trim) {
                rows.push(String::new());
                row_length = 0;
            }

            if row_length > 0 || !opts.trim {
                let n = rows.len();
                rows[n - 1].push(' ');
                row_length += 1;
            }
        }

        // hard && wordWrap !== false && lengths[index] > columns
        if opts.hard && opts.word_wrap && lengths[index] > columns {
            // Compute in i64: remainingColumns can be negative in JS.
            let remaining_columns = columns as i64 - row_length as i64;
            let len = lengths[index] as i64;
            let cols = columns as i64;
            let breaks_starting_this_line = 1 + (len - remaining_columns - 1).div_euclid(cols);
            let breaks_starting_next_line = (len - 1).div_euclid(cols);
            if breaks_starting_next_line < breaks_starting_this_line {
                rows.push(String::new());
            }

            wrap_word(&mut rows, word, columns);
            continue;
        }

        // rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0
        if row_length + lengths[index] > columns && row_length > 0 && lengths[index] > 0 {
            if !opts.word_wrap && row_length < columns {
                wrap_word(&mut rows, word, columns);
                continue;
            }
            rows.push(String::new());
        }

        // rowLength + lengths[index] > columns && wordWrap === false
        if row_length + lengths[index] > columns && !opts.word_wrap {
            wrap_word(&mut rows, word, columns);
            continue;
        }

        let n = rows.len();
        rows[n - 1].push_str(word);
    }

    if opts.trim {
        rows = rows
            .iter()
            .map(|row| string_visible_trim_spaces_right(row))
            .collect();
    }

    render_rows(&rows)
}

/// Final pass of `exec`: join `rows` with `\n` and walk the grapheme stream,
/// tracking ANSI state to close styles before each newline and re-open them
/// (minus any leading resets) after.
fn render_rows(rows: &[String]) -> String {
    let pre_string = rows.join("\n");

    // Fast path: with no SGR/OSC opener anywhere (ESC U+001B / C1 CSI U+009B),
    // the walk below appends every grapheme verbatim and inserts nothing —
    // `active_styles` and `escape_url` can only change inside the two opener
    // branches, so every closing/opening sequence is empty and no hyperlink is
    // re-emitted. The result is exactly the joined rows; skip the grapheme
    // re-segmentation of the whole wrapped output.
    if !pre_string.contains(['\u{1B}', '\u{9B}']) {
        return pre_string;
    }

    let pre: Vec<&str> = pre_string.graphemes(true).collect();

    let mut return_value = String::new();
    let mut escape_url: Option<String> = None;
    let mut active_styles: Vec<ActiveStyle> = Vec::new();

    // Track the byte offset into `pre_string` for `^`-anchored regex matching.
    let mut pre_string_index = 0usize;

    for (index, character) in pre.iter().enumerate() {
        // JS appends the character FIRST, then updates state / handles newlines.
        return_value.push_str(character);

        let next = pre.get(index + 1).copied();

        if *character == "\u{1B}" && next != Some("\\") {
            if let Some(caps) = ANSI_ESCAPE_REGEX.captures(&pre_string[pre_string_index..]) {
                if let Some(sgr) = caps.name("sgr") {
                    apply_sgr_parameters(sgr.as_str(), &mut active_styles);
                } else if let Some(uri) = caps.name("uri") {
                    escape_url = if uri.as_str().is_empty() {
                        None
                    } else {
                        Some(uri.as_str().to_owned())
                    };
                }
            }
        } else if *character == "\u{9B}" {
            let sgr = ANSI_ESCAPE_CSI_REGEX
                .captures(&pre_string[pre_string_index..])
                .and_then(|caps| caps.name("sgr").map(|m| m.as_str().to_owned()));
            if let Some(sgr) = sgr {
                apply_sgr_parameters(&sgr, &mut active_styles);
            }
        }

        if next == Some("\n") {
            if escape_url.is_some() {
                return_value.push_str(&wrap_ansi_hyperlink(""));
            }
            return_value.push_str(&get_closing_sgr_sequence(&active_styles));
        } else if *character == "\n" {
            let mut opening_styles = active_styles.clone();
            // preString.slice(preStringIndex + 1): bytes after this '\n'.
            let after = &pre_string[pre_string_index + character.len()..];
            apply_leading_sgr_resets(after, &mut opening_styles);
            return_value.push_str(&get_opening_sgr_sequence(&opening_styles));

            if let Some(url) = &escape_url {
                return_value.push_str(&wrap_ansi_hyperlink(url));
            }
        }

        pre_string_index += character.len();
    }

    return_value
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::text::string_width::strip_ansi;

    fn hard() -> WrapOptions {
        WrapOptions {
            hard: true,
            ..Default::default()
        }
    }
    fn no_word_wrap() -> WrapOptions {
        WrapOptions {
            word_wrap: false,
            ..Default::default()
        }
    }
    fn no_trim() -> WrapOptions {
        WrapOptions {
            trim: false,
            ..Default::default()
        }
    }

    // ── 1. Plain wrap ────────────────────────────────────────────────────────
    // node: wrapAnsi("hello world foo bar", 10) === "hello\nworld foo\nbar"
    #[test]
    fn plain_wrap() {
        assert_eq!(
            wrap_ansi("hello world foo bar", 10),
            "hello\nworld foo\nbar"
        );
    }

    // ── 2. Colored wrap: styles close at EOL and reopen on next line ──────────
    // node: wrapAnsi("\x1b[31mhello world\x1b[39m", 5)
    //   === "\x1b[31mhello\x1b[39m\n\x1b[31mworld\x1b[39m"
    #[test]
    fn colored_wrap_close_reopen() {
        assert_eq!(
            wrap_ansi("\x1b[31mhello world\x1b[39m", 5),
            "\x1b[31mhello\x1b[39m\n\x1b[31mworld\x1b[39m"
        );
    }

    // ── 3. Hard wrap: long word at small width ────────────────────────────────
    // node: wrapAnsi("abcdefghijklmnop", 5, {hard:true}) === "abcde\nfghij\nklmno\np"
    #[test]
    fn hard_wrap_long_word() {
        assert_eq!(
            wrap_ansi_with("abcdefghijklmnop", 5, hard()),
            "abcde\nfghij\nklmno\np"
        );
    }

    // ── 3b. Hard wrap underflow: non-empty row precedes the hard word ─────────
    // node: wrapAnsi("abcde abcdefghijklmnop", 5, {hard:true})
    //   === "abcde\nabcde\nfghij\nklmno\np"
    #[test]
    fn hard_wrap_underflow() {
        assert_eq!(
            wrap_ansi_with("abcde abcdefghijklmnop", 5, hard()),
            "abcde\nabcde\nfghij\nklmno\np"
        );
    }

    // node: wrapAnsi("ab abcdefghij", 5, {hard:true}) === "ab\nabcde\nfghij"
    #[test]
    fn hard_wrap_underflow2() {
        assert_eq!(
            wrap_ansi_with("ab abcdefghij", 5, hard()),
            "ab\nabcde\nfghij"
        );
    }

    // Regression unlocked by the string-width@8 segment-loop fix: each Tamil
    // "நி" cluster (U+0BA8 U+0BBF) is width 1, so "நிநி" hard-wrapped at 1
    // breaks cleanly between the two clusters with no spurious leading newline.
    // node: wrapAnsi("நிநி", 1, {hard:true}) === "நி\nநி"
    #[test]
    fn hard_wrap_tamil_clusters() {
        assert_eq!(wrap_ansi_with("நிநி", 1, hard()), "நி\nநி");
    }

    // node: wrapAnsi("abc defghijklmno", 5, {hard:true}) === "abc\ndefgh\nijklm\nno"
    #[test]
    fn hard_wrap_short_then_long() {
        assert_eq!(
            wrap_ansi_with("abc defghijklmno", 5, hard()),
            "abc\ndefgh\nijklm\nno"
        );
    }

    // ── 4. word_wrap=false ────────────────────────────────────────────────────
    // node: wrapAnsi("hello world foo bar", 10, {wordWrap:false}) === "hello worl\nd foo bar"
    #[test]
    fn word_wrap_false() {
        assert_eq!(
            wrap_ansi_with("hello world foo bar", 10, no_word_wrap()),
            "hello worl\nd foo bar"
        );
    }

    // node: wrapAnsi("\x1b[31mhello world\x1b[39m", 5, {wordWrap:false})
    //   === "\x1b[31mhello\x1b[39m\n\x1b[31mworld\x1b[39m"
    #[test]
    fn word_wrap_false_with_ansi() {
        assert_eq!(
            wrap_ansi_with("\x1b[31mhello world\x1b[39m", 5, no_word_wrap()),
            "\x1b[31mhello\x1b[39m\n\x1b[31mworld\x1b[39m"
        );
    }

    // ── 5. trim=false preserves spaces ────────────────────────────────────────
    // node: wrapAnsi("hello world foo bar", 10, {trim:false}) === "hello \nworld foo \nbar"
    #[test]
    fn trim_false_preserves_spaces() {
        assert_eq!(
            wrap_ansi_with("hello world foo bar", 10, no_trim()),
            "hello \nworld foo \nbar"
        );
    }

    // node: wrapAnsi("\x1b[31mhello world\x1b[39m", 5, {trim:false})
    //   === "\x1b[31mhello\x1b[39m\n\x1b[31m \x1b[39m\n\x1b[31mworld\x1b[39m"
    #[test]
    fn trim_false_with_ansi() {
        assert_eq!(
            wrap_ansi_with("\x1b[31mhello world\x1b[39m", 5, no_trim()),
            "\x1b[31mhello\x1b[39m\n\x1b[31m \x1b[39m\n\x1b[31mworld\x1b[39m"
        );
    }

    // ── 6. Tab expansion (8-col stops) ────────────────────────────────────────
    // node: wrapAnsi("a\tb", 80) === "a       b"   (a + 7 spaces to col 8 + b)
    #[test]
    fn tab_expansion_single() {
        assert_eq!(wrap_ansi("a\tb", 80), "a       b");
    }

    // node: wrapAnsi("ab\tcd", 80) === "ab      cd"  (ab + 6 spaces to col 8 + cd)
    #[test]
    fn tab_expansion_two_chars() {
        assert_eq!(wrap_ansi("ab\tcd", 80), "ab      cd");
    }

    // ── 7. CRLF normalization ─────────────────────────────────────────────────
    // node: wrapAnsi("a\r\nb", 80) === "a\nb"
    #[test]
    fn crlf_normalization() {
        assert_eq!(wrap_ansi("a\r\nb", 80), "a\nb");
    }

    // ── 8. Unicode NFC normalization ──────────────────────────────────────────
    // node: wrapAnsi("e\u{301}", 80) === "é" (decomposed input; single composed char, length 1)
    #[test]
    fn nfc_normalization() {
        let out = wrap_ansi("e\u{301}", 80);
        assert_eq!(out, "é");
        // Composed: one char, 2 UTF-8 bytes (NOT "e" + combining = 3 bytes).
        assert_eq!(out.chars().count(), 1);
    }

    // ── 9. CJK fullwidth wrapping (width accounting = 2) ──────────────────────
    // node: wrapAnsi("中文 中文 中文", 4) === "中文\n中文\n中文"
    #[test]
    fn cjk_fullwidth_wrap() {
        assert_eq!(wrap_ansi("中文 中文 中文", 4), "中文\n中文\n中文");
    }

    // node: wrapAnsi("中文 中文 中文", 5) === "中文\n中文\n中文"
    #[test]
    fn cjk_fullwidth_wrap_width5() {
        assert_eq!(wrap_ansi("中文 中文 中文", 5), "中文\n中文\n中文");
    }

    // node (soft, no spaces → single overflowing word): wrapAnsi("中文中文中文", 4) === "中文中文中文"
    #[test]
    fn cjk_soft_no_break_single_word() {
        assert_eq!(wrap_ansi("中文中文中文", 4), "中文中文中文");
    }

    // node: wrapAnsi("中文中文中文", 4, {hard:true}) === "中文\n中文\n中文"
    #[test]
    fn cjk_hard_wrap() {
        assert_eq!(
            wrap_ansi_with("中文中文中文", 4, hard()),
            "中文\n中文\n中文"
        );
    }

    // ── 10. Hyperlink (OSC 8) wrap: link closed/reopened across line break ────
    // node: wrapAnsi("\x1b]8;;https://example.com\x07clicky link here\x1b]8;;\x07", 6)
    //   === each visible word wrapped, each line wrapped in its own OSC8 link
    #[test]
    fn hyperlink_osc8_wrap() {
        let input = "\x1b]8;;https://example.com\x07clicky link here\x1b]8;;\x07";
        let expected = "\x1b]8;;https://example.com\x07clicky\x1b]8;;\x07\n\
                        \x1b]8;;https://example.com\x07link\x1b]8;;\x07\n\
                        \x1b]8;;https://example.com\x07here\x1b]8;;\x07";
        assert_eq!(wrap_ansi(input, 6), expected);
    }

    // ── 11. Empty / only-spaces / tiny columns ────────────────────────────────
    // node: wrapAnsi("", 5) === ""
    #[test]
    fn empty_string() {
        assert_eq!(wrap_ansi("", 5), "");
    }

    // node: wrapAnsi("     ", 5) === ""   (trim true → blank line collapses)
    #[test]
    fn only_spaces_trim_true() {
        assert_eq!(wrap_ansi("     ", 5), "");
    }

    // node: wrapAnsi("abc", 1) === "abc"   (single soft word overflows width 1)
    #[test]
    fn tiny_columns_soft() {
        assert_eq!(wrap_ansi("abc", 1), "abc");
    }

    // columns == 0 clamps to 1 (intentional divergence — JS yields NaN garbage;
    // a pty resized to 0 columns must not crash the renderer). Hard path would
    // divide by zero without the clamp.
    #[test]
    fn zero_columns_clamps_to_one() {
        assert_eq!(wrap_ansi("abc", 0), wrap_ansi("abc", 1));
        assert_eq!(
            wrap_ansi_with("abc", 0, hard()),
            wrap_ansi_with("abc", 1, hard())
        );
        assert_eq!(wrap_ansi_with("abc", 0, hard()), "a\nb\nc");
    }

    // node: wrapAnsi("abc", 1, {hard:true}) === "a\nb\nc"
    #[test]
    fn tiny_columns_hard() {
        assert_eq!(wrap_ansi_with("abc", 1, hard()), "a\nb\nc");
    }

    // ── 12. 24-bit color SGR survives wrap ────────────────────────────────────
    // node: wrapAnsi("\x1b[38;2;255;0;0mhello world\x1b[39m", 5)
    //   === "\x1b[38;2;255;0;0mhello\x1b[39m\n\x1b[38;2;255;0;0mworld\x1b[39m"
    #[test]
    fn rgb_color_survives_wrap() {
        assert_eq!(
            wrap_ansi("\x1b[38;2;255;0;0mhello world\x1b[39m", 5),
            "\x1b[38;2;255;0;0mhello\x1b[39m\n\x1b[38;2;255;0;0mworld\x1b[39m"
        );
    }

    // 256-color variant.
    // node: wrapAnsi("\x1b[38;5;200mhello world\x1b[39m", 5)
    //   === "\x1b[38;5;200mhello\x1b[39m\n\x1b[38;5;200mworld\x1b[39m"
    #[test]
    fn color256_survives_wrap() {
        assert_eq!(
            wrap_ansi("\x1b[38;5;200mhello world\x1b[39m", 5),
            "\x1b[38;5;200mhello\x1b[39m\n\x1b[38;5;200mworld\x1b[39m"
        );
    }

    // ── 13. Structure: output stripped of ANSI == plain wrap of stripped input ─
    #[test]
    fn structure_stripped_matches_plain_wrap() {
        let colored = "\x1b[31mhello world foo\x1b[39m";
        let plain = "hello world foo";
        let stripped: String = strip_ansi(&wrap_ansi(colored, 5)).into_owned();
        assert_eq!(stripped, wrap_ansi(plain, 5));
    }

    // ── Additional verified parity cases ──────────────────────────────────────

    // node: wrapAnsi("\x1b[1mhello world\x1b[22m", 5)
    //   === "\x1b[1mhello\x1b[22m\n\x1b[1mworld\x1b[22m"
    #[test]
    fn bold_modifier_wrap() {
        assert_eq!(
            wrap_ansi("\x1b[1mhello world\x1b[22m", 5),
            "\x1b[1mhello\x1b[22m\n\x1b[1mworld\x1b[22m"
        );
    }

    // Leading reset after newline: foreground reset mid-string means the second
    // line is NOT re-opened in red.
    // node: wrapAnsi("\x1b[31mhello\x1b[39m world", 5)
    //   === "\x1b[31mhello\x1b[39m\nworld"
    #[test]
    fn leading_sgr_reset_suppresses_reopen() {
        assert_eq!(
            wrap_ansi("\x1b[31mhello\x1b[39m world", 5),
            "\x1b[31mhello\x1b[39m\nworld"
        );
    }

    // Stacked styles re-open/close in order, modifier and colour together.
    // node: wrapAnsi("\x1b[1m\x1b[31mhello world\x1b[39m\x1b[22m", 5)
    //   === "\x1b[1m\x1b[31mhello\x1b[39m\x1b[22m\n\x1b[1m\x1b[31mworld\x1b[39m\x1b[22m"
    #[test]
    fn stacked_styles_wrap() {
        assert_eq!(
            wrap_ansi("\x1b[1m\x1b[31mhello world\x1b[39m\x1b[22m", 5),
            "\x1b[1m\x1b[31mhello\x1b[39m\x1b[22m\n\x1b[1m\x1b[31mworld\x1b[39m\x1b[22m"
        );
    }

    // Background colour survives wrap.
    // node: wrapAnsi("\x1b[41mhello world\x1b[49m", 5)
    //   === "\x1b[41mhello\x1b[49m\n\x1b[41mworld\x1b[49m"
    #[test]
    fn background_color_wrap() {
        assert_eq!(
            wrap_ansi("\x1b[41mhello world\x1b[49m", 5),
            "\x1b[41mhello\x1b[49m\n\x1b[41mworld\x1b[49m"
        );
    }

    // Underline colour (58;5;N / 59).
    // node: wrapAnsi("\x1b[58;5;1mhello world\x1b[59m", 5)
    //   === "\x1b[58;5;1mhello\x1b[59m\n\x1b[58;5;1mworld\x1b[59m"
    #[test]
    fn underline_color_wrap() {
        assert_eq!(
            wrap_ansi("\x1b[58;5;1mhello world\x1b[59m", 5),
            "\x1b[58;5;1mhello\x1b[59m\n\x1b[58;5;1mworld\x1b[59m"
        );
    }

    // Three-line style continuation (reopen on EVERY line, not just once).
    // node: wrapAnsi("\x1b[31mhello world foo\x1b[39m", 5)
    //   === "\x1b[31mhello\x1b[39m\n\x1b[31mworld\x1b[39m\n\x1b[31mfoo\x1b[39m"
    #[test]
    fn three_line_style_continuation() {
        assert_eq!(
            wrap_ansi("\x1b[31mhello world foo\x1b[39m", 5),
            "\x1b[31mhello\x1b[39m\n\x1b[31mworld\x1b[39m\n\x1b[31mfoo\x1b[39m"
        );
    }

    // Embedded newline in the input is preserved as a line boundary.
    // node: wrapAnsi("hello\nworld", 80) === "hello\nworld"
    #[test]
    fn embedded_newline_preserved() {
        assert_eq!(wrap_ansi("hello\nworld", 80), "hello\nworld");
    }

    // ANSI-only input (no visible characters) is passed through unchanged.
    // node: wrapAnsi("\x1b[31m\x1b[39m", 5) === "\x1b[31m\x1b[39m"
    #[test]
    fn ansi_only_passthrough() {
        assert_eq!(wrap_ansi("\x1b[31m\x1b[39m", 5), "\x1b[31m\x1b[39m");
    }

    // Hard wrap of a styled long word: style closes/reopens on every broken row.
    // node: wrapAnsi("\x1b[31mabcdefghijklmnop\x1b[39m", 5, {hard:true})
    //   === "\x1b[31mabcde\x1b[39m\n\x1b[31mfghij\x1b[39m\n\x1b[31mklmno\x1b[39m\n\x1b[31mp\x1b[39m"
    #[test]
    fn hard_wrap_styled_word() {
        assert_eq!(
            wrap_ansi_with("\x1b[31mabcdefghijklmnop\x1b[39m", 5, hard()),
            "\x1b[31mabcde\x1b[39m\n\x1b[31mfghij\x1b[39m\n\x1b[31mklmno\x1b[39m\n\x1b[31mp\x1b[39m"
        );
    }

    // ── U+009B (C1 CSI) single-byte CSI opener ────────────────────────────────
    // The C1 CSI opener \x9b sets style state via ANSI_ESCAPE_CSI_REGEX, but the
    // re-open always emits the canonical ESC-`[` form (open == "31" →
    // "\x1b[31m"). The trailing C1 reset is the literal closing escape.
    //
    // Verified in node (inputs built with String.fromCharCode(0x9b)):
    //   wrapAnsi("›31mhello world›39m", 5)
    //   === "›31mhello\x1b[39m\n\x1b[31mworld›39m"
    #[test]
    fn c1_csi_opener_wrap() {
        assert_eq!(
            wrap_ansi("\u{9b}31mhello world\u{9b}39m", 5),
            "\u{9b}31mhello\x1b[39m\n\x1b[31mworld\u{9b}39m"
        );
    }

    // C1 CSI leading-reset: the mid-string C1 reset (›39m) clears foreground
    // before the wrap point, so apply_leading_sgr_resets (C1 branch) suppresses
    // the re-open and "world" is unstyled.
    //
    // Verified in node:
    //   wrapAnsi("›31mhello›39m world", 5)
    //   === "›31mhello›39m\nworld"
    #[test]
    fn c1_csi_leading_reset_suppresses_reopen() {
        assert_eq!(
            wrap_ansi("\u{9b}31mhello\u{9b}39m world", 5),
            "\u{9b}31mhello\u{9b}39m\nworld"
        );
    }

    // ── OSC 8 hyperlink with ST terminator (ESC \) instead of BEL ─────────────
    // Exercises the ST-terminator branches in render_rows and wrap_word. The
    // re-open after each line break uses the canonical BEL-terminated hyperlink
    // form (wrap_ansi_hyperlink), so only the original opener/closer keep ESC\.
    //
    // Verified in node (input built with ESC = String.fromCharCode(0x1b)):
    //   wrapAnsi("\x1b]8;;https://x.com\x1b\\link text here\x1b]8;;\x1b\\", 6)
    //   === "\x1b]8;;https://x.com\x1b\\link\x1b]8;;\x07\n
    //        \x1b]8;;https://x.com\x07text\x1b]8;;\x07\n
    //        \x1b]8;;https://x.com\x07here\x1b]8;;\x1b\\"
    #[test]
    fn osc8_hyperlink_st_terminator() {
        let input = "\x1b]8;;https://x.com\x1b\\link text here\x1b]8;;\x1b\\";
        let expected = "\x1b]8;;https://x.com\x1b\\link\x1b]8;;\x07\n\
                        \x1b]8;;https://x.com\x07text\x1b]8;;\x07\n\
                        \x1b]8;;https://x.com\x07here\x1b]8;;\x1b\\";
        assert_eq!(wrap_ansi(input, 6), expected);
    }

    // ── Differential harness: a block of (input, columns, opts) pinned to node ─
    // Each expected value below was produced by running wrap-ansi@10 in
    // /tmp/wa_inspect and copying the JSON output. See the inline node lines.
    #[test]
    fn differential_block_pinned() {
        // node outputs (verified):
        let cases: &[(&str, usize, WrapOptions, &str)] = &[
            // wrapAnsi("hello world foo bar", 10)
            (
                "hello world foo bar",
                10,
                WrapOptions::default(),
                "hello\nworld foo\nbar",
            ),
            // wrapAnsi("a\tb", 80)
            ("a\tb", 80, WrapOptions::default(), "a       b"),
            // wrapAnsi("a\r\nb", 80)
            ("a\r\nb", 80, WrapOptions::default(), "a\nb"),
            // wrapAnsi("abcdefghijklmnop", 5, {hard:true})
            ("abcdefghijklmnop", 5, hard(), "abcde\nfghij\nklmno\np"),
            // wrapAnsi("hello world foo bar", 10, {wordWrap:false})
            (
                "hello world foo bar",
                10,
                no_word_wrap(),
                "hello worl\nd foo bar",
            ),
            // wrapAnsi("hello world foo bar", 10, {trim:false})
            (
                "hello world foo bar",
                10,
                no_trim(),
                "hello \nworld foo \nbar",
            ),
            // wrapAnsi("中文 中文 中文", 4)
            (
                "中文 中文 中文",
                4,
                WrapOptions::default(),
                "中文\n中文\n中文",
            ),
        ];
        for (input, columns, opts, expected) in cases {
            assert_eq!(
                &wrap_ansi_with(input, *columns, *opts),
                expected,
                "case {input:?} cols={columns}"
            );
        }
    }

    // Default options match the documented JS defaults.
    #[test]
    fn default_options() {
        let d = WrapOptions::default();
        assert!(!d.hard);
        assert!(d.word_wrap);
        assert!(d.trim);
    }

    // wrap_ansi (no-opts) == wrap_ansi_with(default).
    #[test]
    fn wrap_ansi_uses_defaults() {
        let s = "hello world foo bar";
        assert_eq!(
            wrap_ansi(s, 10),
            wrap_ansi_with(s, 10, WrapOptions::default())
        );
    }

    // ── Adversarial: grapheme-cluster integrity across a seg-table bump ───────

    // The 4-person ZWJ family is 1 grapheme (7 code points, width 2). At cols=1
    // it never splits mid-cluster; the leading empty row appears because the
    // cluster (width 2) exceeds cols 1. A future unicode-segmentation bump that
    // split the ZWJ family would break this.
    // node: wrapAnsi("👨‍👩‍👧‍👦x", 1, {hard:true}), JSON.stringify == "\n👨‍👩‍👧‍👦\nx"
    #[test]
    fn wrap_zwj_family_emoji_hard_cols1_grapheme_intact() {
        assert_eq!(
            wrap_ansi_with(
                "\u{1F468}\u{200d}\u{1F469}\u{200d}\u{1F467}\u{200d}\u{1F466}x",
                1,
                hard()
            ),
            "\n\u{1F468}\u{200d}\u{1F469}\u{200d}\u{1F467}\u{200d}\u{1F466}\nx"
        );
    }

    // Each flag is one RI-pair grapheme of width 2; at cols=2 each flag fills one
    // row. A segmentation change that un-paired regional indicators would break.
    // node: wrapAnsi("🇩🇪🇫🇷", 2, {hard:true}) == "🇩🇪\n🇫🇷"
    #[test]
    fn wrap_flag_pair_hard_cols2_breaks_between_flags() {
        assert_eq!(
            wrap_ansi_with("\u{1F1E9}\u{1F1EA}\u{1F1EB}\u{1F1F7}", 2, hard()),
            "\u{1F1E9}\u{1F1EA}\n\u{1F1EB}\u{1F1F7}"
        );
    }

    // trim=false must preserve leading and interior spaces at wrap points.
    // node: wrapAnsi("     hello     world", 5, {trim:false}) == "     \nhello\n     \nworld"
    #[test]
    fn wrap_trim_false_leading_and_interior_spaces() {
        assert_eq!(
            wrap_ansi_with("     hello     world", 5, no_trim()),
            "     \nhello\n     \nworld"
        );
    }

    // A malformed SGR with no 'm' terminator (\x1b[31) must NOT match
    // ANSI_ESCAPE_REGEX and stays literal text, while the following valid \x1b[1m
    // is tracked, closed at EOL, and reopened on the next line.
    // node: wrapAnsi("\x1b[31\x1b[1mhello world", 5) == "\x1b[31\x1b[1mhello\x1b[22m\n\x1b[1mworld"
    #[test]
    fn wrap_unterminated_sgr_then_valid_sgr_midstream() {
        assert_eq!(
            wrap_ansi_with("\x1b[31\x1b[1mhello world", 5, WrapOptions::default()),
            "\x1b[31\x1b[1mhello\x1b[22m\n\x1b[1mworld"
        );
    }

    // Three bare C1 CSI opener bytes (U+009B) with no 'm' terminator must NOT
    // match the C1 CSI regex; they fall through to visible chars (width 1 each),
    // affecting the wrap math. (JSON.stringify shows U+009B bare — a stringify
    // artifact, not a divergence; Node's first 3 code points are [155,155,155].)
    // node: wrapAnsi(String.fromCharCode(0x9b)×3 + "hello world", 4) first 3 cp == [155,155,155]
    #[test]
    fn wrap_raw_c1_csi_no_terminator_treated_as_visible() {
        assert_eq!(
            wrap_ansi_with("\u{9b}\u{9b}\u{9b}hello world", 4, WrapOptions::default()),
            "\u{9b}\u{9b}\u{9b}hello\nworld"
        );
    }

    // ── Adversarial: no-panic totality (partial-escape / huge-cols) ───────────

    // A half-written SGR escape (\x1b[ with no params/terminator) at end of input
    // under hard wrap — the "renderer fed a partial escape" class. A panic kills
    // the host terminal app. (Verified output also equals Node's "hel\nlo\n\x1b[".)
    #[test]
    fn wrap_truncated_sgr_at_end_of_line_no_panic() {
        assert_eq!(wrap_ansi_with("hello \x1b[", 3, hard()), "hel\nlo\n\x1b[");
    }

    // A half-written OSC-8 link opener (\x1b]8;;u, no terminator) at end of input
    // — same partial-escape class. (Verified output equals Node's "hello\x1b]8;;u".)
    #[test]
    fn wrap_truncated_osc_at_end_of_line_no_panic() {
        assert_eq!(
            wrap_ansi_with("hello \x1b]8;;u", 3, WrapOptions::default()),
            "hello\x1b]8;;u"
        );
    }

    // columns == usize::MAX must not overflow the hard-wrap break math (the
    // `columns as i64 - row_length`, div_euclid path). A pty width read can be
    // arbitrarily large; the renderer must not crash. No Node oracle here (Node's
    // max is 2^53, Rust's is 2^64); no word exceeds columns so the div_euclid
    // split branch is never entered and the output is the input unchanged.
    #[test]
    fn wrap_cols_usize_max_hard_no_panic() {
        assert_eq!(
            wrap_ansi_with("hello world", usize::MAX, hard()),
            "hello world"
        );
    }

    // Boundary of the render_rows no-escape fast path: ONE styled span among
    // plain rows. The escape check runs on the JOINED output, so a single
    // opener anywhere must route ALL rows through the style-state walk — the
    // red span is closed and reopened on every row it crosses while the plain
    // rows stay verbatim. A per-row fast path (plain rows bypassing the walk
    // while the styled row re-opens) would drop the per-row [31m…[39m
    // bracketing. (Node wrap-ansi@10: byte-exact.)
    #[test]
    fn wrap_styled_span_among_plain_rows_reopens_per_row() {
        assert_eq!(
            wrap_ansi_with(
                "plain start \x1b[31mred spans the wrap boundary\x1b[39m plain tail",
                12,
                WrapOptions::default()
            ),
            "plain start\n\x1b[31mred spans\x1b[39m\n\x1b[31mthe wrap\x1b[39m\n\x1b[31mboundary\x1b[39m\nplain tail"
        );
    }
}