satteri-pulldown-cmark 0.4.1

A fork of the pulldown-cmark crate with MDX extensions, used in the satteri project.
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
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Post-passes that transform the built MDAST tree.
//!
//! `arena_build::parse` produces a structurally complete `Arena<Mdast>`
//! that matches micromark's tokenizer output. The remark ecosystem then
//! layers several `mdast-util-*` / `remark-*` plugins on top to:
//!
//! * recognize bare URLs and emails inside text nodes
//!   ([`gfm_autolink_literal_pass`]),
//! * inline-parse directive labels for backticks and JSX
//!   ([`directive_label_inline_code_pass`], [`directive_label_jsx_pass`]),
//! * mark and unravel MDX-only flow children
//!   ([`mdx_mark_and_unravel`]).
//!
//! Each of those is a self-contained tree-walking transformation that
//! reads / mutates `Arena<Mdast>` after building is finished. They live
//! here so [`arena_build`] stays focused on actually building the arena.

use satteri_arena::{decode_string_ref_data, Arena, ArenaBuilder, Mdast, StringRef};
use satteri_ast::mdast::{codec::LinkData, MdastNodeType};

pub(crate) const MDX_EXPLICIT_JSX_DATA: &[u8] = b"{\"_mdxExplicitJsx\":true}";

/// Mirror `mdast-util-gfm-autolink-literal`'s `isCorrectDomain`. Domain must
/// have ≥2 dot-separated parts; the last and penultimate (if non-empty) must
/// contain an ASCII alphanumeric and must not contain `_`. Empty parts are
/// allowed (skipped) so `https://.foo` (parts=[``, `foo`]) and `https://../`
/// (parts=[``, ``, ``]) both pass.
fn is_correct_domain_for_fnr(domain: &[u8]) -> bool {
    let parts: Vec<&[u8]> = domain.split(|&b| b == b'.').collect();
    if parts.len() < 2 {
        return false;
    }
    let check = |p: &[u8]| -> bool {
        if p.is_empty() {
            return true;
        }
        if p.contains(&b'_') {
            return false;
        }
        p.iter().any(|&b| b.is_ascii_alphanumeric())
    };
    check(parts[parts.len() - 1]) && check(parts[parts.len() - 2])
}

/// Mirror `mdast-util-gfm-autolink-literal`'s `splitUrl`: trim trailing chars
/// in `[!"&'),.:;<>?\]}]+` from `raw_end` while balancing `(`/`)`. Returns
/// the new end (≥ `min_end`).
fn split_url_trim_end(bytes: &[u8], min_end: usize, raw_end: usize) -> usize {
    // Find the longest trail at the end.
    let mut trail_start = raw_end;
    while trail_start > min_end {
        let b = bytes[trail_start - 1];
        if matches!(
            b,
            b'!' | b'"'
                | b'&'
                | b'\''
                | b')'
                | b','
                | b'.'
                | b':'
                | b';'
                | b'<'
                | b'>'
                | b'?'
                | b']'
                | b'}'
        ) {
            trail_start -= 1;
        } else {
            break;
        }
    }
    if trail_start == raw_end {
        return raw_end;
    }
    // Now extend back into the trail to balance any unbalanced `(`s in URL.
    let mut url_end = trail_start;
    let url_segment = &bytes[min_end..url_end];
    let mut opens = url_segment.iter().filter(|&&c| c == b'(').count();
    let mut closes = url_segment.iter().filter(|&&c| c == b')').count();
    let trail = &bytes[trail_start..raw_end];
    let mut trail_pos = 0usize;
    while opens > closes {
        // Find next `)` in trail.
        let mut found = None;
        for (i, &c) in trail[trail_pos..].iter().enumerate() {
            if c == b')' {
                found = Some(trail_pos + i);
                break;
            }
        }
        match found {
            Some(p) => {
                let consumed_end = p + 1;
                let segment = &trail[trail_pos..consumed_end];
                opens += segment.iter().filter(|&&c| c == b'(').count();
                closes += segment.iter().filter(|&&c| c == b')').count();
                url_end = trail_start + consumed_end;
                trail_pos = consumed_end;
            }
            None => break,
        }
    }
    url_end
}

pub(crate) fn scan_autolink_literal(
    bytes: &[u8],
    ix: usize,
) -> Option<(usize, usize, usize, String, bool)> {
    // Scheme. remark-gfm's autolink-literal extension handles http(s) and
    // `www.`, but not ftp — so we match that set exactly.
    let (proto_len, is_www) = if bytes[ix..].starts_with(b"http://") {
        (7, false)
    } else if bytes[ix..].starts_with(b"https://") {
        (8, false)
    } else if bytes[ix..].starts_with(b"www.") {
        (4, true)
    } else {
        return None;
    };

    // Two preceding-character rules apply, depending on which path of
    // remark-gfm's autolink-literal pipeline ends up firing:
    //
    //   * micromark's `previousProtocol` (token-level) rejects only when the
    //     previous char is alphabetic — digits, punctuation, ws, and BOF
    //     all pass.
    //   * `mdast-util-gfm-autolink-literal`'s `previous` (find-and-replace,
    //     used as a fallback when the token construct fails) is stricter:
    //     requires whitespace, punctuation, or BOF.
    //
    // We accept the loose check here so we don't miss `0https://…`. The
    // strict version is enforced later when we know whether the
    // micromark path was actually viable (see `prev_loose_only` below).
    let prev_loose_only = if ix > 0 {
        let prev = bytes[ix - 1];
        // micromark's `previousProtocol` rejects only ASCII alphabetic; any
        // non-ASCII byte (including Cyrillic letters etc.) passes the loose
        // check, so the construct can fire after `п` in `_oпhttps://...`.
        let prev_loose_ok = if prev < 0x80 {
            !prev.is_ascii_alphabetic()
        } else {
            true
        };
        if !prev_loose_ok {
            return None;
        }
        let prev_strict_ok = if prev < 0x80 {
            prev.is_ascii_whitespace() || prev.is_ascii_punctuation()
        } else {
            // Find-and-replace's `previous` accepts ws/punct/EOF in Unicode
            // sense. Cyrillic letters are alphabetic, not punctuation, so
            // they fail strict — but pass loose, leaving the construct path.
            match core::str::from_utf8(&bytes[ix.saturating_sub(4)..ix]) {
                Ok(s) => {
                    let c = s.chars().last().unwrap_or(' ');
                    c.is_whitespace() || !c.is_alphanumeric()
                }
                Err(_) => true,
            }
        };
        !prev_strict_ok
    } else {
        false
    };

    // Collect the URL body: everything until whitespace, `<`, ASCII control, or end.
    // Per GFM, valid URLs exclude control characters; matching remark's behavior
    // here avoids autolinking e.g. `http://\x07>` inside a broken `<...>`.
    //
    // micromark's `afterProtocol` rejects when the first byte past `://`
    // is whitespace, control, or Unicode punctuation — but find-and-replace
    // can still accept some of those (e.g. `https://.foo` rejected by
    // construct, accepted by find-and-replace as parts=[``, `foo`]). So we
    // record the construct verdict here and let the later validation decide.
    // (For `www.` the wwwPrefix factory handles its own first-char rules.)
    let construct_first_ok = if is_www {
        true
    } else {
        let first = bytes.get(ix + proto_len).copied();
        match first {
            None => false,
            Some(b) if b <= b' ' || b == 0x7F => false,
            Some(b) if b < 0x80 && b.is_ascii_punctuation() => false,
            _ => true,
        }
    };

    // Special case: micromark's `trail`/`trailBracketAfter` ends the URL at
    // `]` when the next char looks like the start of a CommonMark
    // resource/reference (`(`, `[`, whitespace, EOF). That keeps
    // `https://example.com/?search=](uri)` from gobbling up the trailing
    // `](uri)` even though `]` itself is fine inside a path.
    let mut end = ix + proto_len;
    while end < bytes.len() {
        let b = bytes[end];
        if b <= b' ' || b == 0x7F || b == b'<' {
            break;
        }
        if b == b']' {
            let next = bytes.get(end + 1).copied();
            if matches!(
                next,
                None | Some(b'(')
                    | Some(b'[')
                    | Some(b' ')
                    | Some(b'\t')
                    | Some(b'\n')
                    | Some(b'\r')
            ) {
                break;
            }
        }
        end += 1;
    }

    // Must have at least one char past the scheme.
    if end == ix + proto_len {
        return None;
    }

    // The GFM spec allows `.`, but a `www.` match must have a valid domain
    // (one more `.`-separated segment beyond `www.`). Reject `www.` alone.
    if is_www {
        let rest = &bytes[ix + proto_len..end];
        if rest.is_empty() {
            return None;
        }
    }

    let raw_end = end;

    // Trim trailing punctuation. Set mirrors micromark-gfm-autolink-literal's
    // trail tokenizer: `!"'*,.:;<?]_~` plus unbalanced `)` plus `&;`-
    // terminated entities. Interleaved so that e.g. trailing `")` is fully
    // stripped (`)` via balance, then `"` via the punctuation set).
    loop {
        if end <= ix + proto_len {
            break;
        }
        let last = bytes[end - 1];
        if matches!(
            last,
            b'!' | b'"'
                | b'\''
                | b'*'
                | b','
                | b'.'
                | b':'
                | b';'
                | b'<'
                | b'?'
                | b']'
                | b'_'
                | b'~'
        ) {
            end -= 1;
            continue;
        }
        if last == b')' {
            let segment = &bytes[ix..end];
            let opens = segment.iter().filter(|&&b| b == b'(').count();
            let closes = segment.iter().filter(|&&b| b == b')').count();
            if closes > opens {
                end -= 1;
                continue;
            }
        }
        break;
    }

    // Trim a trailing `;` only when it closes an HTML entity (`&...;`).
    if end > ix + proto_len && bytes[end - 1] == b';' {
        // Walk back looking for `&` before whitespace. If we find `&`, trim the entity.
        let mut j = end - 2;
        while j > ix {
            let c = bytes[j];
            if c == b'&' {
                end = j;
                break;
            }
            if !(c.is_ascii_alphanumeric() || c == b'#') {
                break;
            }
            j -= 1;
        }
    }

    if end <= ix + proto_len {
        return None;
    }

    // The domain (up to first `/`, `?`, `#`, or end) must contain a `.`
    // so that `https://localhost` or `www.` alone don't match — matching
    // remark-gfm's behavior (they DO match http/https/ftp without `.`,
    // but remark-gfm requires a `.` for the literal extension). To align
    // with the reference, allow http/https/ftp without `.` (remark accepts
    // them) but require a `.` for `www.`.
    let body = &bytes[ix + proto_len..end];
    if is_www {
        let domain_end = body
            .iter()
            .position(|&b| matches!(b, b'/' | b'?' | b'#'))
            .unwrap_or(body.len());
        if !body[..domain_end].contains(&b'.') {
            return None;
        }
    }

    // Two paths produce autolinks: micromark's `protocolAutolink` token
    // construct, and `mdast-util-gfm-autolink-literal`'s find-and-replace
    // fallback. Either accepting is enough; we have to evaluate both to
    // know whether to keep this match.
    //
    //   * Construct (`tokenizeDomain`): needs `afterProtocol` to pass
    //     (recorded above), and the domain must contain at least one
    //     alphanumeric/`-` (the `seen` flag) with no `_` in the last or
    //     penultimate dot-segments.
    //   * Find-and-replace (`isCorrectDomain` + `splitUrl`): the strict
    //     `previous` check must pass (recorded as `!prev_loose_only`),
    //     the dot-split must have ≥2 parts whose last/penult segments
    //     contain alphanumeric without `_`, and the trail-trimmed URL
    //     must be non-empty.
    //
    // The two paths also use different trim sets: micromark's `trail`
    // includes `*`, `_`, `~`; find-and-replace's `splitUrl` includes
    // `&`, `>`, `}`. So when only find-and-replace accepts, we re-trim
    // from `raw_end` with the wider set.
    // Domain ends at the first non-domain char. Micromark's
    // `tokenizeDomain` walks only over chars that can appear in a
    // domain (alphanumeric, `-`, `_`, `.`, non-ASCII); anything else
    // ends the domain. Notably `]`, when not at a trail position, is
    // *kept* in the URL body but is NOT part of the domain. So the
    // underscore check applies only to labels left of any such char.
    let construct_domain_end = body
        .iter()
        .position(|&b| {
            !(b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' || b >= 0x80)
        })
        .unwrap_or(body.len());
    let domain = &body[..construct_domain_end];
    let construct_seen = domain
        .iter()
        .any(|&b| b.is_ascii_alphanumeric() || b == b'-' || b >= 0x80);
    let construct_underscore_ok = {
        let mut last_has_us = false;
        let mut penult_has_us = false;
        for &b in domain {
            if b == b'_' {
                last_has_us = true;
            } else if b == b'.' {
                penult_has_us = last_has_us;
                last_has_us = false;
            }
        }
        !last_has_us && !penult_has_us
    };
    let construct_ok = construct_first_ok && construct_seen && construct_underscore_ok;

    if !construct_ok {
        // Construct rejected. Try find-and-replace.
        if prev_loose_only {
            return None;
        }
        // Use the body extracted via the regex: `[-.\w]+` for domain,
        // `[^ \t\r\n]*` for path (the original collection from `raw_end`
        // already stops only at whitespace/`<`, so we take from `raw_end`
        // and re-derive domain/path).
        let fnr_body = &bytes[ix + proto_len..raw_end];
        // Domain part is `[-.\w]+`: `.`, `_`, `-`, alphanumerics.
        let fnr_domain_end = fnr_body
            .iter()
            .position(|&b| !(b == b'.' || b == b'_' || b == b'-' || b.is_ascii_alphanumeric()))
            .unwrap_or(fnr_body.len());
        let fnr_domain = &fnr_body[..fnr_domain_end];
        if !is_correct_domain_for_fnr(fnr_domain) {
            return None;
        }
        // Re-trim from raw_end with find-and-replace's `splitUrl` set:
        // `[!"&'),.:;<>?\]}]+`, with balanced `)` extension.
        end = split_url_trim_end(bytes, ix + proto_len, raw_end);
        if end <= ix + proto_len {
            return None;
        }
    }

    let url_str = core::str::from_utf8(&bytes[ix..end]).ok()?;
    let full_url = if is_www {
        format!("http://{url_str}")
    } else {
        url_str.to_string()
    };
    Some((ix, raw_end, end, full_url, !construct_ok))
}

#[inline]
fn is_email_local_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-' | b'_')
}

/// GFM extended email autolink. Given `@` at `at_ix`, walk backward for the
/// local-part and forward for the domain. Returns `(start, end, "mailto:...")`.
/// Mirrors `mdast-util-gfm-autolink-literal`: requires a `.` in the domain,
/// the TLD (last dot-segment) must contain at least one letter, and trailing
/// `.`/`-`/`_` are trimmed.
/// Returns (start, end, "mailto:...", retry_needed).
/// `retry_needed` is true when the construct path's prev check failed at
/// max walkback, forcing find-and-replace to try a shorter start. When
/// true, remark emits no position because the construct never tokenized
/// the email. Callers should also treat the email as find-and-replace
/// when the source span contains backslash escapes (text bytes diverge
/// from raw source — micromark would consume the `\X` as an escape token,
/// resetting `self.previous` to `X` (gfmAtext) and rejecting the email
/// construct from firing afterward).
pub(crate) fn scan_email_autolink(
    bytes: &[u8],
    at_ix: usize,
) -> Option<(usize, usize, String, bool)> {
    if at_ix >= bytes.len() || bytes[at_ix] != b'@' {
        return None;
    }
    // Walk backward to find the maximum local-part start. Remark's GFM
    // autolink implementation does not trim any leading local-part
    // punctuation (`+`, `.`, `-`, `_` are all kept), so any non-empty
    // local-part composed of valid email chars is accepted.
    let mut start = at_ix;
    while start > 0 && is_email_local_char(bytes[start - 1]) {
        start -= 1;
    }
    if start == at_ix {
        return None;
    }
    // Two-tier prev check matching micromark's two paths:
    //   - Construct (`emailAutolink`): `previousEmail` rejects `/` (47)
    //     and `gfmAtext` (`+`, `-`, `.`, `_`, alphanumeric).
    //   - Find-and-replace (`(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@`): rejects
    //     `\w` (alphanumeric, `_`) AND `/` (via findEmail's previous(_, true)).
    //
    // At MAX walkback, prev is guaranteed non-local-char (none of `+-._`
    // or alphanumeric, since walkback consumes those). So the construct's
    // gfmAtext check trivially passes — only the `/` exclusion matters.
    let max_prev = if start == 0 {
        None
    } else {
        Some(bytes[start - 1])
    };
    let max_walkback_ok = match max_prev {
        None => true,
        Some(p) => p != b'/',
    };
    let mut retry_needed = !max_walkback_ok;

    if !max_walkback_ok {
        // Find-and-replace retries shorter walkback: advance `start` until
        // prev passes the regex's lookbehind (`^|\s|\p{P}|\p{S}`) AND
        // findEmail's `previous(_, email=true)` allows it (prev != `/`).
        // `_` is in `\p{Pc}` (connector punctuation) so it counts as
        // `\p{P}` for the lookbehind — even though it's also `\w`. Reject
        // only `/` and ASCII alphanumeric here; `+`/`-`/`.`/`_` all pass.
        while start < at_ix {
            let prev_ok = if start == 0 {
                true
            } else {
                let p = bytes[start - 1];
                p != b'/' && !p.is_ascii_alphanumeric()
            };
            if prev_ok {
                break;
            }
            start += 1;
        }
        if start >= at_ix {
            return None;
        }
        retry_needed = true;
    }
    // Forward: scan domain.
    // micromark's email construct accepts `.` as a first domain char
    // (when the `.` came from literal source). Reject is handled in
    // the caller via text-to-source mapping: when source had `\.` (the
    // dot came from an escape), the construct path can't tokenize the
    // email at all, so the caller drops the replacement.
    if at_ix + 1 >= bytes.len() {
        return None;
    }
    let mut end = at_ix + 1;
    while end < bytes.len() {
        let b = bytes[end];
        if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_') {
            end += 1;
        } else {
            break;
        }
    }
    if end == at_ix + 1 {
        return None;
    }
    // Trim trailing `.` per remark — the find-and-replace regex's
    // `(?:\.[-\w]+)+` segments don't capture a final lone `.` (no `[-\w]+`
    // follows), so the dot stays as text after the email.
    while end > at_ix + 1 && bytes[end - 1] == b'.' {
        end -= 1;
    }
    if end == at_ix + 1 {
        return None;
    }
    // mdast-util-gfm-autolink-literal's findEmail rejects when the domain
    // (label) ends in `-`, ASCII digit, or `_` (the `/[-\d_]$/.test(label)`
    // check). Reject the whole match rather than trim, so e.g.
    // `foo@bar.com-` stays as text, not `<a>foo@bar.com</a>-`.
    {
        let last = bytes[end - 1];
        if matches!(last, b'-' | b'_') || last.is_ascii_digit() {
            return None;
        }
    }
    // Domain must contain at least one `.`.
    let domain = &bytes[at_ix + 1..end];
    let last_dot = domain.iter().rposition(|&b| b == b'.')?;
    // TLD (last dot-segment) must contain at least one ASCII letter.
    let tld = &domain[last_dot + 1..];
    if tld.is_empty() || !tld.iter().any(|&b| b.is_ascii_alphabetic()) {
        return None;
    }
    // mdast-util-gfm-autolink-literal's `findEmail` only rejects when the
    // *last* character of the label is in `[-\d_]`. We already handle
    // that above. `_` elsewhere in the domain is permitted.
    let _ = tld;
    let email_str = core::str::from_utf8(&bytes[start..end]).ok()?;
    Some((start, end, format!("mailto:{email_str}"), retry_needed))
}

/// Re-merge `text + textDirective + text` sibling runs when the text ends
/// with a URL scheme and the directive's name is purely numeric (i.e. a port
/// number that got split off by the directive parser).
///
/// This is the inverse of the split that happens during inline parsing for
/// `http://host:4321/path`: the `:4321` looks like a textDirective, so the
/// inline parser emits `[text("..http://host"), textDirective("4321"), text("/path")]`.
/// GFM autolink would normally consume the whole URL as a single token before
/// the directive parser sees it, but since satteri's autolink runs as a post-
/// pass we reconstruct the original run here so autolink can find the URL.
/// Fold the bracket-depth running total forward over one string of text.
/// Returns `true` after consuming `s` iff there's a `[` (or `![`) with no
/// matching `]` so far. Backslash-escaped brackets are ignored.
fn update_bracket_depth(was_open: bool, s: &str) -> bool {
    let mut depth: i32 = if was_open { 1 } else { 0 };
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if c == b'\\' {
            i += 2;
            continue;
        }
        match c {
            b'[' => depth += 1,
            b']' if depth > 0 => depth -= 1,
            _ => {}
        }
        i += 1;
    }
    depth > 0
}

pub(crate) fn merge_directive_port_splits(arena: &mut Arena<Mdast>) {
    // Explicitly skip Link / LinkReference — a bracketed link's label text
    // intentionally preserves `text + textDirective + text` splits (remark
    // keeps them because autolink doesn't recurse into labels).
    let parent_ids: Vec<u32> = (0..arena.len() as u32)
        .filter(|&id| {
            let n = arena.get_node(id);
            matches!(
                MdastNodeType::from_u8(n.node_type),
                Some(
                    MdastNodeType::Paragraph
                        | MdastNodeType::Heading
                        | MdastNodeType::Emphasis
                        | MdastNodeType::Strong
                        | MdastNodeType::Delete
                        | MdastNodeType::TableCell
                )
            )
        })
        .collect();

    for parent_id in parent_ids {
        let children = arena.get_children(parent_id).to_vec();
        if children.len() < 2 {
            continue;
        }
        let mut new_children: Vec<u32> = Vec::with_capacity(children.len());
        let mut i = 0;
        // When a potential link-label `[` remains unclosed in earlier siblings,
        // remark's autolink-literal never tokenizes URLs in the following text
        // and its post-transformer rejects no-dot domains. Merging back would
        // then resurrect URLs remark deliberately leaves alone (see
        // `docs/src/content/docs/ru/guides/testing.mdx` in the conformance
        // check). Track the running bracket depth across preceding siblings so
        // we can bail when we're inside a broken label attempt.
        let mut unmatched_open_bracket = false;
        while i < children.len() {
            let text_id = children[i];
            let text_node = arena.get_node(text_id);
            // Track bracket depth across every text node we visit so the
            // unmatched-`[` gate below sees a correct running total.
            let is_text = text_node.node_type == MdastNodeType::Text as u8;
            if is_text {
                let d = arena.get_type_data(text_id);
                if !d.is_empty() {
                    let s = arena.get_str(StringRef::from_bytes(d));
                    unmatched_open_bracket = update_bracket_depth(unmatched_open_bracket, s);
                }
            }
            // Need a text node whose value ends with `://<host>` (no path yet).
            if !is_text || i + 1 >= children.len() {
                new_children.push(text_id);
                i += 1;
                continue;
            }
            if unmatched_open_bracket {
                new_children.push(text_id);
                i += 1;
                continue;
            }
            let dir_id = children[i + 1];
            let dir_node = arena.get_node(dir_id);
            if dir_node.node_type != MdastNodeType::TextDirective as u8 {
                new_children.push(text_id);
                i += 1;
                continue;
            }
            // Directive name must be all ASCII digits (port number).
            let dir_data = arena.get_type_data(dir_id);
            if dir_data.len() < 8 {
                new_children.push(text_id);
                i += 1;
                continue;
            }
            let dir_name_sr = StringRef::from_bytes(&dir_data[..8]);
            let dir_name = arena.get_str(dir_name_sr).to_string();
            if dir_name.is_empty() || !dir_name.bytes().all(|b| b.is_ascii_digit()) {
                new_children.push(text_id);
                i += 1;
                continue;
            }

            // Text must end with `://<host>` — check by looking for `://`
            // after the last whitespace and then any non-whitespace host.
            let text_data = arena.get_type_data(text_id);
            let text_sr = StringRef::from_bytes(text_data);
            let text_val = arena.get_str(text_sr).to_string();
            let looks_like_url_host = {
                let after_ws = text_val
                    .rsplit(|c: char| c.is_whitespace())
                    .next()
                    .unwrap_or("");
                after_ws.contains("://")
            };
            if !looks_like_url_host {
                new_children.push(text_id);
                i += 1;
                continue;
            }

            // Build merged value. Trailing text (i+2) is merged too if present
            // and starts with a URL-path char, or we leave it standalone.
            let mut merged = text_val;
            merged.push(':');
            merged.push_str(&dir_name);

            let mut consumed = 2; // text + directive
            if i + 2 < children.len() {
                let after_id = children[i + 2];
                let after_node = arena.get_node(after_id);
                if after_node.node_type == MdastNodeType::Text as u8 {
                    let after_data = arena.get_type_data(after_id);
                    let after_sr = StringRef::from_bytes(after_data);
                    let after_val = arena.get_str(after_sr);
                    merged.push_str(after_val);
                    consumed = 3;
                }
            }

            let merged_sr = arena.alloc_string(&merged);
            let text_node_start = arena.get_node(text_id).start_offset;
            let last_id = children[i + consumed - 1];
            let last_node = arena.get_node(last_id);
            let end_offset = last_node.end_offset;
            let end_line = last_node.end_line;
            let end_column = last_node.end_column;
            let start_line = arena.get_node(text_id).start_line;
            let start_column = arena.get_node(text_id).start_column;

            // Reuse the first text node as the merged one.
            arena.set_type_data(text_id, &merged_sr.as_bytes());
            arena.set_position(
                text_id,
                text_node_start,
                end_offset,
                start_line,
                start_column,
                end_line,
                end_column,
            );
            // The leading text's brackets were already folded into
            // `unmatched_open_bracket` at the top of the loop; fold in the
            // remaining text (if any) from the trailing sibling we consumed.
            if consumed == 3 {
                let tail_sr = StringRef::from_bytes(arena.get_type_data(children[i + 2]));
                let tail = arena.get_str(tail_sr);
                unmatched_open_bracket = update_bracket_depth(unmatched_open_bracket, tail);
            }
            new_children.push(text_id);
            i += consumed;
        }
        if new_children.len() != children.len() {
            arena.set_children(parent_id, &new_children);
        }
    }
}

/// Find-and-replace fallback for GFM autolink literals — the mdast-tree
/// transform equivalent of `mdast-util-gfm-autolink-literal`'s
/// `transformGfmAutolinkLiterals`. The inline construct in `firstpass.rs`
/// handles the common case (URL bytes consumed during tokenization with
/// source positions); this pass picks up URL/email patterns that survived
/// in plain Text nodes — typically because the construct path didn't fire
/// (e.g. preceded by a digit, inside a previously-failed `<...>` autolink,
/// across container prefixes). All Links emitted here are position-less,
/// matching `findAndReplace`'s behavior.
pub(crate) fn gfm_autolink_literal_pass(arena: &mut Arena<Mdast>, source_bytes: &[u8]) {
    let len = arena.len() as u32;
    let mut candidates: Vec<u32> = Vec::new();
    let text_ty = MdastNodeType::Text as u8;
    for id in 0..len {
        let node = arena.get_node(id);
        if node.node_type != text_ty {
            continue;
        }
        let parent_id = node.parent;
        if parent_id == u32::MAX || parent_id >= len {
            continue;
        }
        let parent_type = MdastNodeType::from_u8(arena.get_node(parent_id).node_type);
        // Mirrors `findAndReplace`'s `{ignore: ['link', 'linkReference']}`,
        // plus image alt-text (don't nest links there) and code/expression
        // /frontmatter nodes where literal autolinks shouldn't fire.
        if matches!(
            parent_type,
            Some(
                MdastNodeType::Link
                    | MdastNodeType::LinkReference
                    | MdastNodeType::Image
                    | MdastNodeType::ImageReference
                    | MdastNodeType::InlineCode
                    | MdastNodeType::Code
                    | MdastNodeType::MdxjsEsm
                    | MdastNodeType::MdxFlowExpression
                    | MdastNodeType::MdxTextExpression
                    | MdastNodeType::Yaml
                    | MdastNodeType::Toml
            )
        ) {
            continue;
        }
        let data = arena.get_type_data(id);
        if data.is_empty() {
            continue;
        }
        let sr = StringRef::from_bytes(data);
        let text = arena.get_str(sr);
        let bytes = text.as_bytes();
        if memchr::memchr3(b'h', b'w', b'@', bytes).is_some() {
            candidates.push(id);
        }
    }
    for node_id in candidates {
        split_text_with_autolinks_fnr(arena, node_id, source_bytes);
    }
}

/// `previous()` in `mdast-util-gfm-autolink-literal`: prev char must be
/// whitespace, punctuation, or start-of-string. Stricter than the
/// construct's `previousProtocol` (`!alphabetic`), since digits and
/// non-ASCII letters fail.
fn fnr_prev_ok(bytes: &[u8], ix: usize) -> bool {
    if ix == 0 {
        return true;
    }
    let prev = bytes[ix - 1];
    if prev < 0x80 {
        return prev.is_ascii_whitespace() || prev.is_ascii_punctuation();
    }
    // Decode the last char to apply Unicode whitespace/punctuation rules
    // (matches the `\s` / `\p{P}` / `\p{S}` lookbehind in the regex).
    match core::str::from_utf8(&bytes[ix.saturating_sub(4)..ix]) {
        Ok(s) => {
            let c = s.chars().last().unwrap_or(' ');
            c.is_whitespace() || !c.is_alphanumeric()
        }
        Err(_) => true,
    }
}

/// FNR's `findUrl` equivalent. Mirrors the
/// `(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)` regex + `previous()` +
/// `isCorrectDomain` + `splitUrl` validation chain from
/// `mdast-util-gfm-autolink-literal`.
///
/// Returns `(start, url_end, full_url, raw_end)` where `url_end..raw_end`
/// is the splitUrl trail (kept as its own text node by `findAndReplace`).
fn fnr_find_url(bytes: &[u8], ix: usize) -> Option<(usize, usize, String, usize)> {
    let (proto_len, is_www) = if bytes[ix..].starts_with(b"http://") {
        (7, false)
    } else if bytes[ix..].starts_with(b"https://") {
        (8, false)
    } else if bytes[ix..].starts_with(b"www.") {
        // The www. branch has `(?=\.)` lookahead in the regex — already
        // satisfied by `starts_with(b"www.")`.
        (4, true)
    } else {
        return None;
    };
    let s = ix;
    if !fnr_prev_ok(bytes, s) {
        return None;
    }
    // Domain class `[-.\w]+` (alphanumeric, `.`, `_`, `-`).
    let domain_start = s + proto_len;
    let mut p = domain_start;
    while p < bytes.len() {
        let b = bytes[p];
        if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_') {
            p += 1;
        } else {
            break;
        }
    }
    let domain_end = p;
    if domain_end == domain_start {
        return None;
    }
    // Path class `[^ \t\r\n]*` (anything except markdown line ending/space).
    while p < bytes.len() {
        if matches!(bytes[p], b' ' | b'\t' | b'\r' | b'\n') {
            break;
        }
        p += 1;
    }
    let raw_end = p;
    // `isCorrectDomain`: ≥2 dot parts, no `_` in last/penult, alphanumeric
    // in non-empty parts.
    if !is_correct_domain_for_fnr(&bytes[domain_start..domain_end]) {
        return None;
    }
    // `splitUrl` trim — wider than the construct's trim set; includes
    // `>`, `}`, `&` (which the construct keeps) and excludes `*`, `_`,
    // `~` (which the construct trims).
    let url_end = split_url_trim_end(bytes, domain_start, raw_end);
    if url_end <= domain_start {
        return None;
    }
    let url_str = core::str::from_utf8(&bytes[s..url_end]).ok()?;
    let full_url = if is_www {
        format!("http://{url_str}")
    } else {
        url_str.to_string()
    };
    Some((s, url_end, full_url, raw_end))
}

/// FNR's `findEmail` equivalent. Mirrors the
/// `(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)` regex + the
/// `previous(_, email=true)` + `/[-\d_]$/` rejection.
///
/// Returns `(start, end, "mailto:<addr>", raw_end)`. For emails the regex
/// has no trail, so `raw_end == end`. Uses `scan_email_autolink`'s walkback
/// (which retries from a shorter start when the max walkback's prev is
/// `/` or alphanumeric, matching FNR's `previous(_, true)` semantics).
fn fnr_find_email(bytes: &[u8], ix: usize) -> Option<(usize, usize, String, usize)> {
    let (s, e, url, _retry) = scan_email_autolink(bytes, ix)?;
    // The regex's domain class is `[-\w]+(?:\.[-\w]+)+`. The first domain
    // char must be `[-\w]` (alphanumeric, `-`, `_`); `.` is rejected.
    let first_domain = *bytes.get(ix + 1)?;
    if !(first_domain.is_ascii_alphanumeric() || first_domain == b'-' || first_domain == b'_') {
        return None;
    }
    // FNR lookbehind: whitespace/punctuation/start (Unicode-aware).
    // `scan_email_autolink`'s walkback rejects ASCII alphanumeric and `/`
    // but accepts non-ASCII letters (e.g. Cyrillic `п`) as "not atext".
    // FNR's regex rejects those via the `\p{P}|\p{S}` lookbehind class.
    if !fnr_prev_ok(bytes, s) {
        return None;
    }
    Some((s, e, url, e))
}

/// FNR-style scan over a Text node's bytes. Emits position-less Links for
/// each match; left-over text becomes plain Text nodes between/around them.
/// `findUrl` returns `[link, text(trail)]` when splitUrl strips trailing
/// chars — `findAndReplace` then inserts those as adjacent siblings,
/// keeping the trail distinct from the surrounding text. Mirror that.
fn split_text_with_autolinks_fnr(arena: &mut Arena<Mdast>, text_id: u32, source_bytes: &[u8]) {
    let data = arena.get_type_data(text_id);
    if data.is_empty() {
        return;
    }
    let sr = StringRef::from_bytes(data);
    let text = arena.get_str(sr).to_string();
    let bytes = text.as_bytes();

    let mut matches: Vec<(usize, usize, usize, String)> = Vec::new();
    let mut i = 0;
    while let Some(rel) = memchr::memchr3(b'h', b'w', b'@', &bytes[i..]) {
        i += rel;
        let b = bytes[i];
        let hit = if b == b'h' || b == b'w' {
            fnr_find_url(bytes, i)
        } else {
            fnr_find_email(bytes, i)
        };
        if let Some((s, url_end, url, raw_end)) = hit {
            let last_end = matches.last().map_or(0, |m| m.2);
            if s >= last_end {
                matches.push((s, url_end, raw_end, url));
                i = raw_end;
                continue;
            }
        }
        i += 1;
    }

    if matches.is_empty() {
        return;
    }

    // Per `mdast-util-gfm-autolink-literal`'s `findAndReplace`, links
    // emitted here are intentionally position-less — even though they
    // span a known source range, the F&R transform doesn't carry source
    // offsets. We mirror that to match REF exactly on inputs where the
    // construct-level autolink tokenizer didn't fire (e.g. autolinks
    // preceded by `[`). Don't emit positions on the new nodes.
    let _ = source_bytes;
    let pos_for =
        |_chunk_lo: usize, _chunk_hi: usize| -> Option<(u32, u32, u32, u32, u32, u32)> { None };

    let mut new_children: Vec<u32> = Vec::new();
    let mut cursor = 0usize;
    for (s, url_end, raw_end, url) in matches {
        if s > cursor {
            let chunk = &text[cursor..s];
            let new_text_id = arena.alloc_node(MdastNodeType::Text as u8);
            let chunk_sr = arena.alloc_string(chunk);
            arena.set_type_data(new_text_id, &chunk_sr.as_bytes());
            if let Some((so, eo, sl, sc, el, ec)) = pos_for(cursor, s) {
                arena.set_position(new_text_id, so, eo, sl, sc, el, ec);
            }
            new_children.push(new_text_id);
        }
        let link_id = arena.alloc_node(MdastNodeType::Link as u8);
        let url_sr = arena.alloc_string(&url);
        let link_data = LinkData {
            url: url_sr,
            title: StringRef::empty(),
        };
        arena.set_type_data(link_id, &link_data.to_bytes());
        let link_text_id = arena.alloc_node(MdastNodeType::Text as u8);
        let disp_sr = arena.alloc_string(&text[s..url_end]);
        arena.set_type_data(link_text_id, &disp_sr.as_bytes());
        if let Some((so, eo, sl, sc, el, ec)) = pos_for(s, url_end) {
            arena.set_position(link_id, so, eo, sl, sc, el, ec);
            arena.set_position(link_text_id, so, eo, sl, sc, el, ec);
        }
        arena.set_children(link_id, &[link_text_id]);
        new_children.push(link_id);
        // `findUrl` emits the trail as a separate text node. `findEmail`
        // has no trail (raw_end == end).
        if raw_end > url_end {
            let trail_chunk = &text[url_end..raw_end];
            let trail_id = arena.alloc_node(MdastNodeType::Text as u8);
            let trail_sr = arena.alloc_string(trail_chunk);
            arena.set_type_data(trail_id, &trail_sr.as_bytes());
            if let Some((so, eo, sl, sc, el, ec)) = pos_for(url_end, raw_end) {
                arena.set_position(trail_id, so, eo, sl, sc, el, ec);
            }
            new_children.push(trail_id);
        }
        cursor = raw_end;
    }
    if cursor < bytes.len() {
        let chunk = &text[cursor..];
        let new_text_id = arena.alloc_node(MdastNodeType::Text as u8);
        let chunk_sr = arena.alloc_string(chunk);
        arena.set_type_data(new_text_id, &chunk_sr.as_bytes());
        if let Some((so, eo, sl, sc, el, ec)) = pos_for(cursor, bytes.len()) {
            arena.set_position(new_text_id, so, eo, sl, sc, el, ec);
        }
        new_children.push(new_text_id);
    }

    arena.replace_node_with_children(text_id, &new_children);
}

/// Append a text value as an MDAST Text leaf, merging with the previous
/// sibling text node when possible. Matches the behavior remark inherits
/// from `mdast-util-from-markdown`, which coalesces adjacent text nodes
/// that result from entity decoding, character synthesis, etc.
#[allow(clippy::too_many_arguments)]
pub(crate) fn emit_text_merging(
    builder: &mut ArenaBuilder<Mdast>,
    text_value: &str,
    start: u32,
    end: u32,
    start_line: u32,
    start_col: u32,
    end_line: u32,
    end_col: u32,
) {
    if let Some(pid) = builder.last_sibling_id() {
        let prev = builder.arena_ref().get_node(pid);
        if prev.node_type == MdastNodeType::Text as u8 {
            let prev_data = builder.arena_ref().get_type_data(pid);
            if prev_data.len() >= 8 {
                let prev_sr = StringRef::from_bytes(prev_data);
                let prev_text = builder.arena_ref().get_str(prev_sr);
                let combined = [prev_text, text_value].concat();
                let new_sr = builder.alloc_string(&combined);
                let pn = builder.arena_ref().get_node(pid);
                builder.update_leaf_full(
                    pid,
                    pn.start_offset,
                    end,
                    pn.start_line,
                    pn.start_column,
                    end_line,
                    end_col,
                    &new_sr.as_bytes(),
                );
                return;
            }
        }
    }
    let sr = builder.alloc_string(text_value);
    builder.add_leaf_full(
        MdastNodeType::Text as u8,
        start,
        end,
        start_line,
        start_col,
        end_line,
        end_col,
        &sr.as_bytes(),
    );
}

/// For each `Text` node that lives directly under a directive's label, scan
/// for balanced backtick runs and split the text into `text + inlineCode + text`
/// pieces. This matches the common `:::tip[Set a \`baseUrl\`]` pattern without
/// needing to re-run the full inline parser on the label substring.
pub(crate) fn directive_label_inline_code_pass(arena: &mut Arena<Mdast>) {
    // Collect candidate text node ids first (pair: parent id, text id).
    let mut candidates: Vec<u32> = Vec::new();
    for id in 0..arena.len() as u32 {
        let node = arena.get_node(id);
        if node.node_type != MdastNodeType::Text as u8 {
            continue;
        }
        // Text value must contain a backtick to be worth processing.
        let data = arena.get_type_data(id);
        if data.is_empty() {
            continue;
        }
        let sr = StringRef::from_bytes(data);
        let text = arena.get_str(sr);
        if !text.contains('`') {
            continue;
        }

        let parent_id = node.parent;
        let parent = arena.get_node(parent_id);
        let parent_type = MdastNodeType::from_u8(parent.node_type);

        let is_directive_label = match parent_type {
            // Text directly under a leaf/text directive — the directive's
            // children ARE the label.
            Some(MdastNodeType::LeafDirective | MdastNodeType::TextDirective) => true,
            // Paragraph under a container directive is the label iff it has
            // the `directiveLabel:true` marker.
            Some(MdastNodeType::Paragraph) => {
                let node_data = arena.get_node_data(parent_id);
                node_data
                    .map(|d| d.starts_with(b"{\"directiveLabel\":true}"))
                    .unwrap_or(false)
            }
            _ => false,
        };
        if !is_directive_label {
            continue;
        }
        candidates.push(id);
    }

    for text_id in candidates {
        split_text_on_backticks(arena, text_id);
    }
}

/// Split a `Text` node's value into `text + inlineCode + text …` on balanced
/// backtick runs. Only handles the simple case (same-length opening/closing
/// runs, single-line), which is what directive labels carry in practice.
fn split_text_on_backticks(arena: &mut Arena<Mdast>, text_id: u32) {
    let data = arena.get_type_data(text_id);
    if data.is_empty() {
        return;
    }
    let sr = StringRef::from_bytes(data);
    // Fast-path: no backtick anywhere → nothing to split, skip the clone.
    if memchr::memchr(b'`', arena.get_str(sr).as_bytes()).is_none() {
        return;
    }
    let text = arena.get_str(sr).to_string();
    let bytes = text.as_bytes();

    // Find all balanced backtick pairs.
    #[derive(Clone, Copy)]
    struct Pair {
        open_start: usize,
        open_end: usize,
        close_start: usize,
        close_end: usize,
    }
    let mut pairs: Vec<Pair> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'`' {
            i += 1;
            continue;
        }
        // Count run length.
        let open_start = i;
        while i < bytes.len() && bytes[i] == b'`' {
            i += 1;
        }
        let open_end = i;
        let run_len = open_end - open_start;
        // Find matching closing run of the same length.
        let mut j = i;
        let matched_close: Option<(usize, usize)> = loop {
            if j >= bytes.len() {
                break None;
            }
            if bytes[j] == b'`' {
                let close_start = j;
                while j < bytes.len() && bytes[j] == b'`' {
                    j += 1;
                }
                let close_end = j;
                if close_end - close_start == run_len {
                    break Some((close_start, close_end));
                }
                // Not a match; skip this run and continue searching.
                continue;
            }
            j += 1;
        };
        if let Some((cs, ce)) = matched_close {
            pairs.push(Pair {
                open_start,
                open_end,
                close_start: cs,
                close_end: ce,
            });
            i = ce;
        }
    }

    if pairs.is_empty() {
        return;
    }

    // Build the replacement child list.
    let node = arena.get_node(text_id);
    let base_start = node.start_offset;
    let base_line = node.start_line;
    let base_col = node.start_column;

    let mut new_children: Vec<u32> = Vec::new();
    let mut cursor = 0usize;
    for p in pairs {
        // Leading plain text.
        if p.open_start > cursor {
            let segment = &text[cursor..p.open_start];
            if !segment.is_empty() {
                let seg_sr = arena.alloc_string(segment);
                let tid = arena.alloc_node(MdastNodeType::Text as u8);
                arena.set_type_data(tid, &seg_sr.as_bytes());
                arena.set_position(
                    tid,
                    base_start + cursor as u32,
                    base_start + p.open_start as u32,
                    base_line,
                    base_col + cursor as u32,
                    base_line,
                    base_col + p.open_start as u32,
                );
                new_children.push(tid);
            }
        }
        // Inline code.
        let code_value = &text[p.open_end..p.close_start];
        let code_sr = arena.alloc_string(code_value);
        let cid = arena.alloc_node(MdastNodeType::InlineCode as u8);
        arena.set_type_data(cid, &code_sr.as_bytes());
        arena.set_position(
            cid,
            base_start + p.open_start as u32,
            base_start + p.close_end as u32,
            base_line,
            base_col + p.open_start as u32,
            base_line,
            base_col + p.close_end as u32,
        );
        new_children.push(cid);
        cursor = p.close_end;
    }
    // Trailing plain text.
    if cursor < text.len() {
        let segment = &text[cursor..];
        let seg_sr = arena.alloc_string(segment);
        let tid = arena.alloc_node(MdastNodeType::Text as u8);
        arena.set_type_data(tid, &seg_sr.as_bytes());
        arena.set_position(
            tid,
            base_start + cursor as u32,
            base_start + text.len() as u32,
            base_line,
            base_col + cursor as u32,
            base_line,
            base_col + text.len() as u32,
        );
        new_children.push(tid);
    }

    arena.replace_node_with_children(text_id, &new_children);
}

/// Post-pass matching `directive_label_inline_code_pass` for JSX tags. For
/// each `Text` node directly under a directive label, split on balanced
/// `<Name>…</Name>` (or self-closing `<Name/>`) runs and emit
/// `mdxJsxTextElement` children. Also splits on balanced `{…}` spans and
/// emits `mdxTextExpression` nodes.
pub(crate) fn directive_label_jsx_pass(arena: &mut Arena<Mdast>) {
    let mut candidates: Vec<u32> = Vec::new();
    for id in 0..arena.len() as u32 {
        let node = arena.get_node(id);
        if node.node_type != MdastNodeType::Text as u8 {
            continue;
        }
        let data = arena.get_type_data(id);
        if data.is_empty() {
            continue;
        }
        let sr = StringRef::from_bytes(data);
        let text = arena.get_str(sr);
        if !text.contains('<') && !text.contains('{') {
            continue;
        }
        let parent_id = node.parent;
        let parent = arena.get_node(parent_id);
        let parent_type = MdastNodeType::from_u8(parent.node_type);
        let is_directive_label = match parent_type {
            Some(MdastNodeType::LeafDirective | MdastNodeType::TextDirective) => true,
            Some(MdastNodeType::Paragraph) => arena
                .get_node_data(parent_id)
                .map(|d| d.starts_with(b"{\"directiveLabel\":true}"))
                .unwrap_or(false),
            _ => false,
        };
        if !is_directive_label {
            continue;
        }
        candidates.push(id);
    }
    for text_id in candidates {
        split_text_on_jsx_tags(arena, text_id);
    }
    // Second pass picks up text nodes created by the first split and emits
    // MDX text expressions for `{…}` runs.
    let mut expr_candidates: Vec<u32> = Vec::new();
    for id in 0..arena.len() as u32 {
        let node = arena.get_node(id);
        if node.node_type != MdastNodeType::Text as u8 {
            continue;
        }
        let data = arena.get_type_data(id);
        if data.is_empty() {
            continue;
        }
        let sr = StringRef::from_bytes(data);
        let text = arena.get_str(sr);
        if !text.contains('{') {
            continue;
        }
        let parent_id = node.parent;
        let parent = arena.get_node(parent_id);
        let parent_type = MdastNodeType::from_u8(parent.node_type);
        let in_label = match parent_type {
            Some(MdastNodeType::LeafDirective | MdastNodeType::TextDirective) => true,
            Some(MdastNodeType::Paragraph) => arena
                .get_node_data(parent_id)
                .map(|d| d.starts_with(b"{\"directiveLabel\":true}"))
                .unwrap_or(false),
            // Also handle the children of a JSX text element created by the
            // first pass — they also live under a directive label.
            Some(MdastNodeType::MdxJsxTextElement) => {
                let grandparent_id = parent.parent;
                if grandparent_id == u32::MAX {
                    false
                } else {
                    let grandparent = arena.get_node(grandparent_id);
                    let gp_type = MdastNodeType::from_u8(grandparent.node_type);
                    matches!(
                        gp_type,
                        Some(MdastNodeType::LeafDirective | MdastNodeType::TextDirective)
                    ) || (gp_type == Some(MdastNodeType::Paragraph)
                        && arena
                            .get_node_data(grandparent_id)
                            .map(|d| d.starts_with(b"{\"directiveLabel\":true}"))
                            .unwrap_or(false))
                }
            }
            _ => false,
        };
        if !in_label {
            continue;
        }
        expr_candidates.push(id);
    }
    for text_id in expr_candidates {
        split_text_on_mdx_expressions(arena, text_id);
    }
}

/// Split a `Text` node on `{…}` spans (balanced braces, JS-aware) and emit
/// `mdxTextExpression` nodes for the matched spans.
fn split_text_on_mdx_expressions(arena: &mut Arena<Mdast>, text_id: u32) {
    use crate::mdx::scan_mdx_inline_expression;
    let data = arena.get_type_data(text_id);
    if data.is_empty() {
        return;
    }
    let sr = StringRef::from_bytes(data);
    // Fast-path: no `{` anywhere → no expression spans possible.
    if memchr::memchr(b'{', arena.get_str(sr).as_bytes()).is_none() {
        return;
    }
    let text = arena.get_str(sr).to_string();
    let bytes = text.as_bytes();
    let mut spans: Vec<(usize, usize, usize, usize)> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'{' {
            i += 1;
            continue;
        }
        let Some((content_start, content_end, total_len)) = scan_mdx_inline_expression(&bytes[i..])
        else {
            i += 1;
            continue;
        };
        spans.push((i, i + total_len, i + content_start, i + content_end));
        i += total_len;
    }
    if spans.is_empty() {
        return;
    }
    let node = arena.get_node(text_id);
    let base_start = node.start_offset;
    let base_line = node.start_line;
    let base_col = node.start_column;

    let mut new_children: Vec<u32> = Vec::new();
    let mut cursor = 0usize;
    for (span_start, span_end, content_start, content_end) in spans {
        if span_start > cursor {
            let seg = &text[cursor..span_start];
            let seg_sr = arena.alloc_string(seg);
            let tid = arena.alloc_node(MdastNodeType::Text as u8);
            arena.set_type_data(tid, &seg_sr.as_bytes());
            arena.set_position(
                tid,
                base_start + cursor as u32,
                base_start + span_start as u32,
                base_line,
                base_col + cursor as u32,
                base_line,
                base_col + span_start as u32,
            );
            new_children.push(tid);
        }
        let content = &text[content_start..content_end];
        let content_sr = arena.alloc_string(content);
        let eid = arena.alloc_node(MdastNodeType::MdxTextExpression as u8);
        arena.set_type_data(eid, &content_sr.as_bytes());
        arena.set_position(
            eid,
            base_start + span_start as u32,
            base_start + span_end as u32,
            base_line,
            base_col + span_start as u32,
            base_line,
            base_col + span_end as u32,
        );
        new_children.push(eid);
        cursor = span_end;
    }
    if cursor < text.len() {
        let seg = &text[cursor..];
        let seg_sr = arena.alloc_string(seg);
        let tid = arena.alloc_node(MdastNodeType::Text as u8);
        arena.set_type_data(tid, &seg_sr.as_bytes());
        arena.set_position(
            tid,
            base_start + cursor as u32,
            base_start + text.len() as u32,
            base_line,
            base_col + cursor as u32,
            base_line,
            base_col + text.len() as u32,
        );
        new_children.push(tid);
    }
    arena.replace_node_with_children(text_id, &new_children);
}

/// Split a `Text` node on `<Name>…</Name>` / `<Name/>` spans, producing
/// `mdxJsxTextElement` nodes for the matched spans. The inner content of a
/// matched open/close pair becomes a child `Text` node (no recursion — nested
/// JSX inside a directive label is rare enough that a single-level split
/// covers the conformance cases).
fn split_text_on_jsx_tags(arena: &mut Arena<Mdast>, text_id: u32) {
    use crate::mdx::{parse_jsx_tag, scan_mdx_inline_jsx};
    let data = arena.get_type_data(text_id);
    if data.is_empty() {
        return;
    }
    let sr = StringRef::from_bytes(data);
    // Fast-path: no `<` anywhere → no JSX tag spans possible.
    if memchr::memchr(b'<', arena.get_str(sr).as_bytes()).is_none() {
        return;
    }
    let text = arena.get_str(sr).to_string();
    let bytes = text.as_bytes();

    #[derive(Clone)]
    enum Span {
        SelfClosing {
            start: usize,
            end: usize,
            name: alloc::string::String,
        },
        Paired {
            start: usize,
            open_end: usize,
            close_start: usize,
            end: usize,
            name: alloc::string::String,
        },
    }

    let mut spans: Vec<Span> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'<' {
            i += 1;
            continue;
        }
        let Some(tag_end) = scan_mdx_inline_jsx(&bytes[i..]) else {
            i += 1;
            continue;
        };
        let tag_raw = &text[i..i + tag_end];
        let jsx = parse_jsx_tag(tag_raw);
        if jsx.is_closing {
            i += tag_end;
            continue;
        }
        if jsx.is_self_closing {
            spans.push(Span::SelfClosing {
                start: i,
                end: i + tag_end,
                name: jsx.name.to_string(),
            });
            i += tag_end;
            continue;
        }
        // Opening tag — scan forward for a matching `</name>`.
        let name = jsx.name.to_string();
        let open_end = i + tag_end;
        let mut j = open_end;
        let mut close_span: Option<(usize, usize)> = None;
        while j < bytes.len() {
            if bytes[j] != b'<' {
                j += 1;
                continue;
            }
            let Some(inner_tag_end) = scan_mdx_inline_jsx(&bytes[j..]) else {
                j += 1;
                continue;
            };
            let inner_tag = &text[j..j + inner_tag_end];
            let inner_jsx = parse_jsx_tag(inner_tag);
            if inner_jsx.is_closing && inner_jsx.name.as_ref() == name.as_str() {
                close_span = Some((j, j + inner_tag_end));
                break;
            }
            j += inner_tag_end;
        }
        if let Some((close_start, close_end)) = close_span {
            spans.push(Span::Paired {
                start: i,
                open_end,
                close_start,
                end: close_end,
                name,
            });
            i = close_end;
        } else {
            i = open_end;
        }
    }

    if spans.is_empty() {
        return;
    }

    let node = arena.get_node(text_id);
    let base_start = node.start_offset;
    let base_line = node.start_line;
    let base_col = node.start_column;

    let push_text = |arena: &mut Arena<Mdast>,
                     out: &mut Vec<u32>,
                     segment: &str,
                     seg_start: usize,
                     seg_end: usize| {
        if segment.is_empty() {
            return;
        }
        let seg_sr = arena.alloc_string(segment);
        let tid = arena.alloc_node(MdastNodeType::Text as u8);
        arena.set_type_data(tid, &seg_sr.as_bytes());
        arena.set_position(
            tid,
            base_start + seg_start as u32,
            base_start + seg_end as u32,
            base_line,
            base_col + seg_start as u32,
            base_line,
            base_col + seg_end as u32,
        );
        out.push(tid);
    };

    let mut new_children: Vec<u32> = Vec::new();
    let mut cursor = 0usize;
    for span in spans {
        match span {
            Span::SelfClosing { start, end, name } => {
                push_text(
                    arena,
                    &mut new_children,
                    &text[cursor..start],
                    cursor,
                    start,
                );
                let name_sr = arena.alloc_string(&name);
                let jsx_data = satteri_ast::mdast::encode_mdx_jsx_element_data(name_sr, &[], true);
                let jid = arena.alloc_node(MdastNodeType::MdxJsxTextElement as u8);
                arena.set_type_data(jid, &jsx_data);
                arena.set_node_data(jid, MDX_EXPLICIT_JSX_DATA.to_vec());
                arena.set_position(
                    jid,
                    base_start + start as u32,
                    base_start + end as u32,
                    base_line,
                    base_col + start as u32,
                    base_line,
                    base_col + end as u32,
                );
                new_children.push(jid);
                cursor = end;
            }
            Span::Paired {
                start,
                open_end,
                close_start,
                end,
                name,
            } => {
                push_text(
                    arena,
                    &mut new_children,
                    &text[cursor..start],
                    cursor,
                    start,
                );
                let name_sr = arena.alloc_string(&name);
                let jsx_data = satteri_ast::mdast::encode_mdx_jsx_element_data(name_sr, &[], true);
                let jid = arena.alloc_node(MdastNodeType::MdxJsxTextElement as u8);
                arena.set_type_data(jid, &jsx_data);
                arena.set_node_data(jid, MDX_EXPLICIT_JSX_DATA.to_vec());
                arena.set_position(
                    jid,
                    base_start + start as u32,
                    base_start + end as u32,
                    base_line,
                    base_col + start as u32,
                    base_line,
                    base_col + end as u32,
                );
                // Inner text child.
                let inner = &text[open_end..close_start];
                if !inner.is_empty() {
                    let inner_sr = arena.alloc_string(inner);
                    let cid = arena.alloc_node(MdastNodeType::Text as u8);
                    arena.set_type_data(cid, &inner_sr.as_bytes());
                    arena.set_position(
                        cid,
                        base_start + open_end as u32,
                        base_start + close_start as u32,
                        base_line,
                        base_col + open_end as u32,
                        base_line,
                        base_col + close_start as u32,
                    );
                    arena.set_children(jid, &[cid]);
                }
                new_children.push(jid);
                cursor = end;
            }
        }
    }
    push_text(
        arena,
        &mut new_children,
        &text[cursor..],
        cursor,
        text.len(),
    );

    arena.replace_node_with_children(text_id, &new_children);
}

pub(crate) fn mdx_mark_and_unravel(arena: &mut Arena<Mdast>) {
    let len = arena.len() as u32;
    // Only paragraphs containing inline MDX nodes can be promoted; without
    // any in the arena the per-paragraph work below is guaranteed wasted.
    let has_inline_mdx = (0..len).any(|id| {
        matches!(
            MdastNodeType::from_u8(arena.get_node(id).node_type),
            Some(MdastNodeType::MdxJsxTextElement | MdastNodeType::MdxTextExpression),
        )
    });
    if !has_inline_mdx {
        return;
    }
    for id in 0..len {
        let node = arena.get_node(id);
        if node.node_type != MdastNodeType::Paragraph as u8 {
            continue;
        }
        let children = arena.get_children(id).to_vec();
        if children.is_empty() {
            continue;
        }
        let mut all_mdx = true;
        let mut has_mdx = false;
        for &child_id in &children {
            let child = arena.get_node(child_id);
            match MdastNodeType::from_u8(child.node_type) {
                Some(MdastNodeType::MdxJsxTextElement | MdastNodeType::MdxTextExpression) => {
                    has_mdx = true;
                }
                Some(MdastNodeType::Text) => {
                    let data = arena.get_type_data(child_id);
                    if !data.is_empty() {
                        let sr = decode_string_ref_data(data);
                        let text = arena.get_str(sr);
                        if !text.chars().all(|c| c.is_ascii_whitespace()) {
                            all_mdx = false;
                            break;
                        }
                    }
                }
                _ => {
                    all_mdx = false;
                    break;
                }
            }
        }
        if !all_mdx || !has_mdx {
            continue;
        }
        let mut promoted: Vec<u32> = Vec::new();
        for &child_id in &children {
            let child = arena.get_node(child_id);
            match MdastNodeType::from_u8(child.node_type) {
                Some(MdastNodeType::MdxJsxTextElement) => {
                    arena.get_node_mut(child_id).node_type = MdastNodeType::MdxJsxFlowElement as u8;
                    promoted.push(child_id);
                }
                Some(MdastNodeType::MdxTextExpression) => {
                    arena.get_node_mut(child_id).node_type = MdastNodeType::MdxFlowExpression as u8;
                    promoted.push(child_id);
                }
                Some(MdastNodeType::Text) => {
                    let data = arena.get_type_data(child_id);
                    if !data.is_empty() {
                        let sr = decode_string_ref_data(data);
                        let text = arena.get_str(sr);
                        if !text.chars().all(|c| c.is_ascii_whitespace()) {
                            promoted.push(child_id);
                        }
                    }
                }
                _ => {
                    promoted.push(child_id);
                }
            }
        }
        arena.replace_node_with_children(id, &promoted);
    }
}