bun_url 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
// This is close to WHATWG URL, but we don't want the validation errors
#![warn(unused_must_use)]
use core::cell::RefCell;

use bun_collections::bit_set::{ArrayBitSet, num_masks_for};
use bun_core::{self, fmt as bun_fmt};
use bun_core::{String as BunString, Tag as BunStringTag, immutable as strings};
use bun_paths::resolve_path::{self, platform};
use bun_wyhash::hash as wyhash;

// `bun.schema.api.StringPointer` — canonical definition lives in `bun_core`
// (T0, already a dep). Re-exported under `api::` so `QueryStringMap` /
// `CombinedScanner` field types keep resolving.
pub mod api {
    pub use bun_core::StringPointer;
}

use bun_core::io::Write as _;

// ── route_param (moved from bun_router) ───────────────────────────────────
pub mod route_param {
    // PORT NOTE: name/value borrow from the route template + the live request
    // path; lifetime-generic so `bun_router` (the only producer) can fill them
    // from non-'static buffers. Downstream that only stores literals can use
    // `Param<'static>`.
    #[derive(Clone, Copy)]
    pub struct Param<'a> {
        pub name: &'a [u8],
        pub value: &'a [u8],
    }
    // TODO(port): bun_collections::MultiArrayList — derive(MultiArrayElement)
    // proc-macro not yet available. Using Vec; SoA layout is a perf concern only.
    pub type List<'a> = Vec<Param<'a>>;
}
pub use route_param::List as ParamsList;

// ── whatwg (pure-Rust WHATWG surface; was WTF::URL FFI) ───────────────────
// Ground truth: src/jsc/URL.zig. The JS-value entry points (`hrefFromJS`, `fromJS`)
// stay in tier-6 as extension methods — they need JSValue/JSGlobalObject.
// All string/parse entry points are pure Rust over `super::URL::parse` /
// `OwnedURL` so product no longer needs WebKit `URL__*` noops.
//
// @trace STUB-INVENTORY: pure-Rust bun_url WHATWG (drop dead URL__* FFI)
pub mod whatwg {
    use core::ptr::NonNull;

    use super::BunString as String;

    /// Heap-owned URL. Mirrors the old WTF::URL handle shape (`NonNull<URL>` +
    /// `deinit`) so `hosted_git_info` / install keep working without C++.
    /// Free **only** via [`URL::deinit`] / `Box::from_raw` — no `Drop` (callers
    /// own the pointer explicitly, matching Zig/C++).
    pub struct URL {
        href: Box<[u8]>,
    }

    impl URL {
        fn parsed(&self) -> super::URL<'_> {
            super::URL::parse(&self.href)
        }

        fn component_string(&self, pick: impl FnOnce(super::URL<'_>) -> &[u8]) -> String {
            let bytes = pick(self.parsed());
            // View into self.href — caller must consume before deinit (Zig parity).
            String::from_bytes(bytes)
        }

        pub fn from_string(str: &String) -> Option<NonNull<URL>> {
            let utf8 = str.to_utf8();
            let bytes = utf8.slice();
            Self::from_utf8(bytes)
        }

        pub fn from_utf8(input: &[u8]) -> Option<NonNull<URL>> {
            if input.is_empty() {
                return None;
            }
            let parsed = super::URL::parse(input);
            // Require a protocol (same gate as `href_from_string`).
            if parsed.protocol.is_empty() {
                return None;
            }
            let owned = Box::new(URL {
                href: input.to_vec().into_boxed_slice(),
            });
            // SAFETY: freshly allocated; unique owner until deinit.
            Some(unsafe { NonNull::new_unchecked(Box::into_raw(owned)) })
        }

        /// Includes the leading '#'.
        pub fn hash(&self) -> String {
            self.component_string(|u| u.hash)
        }
        /// Exactly the same as `hash`, excluding the leading '#'.
        pub fn fragment_identifier(&self) -> String {
            self.component_string(|u| {
                if u.hash.starts_with(b"#") {
                    &u.hash[1..]
                } else {
                    u.hash
                }
            })
        }
        pub fn protocol(&self) -> String {
            // Zig/WTF returns scheme with trailing ':'.
            let p = self.parsed().protocol;
            if p.is_empty() {
                return String::empty();
            }
            let mut buf = Vec::with_capacity(p.len() + 1);
            buf.extend_from_slice(p);
            buf.push(b':');
            string_from_owned_bytes(buf)
        }
        pub fn href(&self) -> String {
            String::from_bytes(&self.href)
        }
        pub fn username(&self) -> String {
            self.component_string(|u| u.username)
        }
        pub fn password(&self) -> String {
            self.component_string(|u| u.password)
        }
        pub fn search(&self) -> String {
            self.component_string(|u| u.search)
        }
        /// Host WITHOUT the port (Bun naming; opposite of JS `host`).
        pub fn host(&self) -> String {
            self.component_string(|u| u.hostname)
        }
        /// Host WITH the port (Bun naming; opposite of JS `hostname`).
        pub fn hostname(&self) -> String {
            self.component_string(|u| u.host)
        }
        /// Returns `u32::MAX` if the port is not set. Otherwise, the result is
        /// guaranteed to be within the `u16` range.
        pub fn port(&self) -> u32 {
            let p = self.parsed().port;
            if p.is_empty() {
                return u32::MAX;
            }
            bun_core::fmt::parse_int::<u16>(p, 10)
                .map(|v| v as u32)
                .unwrap_or(u32::MAX)
        }
        pub fn pathname(&self) -> String {
            self.component_string(|u| u.pathname)
        }
        /// Frees the heap URL. Must be called exactly once per successful
        /// `from_string` / `from_utf8`. After this, the pointer is dangling.
        pub fn deinit(&mut self) {
            // SAFETY: `self` is the unique owner produced by `Box::into_raw`.
            unsafe {
                drop(Box::from_raw(self as *mut URL));
            }
        }
    }

    /// Leak-backed owned `String` for free-function return values that outlive
    /// a local buffer (no WTF heap on product path). Rare call sites only
    /// (file URL conversion / join).
    fn string_from_owned_bytes(bytes: Vec<u8>) -> String {
        if bytes.is_empty() {
            return String::empty();
        }
        let leaked: &'static [u8] = Box::leak(bytes.into_boxed_slice());
        String::static_(leaked)
    }

    /// Validates the URL and returns the href. If parsing fails, returns `Dead`.
    pub fn href_from_string(str: &String) -> String {
        let utf8 = str.to_utf8();
        let bytes = utf8.slice();
        if bytes.is_empty() {
            return String::dead();
        }
        let url = super::URL::parse(bytes);
        if url.protocol.is_empty() {
            return String::dead();
        }
        drop(utf8);
        *str
    }

    /// Resolves `relative` against `base` and returns the joined href.
    /// Returns `Dead` if base is invalid.
    pub fn join(base: &String, relative: &String) -> String {
        let base_utf8 = base.to_utf8();
        let base_bytes = base_utf8.slice();
        if base_bytes.is_empty() {
            return String::dead();
        }
        let base_url = super::URL::parse(base_bytes);
        if base_url.protocol.is_empty() {
            return String::dead();
        }
        let rel_utf8 = relative.to_utf8();
        let rel_bytes = rel_utf8.slice();
        if rel_bytes.is_empty() {
            return *base;
        }
        // Absolute URL — return as-is
        let rel_url = super::URL::parse(rel_bytes);
        if !rel_url.protocol.is_empty() {
            return *relative;
        }
        // Resolve relative against base origin
        let origin = base_url.origin;
        let mut buf: Vec<u8> = Vec::with_capacity(origin.len() + 1 + rel_bytes.len());
        buf.extend_from_slice(origin);
        if !rel_bytes.starts_with(b"/") {
            let dir = base_url.pathname;
            let dir_end = dir.iter().rposition(|&c| c == b'/').map_or(0, |i| i + 1);
            buf.extend_from_slice(&dir[..dir_end]);
        }
        buf.extend_from_slice(rel_bytes);
        string_from_owned_bytes(buf)
    }

    /// `path` → `file://…` (absolute paths get a leading `/` after the scheme).
    pub fn file_url_from_string(str: &String) -> String {
        let utf8 = str.to_utf8();
        let path = utf8.slice();
        if path.is_empty() {
            return String::dead();
        }
        // Already a file URL — return as-is.
        if path.starts_with(b"file:") {
            return *str;
        }
        let mut buf: Vec<u8> = Vec::with_capacity(path.len() + 8);
        buf.extend_from_slice(b"file://");
        if !path.starts_with(b"/") {
            buf.push(b'/');
        }
        // Percent-encode only the characters WHATWG requires for path segments.
        for &c in path {
            match c {
                b'%' | b'?' | b'#' | b' ' | 0x00..=0x1f | 0x7f..=0xff => {
                    const HEX: &[u8; 16] = b"0123456789ABCDEF";
                    buf.push(b'%');
                    buf.push(HEX[(c >> 4) as usize]);
                    buf.push(HEX[(c & 0xf) as usize]);
                }
                _ => buf.push(c),
            }
        }
        string_from_owned_bytes(buf)
    }

    /// `file://host/path` → `/path` (host stripped; percent sequences kept).
    pub fn path_from_file_url(str: &String) -> String {
        let utf8 = str.to_utf8();
        let s = utf8.slice();
        let rest = if let Some(r) = s.strip_prefix(b"file://") {
            r
        } else if let Some(r) = s.strip_prefix(b"file:") {
            r
        } else {
            return String::dead();
        };
        // `file:///path` → path starts at first `/`
        // `file://localhost/path` → skip host
        // `file:/path` → already path-like
        let path = if rest.starts_with(b"/") {
            rest
        } else if let Some(idx) = rest.iter().position(|&c| c == b'/') {
            &rest[idx..]
        } else if rest.is_empty() {
            b"/"
        } else {
            // No slash after host — treat whole remainder as path with leading /
            return string_from_owned_bytes({
                let mut v = Vec::with_capacity(rest.len() + 1);
                v.push(b'/');
                v.extend_from_slice(rest);
                v
            });
        };
        string_from_owned_bytes(path.to_vec())
    }

    /// Returns the origin (`scheme://host[:port]`) prefix of `slice` as a borrowed
    /// subslice, or `None` if `slice` does not parse as a valid URL with protocol.
    #[inline]
    pub fn origin_from_slice(slice: &[u8]) -> Option<&[u8]> {
        let url = super::URL::parse(slice);
        if url.protocol.is_empty() || url.origin.is_empty() {
            return None;
        }
        // origin is a subslice of `slice` (parser only re-slices the input).
        Some(url.origin)
    }
}
// Re-export the free helpers at crate root so lower-tier callers can write
// `bun_url::join(...)` / `bun_url::href_from_string(...)` (install, http, bake, js_parser).
pub use whatwg::{
    file_url_from_string, href_from_string, join, origin_from_slice, path_from_file_url,
};

// PORT NOTE: URL is a pure view struct — every field is a slice into `href` (or a
// literal default). Zig expresses this with `[]const u8` fields borrowing the
// caller-provided `base`.
#[derive(Clone)]
pub struct URL<'a> {
    pub hash: &'a [u8],
    /// hostname, but with a port — `localhost:3000`
    pub host: &'a [u8],
    /// hostname does not have a port — `localhost`
    pub hostname: &'a [u8],
    pub href: &'a [u8],
    pub origin: &'a [u8],
    pub password: &'a [u8],
    pub pathname: &'a [u8],
    pub path: &'a [u8],
    pub port: &'a [u8],
    pub protocol: &'a [u8],
    pub search: &'a [u8],
    pub search_params: Option<QueryStringMap>,
    pub username: &'a [u8],
    pub port_was_automatically_set: bool,
}

impl<'a> Default for URL<'a> {
    fn default() -> Self {
        Self {
            hash: b"",
            host: b"",
            hostname: b"",
            href: b"",
            origin: b"",
            password: b"",
            pathname: b"/",
            path: b"/",
            port: b"",
            protocol: b"",
            search: b"",
            search_params: None,
            username: b"",
            port_was_automatically_set: false,
        }
    }
}

/// An owning URL — holds the normalized `href` buffer that the borrowed
/// `URL<'_>` view slices into. Port of `URL.fromString`'s ownership model:
/// Zig returned a `URL` borrowing from a fresh allocation the caller had to
/// `allocator.free(url.href)`; in Rust, `OwnedURL` owns that buffer and
/// `Drop` frees it.
#[derive(Default, Clone)]
pub struct OwnedURL {
    href: Box<[u8]>,
}

impl OwnedURL {
    /// Borrow as a parsed `URL` view. All slices in the returned `URL` borrow
    /// `self.href`.
    // PERF(port): re-parses on each call. Zig parsed once into a borrowing
    // struct the caller held alongside the buffer; Rust cannot express that
    // self-reference without unsafe lifetime extension (PORTING.md §Forbidden).
    // Callers in practice call this once and hold the borrow — if this shows
    // up on a hot path, store component `(u32, u32)` offsets here instead.
    #[inline]
    pub fn url(&self) -> URL<'_> {
        URL::parse(&self.href)
    }
    #[inline]
    pub fn href(&self) -> &[u8] {
        &self.href
    }
    #[inline]
    pub fn into_href(self) -> Box<[u8]> {
        self.href
    }
    /// Construct from an already-normalized href buffer (the tail of
    /// `URL::from_string` after `to_owned_slice`). Exposed so out-of-crate
    /// producers can build an `OwnedURL` without the `href` field being
    /// public.
    #[inline]
    pub fn from_href(href: Box<[u8]>) -> Self {
        Self { href }
    }
}

impl<'a> URL<'a> {
    /// Detach the borrow-checker lifetime from a `URL`.
    ///
    /// Centralized helper for the self-referential pattern where a `URL`
    /// borrows from a buffer that the caller is about to move into a sibling
    /// field on the same struct (e.g. `self.url = URL::parse(&buf);
    /// self.redirect = buf;`). All slices in `URL` are `(ptr, len)` views, so
    /// the value is bitwise unchanged — only the borrow-checker tag widens.
    ///
    /// # Safety
    /// Caller must guarantee every slice the returned `URL<'b>` references
    /// outlives `'b`. The buffer must NOT be dropped, reallocated, or mutated
    /// for the lifetime of the returned value.
    #[inline(always)]
    #[allow(unsafe_op_in_unsafe_fn)]
    pub unsafe fn erase_lifetime<'b>(self) -> URL<'b> {
        // Field-by-field reconstruction — every slice is `(ptr, len)`, so the
        // value is bitwise unchanged; only the borrow-checker tag widens.
        // `d` stays `unsafe fn` so a safe-signature wrapper does not hide the
        // lifetime-widen; the outer fn carries `#[allow(unsafe_op_in_unsafe_fn)]`
        // so the dozen call sites below need no per-line `unsafe { }`.
        #[inline(always)]
        unsafe fn d<'b>(s: &[u8]) -> &'b [u8] {
            // SAFETY: caller contract on `erase_lifetime` — every slice the
            // returned `URL<'b>` references outlives `'b`.
            unsafe { &*core::ptr::from_ref::<[u8]>(s) }
        }
        URL {
            hash: d(self.hash),
            host: d(self.host),
            hostname: d(self.hostname),
            href: d(self.href),
            origin: d(self.origin),
            password: d(self.password),
            pathname: d(self.pathname),
            path: d(self.path),
            port: d(self.port),
            protocol: d(self.protocol),
            search: d(self.search),
            search_params: self.search_params,
            username: d(self.username),
            port_was_automatically_set: self.port_was_automatically_set,
        }
    }

    pub fn is_file(&self) -> bool {
        self.protocol == b"file"
    }

    /// host + path without the ending slash, protocol, searchParams and hash
    pub fn host_with_path(&self) -> &'a [u8] {
        if !self.host.is_empty() {
            if self.path.len() > 1
                && bun_alloc::is_slice_in_buffer(self.path, self.href)
                && bun_alloc::is_slice_in_buffer(self.host, self.href)
            {
                let end = self.path.as_ptr() as usize + self.path.len();
                let start = self.host.as_ptr() as usize;
                let len: usize = end
                    - start
                    - (if self.path.ends_with(b"/") {
                        1usize
                    } else {
                        0usize
                    });
                let ptr = start as *const u8;
                // SAFETY: start..end is a subrange of self.href (both slices verified above)
                return unsafe { core::slice::from_raw_parts(ptr, len) };
            }
            return self.host;
        }
        b""
    }

    /// `"blob:".len + UUID.stringLength` — see `runtime/webcore/ObjectURLRegistry.specifier_len`.
    const BLOB_SPECIFIER_LEN: usize = b"blob:".len() + 36;

    pub fn is_blob(&self) -> bool {
        self.href.len() == Self::BLOB_SPECIFIER_LEN && self.href.starts_with(b"blob:")
    }

    // PORT NOTE: ownership — Zig returns a `URL` borrowing from a freshly-allocated
    // owned slice (`href.toOwnedSlice`); caller frees `url.href` later. Per
    // PORTING.md §Forbidden (no Box::leak / mem::forget / unsafe lifetime
    // extension), Rust returns an `OwnedURL` that owns the buffer; callers borrow
    // via `.url()` and Drop frees it.
    pub fn from_string(input: &BunString) -> Result<OwnedURL, bun_core::Error> {
        let href = whatwg::href_from_string(input);
        if href.tag() == BunStringTag::Dead {
            return Err(bun_core::err!("InvalidURL"));
        }
        // Zig: `defer href.deref()` — `to_owned_slice` is infallible so explicit
        // ordering suffices (no error path between alloc and deref).
        let owned = href.to_owned_slice().into_boxed_slice();
        href.deref();
        Ok(OwnedURL { href: owned })
    }

    pub fn from_utf8(input: &[u8]) -> Result<OwnedURL, bun_core::Error> {
        Self::from_string(&BunString::borrow_utf8(input))
    }

    pub fn is_localhost(&self) -> bool {
        self.hostname.is_empty() || self.hostname == b"localhost" || self.hostname == b"0.0.0.0"
    }

    #[inline]
    pub fn is_unix(&self) -> bool {
        self.protocol.starts_with(b"unix")
    }

    pub fn display_protocol(&self) -> &[u8] {
        if !self.protocol.is_empty() {
            return self.protocol;
        }

        if let Some(port) = self.get_port() {
            if port == 443 {
                return b"https";
            }
        }

        b"http"
    }

    #[inline]
    pub fn is_https(&self) -> bool {
        self.protocol == b"https"
    }
    #[inline]
    pub fn is_s3(&self) -> bool {
        self.protocol == b"s3"
    }
    #[inline]
    pub fn is_http(&self) -> bool {
        self.protocol == b"http"
    }

    pub fn display_hostname(&self) -> &[u8] {
        if !self.hostname.is_empty() {
            self.hostname
        } else {
            b"localhost"
        }
    }

    pub fn s3_path(&self) -> &'a [u8] {
        if !self.protocol.is_empty() && self.href.len() > self.protocol.len() + 2 {
            &self.href[self.protocol.len() + 2..]
        } else {
            self.href
        }
    }

    pub fn display_host(&self) -> bun_fmt::HostFormatter<'_> {
        bun_fmt::HostFormatter {
            host: if !self.host.is_empty() {
                self.host
            } else {
                self.display_hostname()
            },
            port: if !self.port.is_empty() {
                self.get_port()
            } else {
                None
            },
            is_https: self.is_https(),
        }
    }

    /// Zig: `std.fmt.allocPrint(alloc, "{s}://{f}/{s}/", .{
    ///     url.displayProtocol(), url.displayHost(),
    ///     std.mem.trim(u8, url.pathname, "/") })`.
    ///
    /// `display_host()` yields a `bun_core::fmt::HostFormatter` (impls
    /// `Display`); the other two pieces are raw byte slices, so we assemble
    /// into a `Vec<u8>` directly rather than going through `format!` and
    /// risking lossy UTF-8 round-trips.
    pub fn href_without_auth(&self) -> Box<[u8]> {
        let proto = self.display_protocol();
        let path = strings::trim(self.pathname, b"/");

        let mut buf: Vec<u8> =
            Vec::with_capacity(proto.len() + 3 + self.host.len() + 1 + path.len() + 1);
        buf.extend_from_slice(proto);
        buf.extend_from_slice(b"://");
        // bun_core::io::Write on Vec<u8> is infallible.
        let _ = buf.print(format_args!("{}", self.display_host()));
        buf.push(b'/');
        buf.extend_from_slice(path);
        buf.push(b'/');
        buf.into_boxed_slice()
    }

    pub fn has_http_like_protocol(&self) -> bool {
        self.protocol == b"http" || self.protocol == b"https"
    }

    pub fn get_port(&self) -> Option<u16> {
        bun_core::fmt::parse_int::<u16>(self.port, 10).ok()
    }

    pub fn get_port_auto(&self) -> u16 {
        self.get_port().unwrap_or_else(|| self.get_default_port())
    }

    pub fn get_default_port(&self) -> u16 {
        if self.is_https() { 443u16 } else { 80u16 }
    }

    pub fn is_ip_address(&self) -> bool {
        strings::is_ip_address(self.hostname)
    }

    pub fn has_valid_port(&self) -> bool {
        self.get_port().unwrap_or(0) > 0
    }

    pub fn is_empty(&self) -> bool {
        self.href.is_empty()
    }

    pub fn is_absolute(&self) -> bool {
        !self.hostname.is_empty() && !self.pathname.is_empty()
    }

    pub fn join_normalize<'b>(
        out: &'b mut [u8],
        prefix: &[u8],
        dirname: &[u8],
        basename: &[u8],
        extname: &[u8],
    ) -> &'b [u8] {
        let mut buf = [0u8; 2048];

        let mut path_parts: [&[u8]; 10] = [b""; 10];
        let mut path_end: usize = 0;

        path_parts[0] = b"/";
        path_end += 1;

        if !prefix.is_empty() {
            path_parts[path_end] = prefix;
            path_end += 1;
        }

        if !dirname.is_empty() {
            path_parts[path_end] = strings::trim(dirname, b"/\\");
            path_end += 1;
        }

        if !basename.is_empty() {
            if !dirname.is_empty() {
                path_parts[path_end] = b"/";
                path_end += 1;
            }

            path_parts[path_end] = strings::trim(basename, b"/\\");
            path_end += 1;
        }

        if !extname.is_empty() {
            path_parts[path_end] = extname;
            path_end += 1;
        }

        let mut buf_i: usize = 0;
        for part in &path_parts[0..path_end] {
            buf[buf_i..buf_i + part.len()].copy_from_slice(part);
            buf_i += part.len();
        }
        // Zig: resolve_path.normalizeStringBuf(buf[0..buf_i], out, false, .loose, false)
        resolve_path::normalize_string_buf::<false, platform::Loose, false>(&buf[0..buf_i], out)
    }

    pub fn join_write(
        &self,
        writer: &mut impl bun_core::io::Write,
        prefix: &[u8],
        dirname: &[u8],
        basename: &[u8],
        extname: &[u8],
    ) -> Result<(), bun_core::Error> {
        // TODO(port): narrow error set
        let mut out = [0u8; 2048];
        let normalized_path = Self::join_normalize(&mut out, prefix, dirname, basename, extname);

        // Zig: writer.print("{s}/{s}", .{ this.origin, normalized_path })
        writer.write_all(self.origin)?;
        writer.write_all(b"/")?;
        writer.write_all(normalized_path)?;
        Ok(())
    }

    pub fn join_alloc(
        &self,
        prefix: &[u8],
        dirname: &[u8],
        basename: &[u8],
        extname: &[u8],
        absolute_path: &[u8],
    ) -> Result<Box<[u8]>, bun_core::Error> {
        // TODO(port): narrow error set
        let has_uplevels = strings::index_of(dirname, b"../").is_some();

        if has_uplevels {
            // std.fmt.allocPrint("{s}/abs:{s}")
            let mut v = Vec::with_capacity(self.origin.len() + 5 + absolute_path.len());
            v.extend_from_slice(self.origin);
            v.extend_from_slice(b"/abs:");
            v.extend_from_slice(absolute_path);
            Ok(v.into_boxed_slice())
        } else {
            let mut out = [0u8; 2048];
            let normalized_path =
                Self::join_normalize(&mut out, prefix, dirname, basename, extname);
            let mut v = Vec::with_capacity(self.origin.len() + 1 + normalized_path.len());
            v.extend_from_slice(self.origin);
            v.extend_from_slice(b"/");
            v.extend_from_slice(normalized_path);
            Ok(v.into_boxed_slice())
        }
    }

    pub fn parse(base: &'a [u8]) -> URL<'a> {
        if base.is_empty() {
            return URL::default();
        }
        let mut url = URL {
            href: base,
            ..Default::default()
        };
        // PORT NOTE: Zig uses u31; Rust has no u31 — using u32 (values never approach 2^31).
        let mut offset: u32 = 0;
        match base[0] {
            b'@' => {
                offset += url.parse_password(&base[offset as usize..]).unwrap_or(0);
                offset += url.parse_host(&base[offset as usize..]).unwrap_or(0);
            }
            // Bare bracketed IPv6 host, e.g. the `[::1]:4873/` left of an .npmrc
            // `//[::1]:4873/:_authToken` key once its `//` is stripped.
            b'[' => {
                offset += url.parse_host(base).unwrap_or(0);
            }
            b'/' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b':' => {
                let is_protocol_relative = base.len() > 1 && base[1] == b'/';
                if is_protocol_relative {
                    offset += 1;
                } else {
                    offset += url.parse_protocol(&base[offset as usize..]).unwrap_or(0);
                }

                let is_relative_path = !is_protocol_relative && base[0] == b'/';

                if !is_relative_path {
                    // if there's no protocol or @, it's ambiguous whether the colon is a port or a username.
                    if offset > 0 {
                        // see https://github.com/oven-sh/bun/issues/1390
                        let first_at =
                            strings::index_of_char(&base[offset as usize..], b'@').unwrap_or(0);
                        let first_colon =
                            strings::index_of_char(&base[offset as usize..], b':').unwrap_or(0);

                        if first_at > first_colon
                            && first_at
                                < strings::index_of_char(&base[offset as usize..], b'/')
                                    .unwrap_or(u32::MAX)
                        {
                            offset += url.parse_username(&base[offset as usize..]).unwrap_or(0);
                            offset += url.parse_password(&base[offset as usize..]).unwrap_or(0);
                        }
                    }

                    offset += url.parse_host(&base[offset as usize..]).unwrap_or(0);
                }
            }
            _ => {}
        }

        url.origin = &base[0..offset as usize];
        let mut hash_offset: u32 = u32::MAX;

        if offset as usize > base.len() {
            return url;
        }

        let path_offset = offset;

        let mut can_update_path = true;
        if base.len() > offset as usize + 1
            && base[offset as usize] == b'/'
            && !base[offset as usize..].is_empty()
        {
            url.path = &base[offset as usize..];
            url.pathname = url.path;
        }

        if let Some(q) = strings::index_of_char(&base[offset as usize..], b'?') {
            offset += q;
            url.path = &base[path_offset as usize..][0..q as usize];
            can_update_path = false;
            url.search = &base[offset as usize..];
        }

        if let Some(hash) = strings::index_of_char(&base[offset as usize..], b'#') {
            offset += hash;
            hash_offset = offset;
            if can_update_path {
                url.path = &base[path_offset as usize..][0..hash as usize];
            }
            url.hash = &base[offset as usize..];

            if !url.search.is_empty() {
                url.search = &url.search[0..url.search.len() - url.hash.len()];
            }
        }

        if base.len() > path_offset as usize && base[path_offset as usize] == b'/' && offset > 0 {
            if !url.search.is_empty() {
                url.pathname = &base[path_offset as usize
                    ..((offset as usize + url.search.len()).min(base.len()))
                        .min(hash_offset as usize)];
            } else if hash_offset < u32::MAX {
                url.pathname = &base[path_offset as usize..hash_offset as usize];
            }

            url.origin = &base[0..path_offset as usize];
        }

        if url.path.len() > 1 {
            let trimmed = strings::trim(url.path, b"/");
            if trimmed.len() > 1 {
                let ptr_diff = (trimmed.as_ptr() as usize) - (url.path.as_ptr() as usize);
                let start = (ptr_diff.max(1) - 1).min(hash_offset as usize);
                url.path = &url.path[start..];
            } else {
                url.path = b"/";
            }
        } else {
            url.path = b"/";
        }

        if url.pathname.is_empty() {
            url.pathname = b"/";
        }

        const SLASH_SLASH: u16 = u16::from_le_bytes(*b"//");
        while url.pathname.len() > 1
            && u16::from_le_bytes([url.pathname[0], url.pathname[1]]) == SLASH_SLASH
        {
            url.pathname = &url.pathname[1..];
        }

        url.origin = strings::trim(url.origin, b"/ ?#");
        url
    }

    pub fn parse_protocol(&mut self, str: &'a [u8]) -> Option<u32> {
        if str.len() < b"://".len() {
            return None;
        }
        for i in 0..str.len() {
            match str[i] {
                b'/' | b'?' | b'%' => {
                    return None;
                }
                b':' => {
                    if i + 3 <= str.len() && str[i + 1] == b'/' && str[i + 2] == b'/' {
                        self.protocol = &str[0..i];
                        return Some(u32::try_from(i + 3).expect("int cast"));
                    }
                }
                _ => {}
            }
        }

        None
    }

    pub fn parse_username(&mut self, str: &'a [u8]) -> Option<u32> {
        // reset it
        self.username = b"";

        if str.len() < b"@".len() {
            return None;
        }
        for i in 0..str.len() {
            match str[i] {
                b':' | b'@' => {
                    // we found a username, everything before this point in the slice is a username
                    self.username = &str[0..i];
                    return Some(u32::try_from(i + 1).expect("int cast"));
                }
                // if we reach a slash or "?", there's no username
                b'?' | b'/' => {
                    return None;
                }
                _ => {}
            }
        }
        None
    }

    pub fn parse_password(&mut self, str: &'a [u8]) -> Option<u32> {
        // reset it
        self.password = b"";

        if str.len() < b"@".len() {
            return None;
        }
        for i in 0..str.len() {
            match str[i] {
                b'@' => {
                    // we found a password, everything before this point in the slice is a password
                    self.password = &str[0..i];
                    if cfg!(debug_assertions) {
                        debug_assert!(
                            str[i..].len() < 2
                                || u16::from_le_bytes([str[i], str[i + 1]])
                                    != u16::from_le_bytes(*b"//")
                        );
                    }
                    return Some(u32::try_from(i + 1).expect("int cast"));
                }
                // if we reach a slash or "?", there's no password
                b'?' | b'/' => {
                    return None;
                }
                _ => {}
            }
        }
        None
    }

    pub fn parse_host(&mut self, str: &'a [u8]) -> Option<u32> {
        let mut i: u32 = 0;

        // reset it
        self.host = b"";
        self.hostname = b"";
        self.port = b"";

        // if starts with "[" so its IPV6
        if !str.is_empty() && str[0] == b'[' {
            i = 1;
            let mut ipv6_i: Option<u32> = None;
            let mut colon_i: Option<u32> = None;

            while (i as usize) < str.len() {
                ipv6_i = if ipv6_i.is_none() && str[i as usize] == b']' {
                    Some(i)
                } else {
                    ipv6_i
                };
                colon_i = if ipv6_i.is_some() && colon_i.is_none() && str[i as usize] == b':' {
                    Some(i)
                } else {
                    colon_i
                };
                match str[i as usize] {
                    // alright, we found the slash or "?"
                    b'?' | b'/' => {
                        break;
                    }
                    _ => {}
                }
                i += 1;
            }

            self.host = &str[0..i as usize];
            if let Some(ipv6) = ipv6_i {
                // hostname includes "[" and "]"
                self.hostname = &str[0..ipv6 as usize + 1];
            }

            if let Some(colon) = colon_i {
                self.port = &str[colon as usize + 1..i as usize];
            }
        } else {
            // look for the first "/" or "?"
            // if we have a slash or "?", anything before that is the host
            // anything before the colon is the hostname
            // anything after the colon but before the slash is the port
            // the origin is the scheme before the slash

            let mut colon_i: Option<u32> = None;
            while (i as usize) < str.len() {
                colon_i = if colon_i.is_none() && str[i as usize] == b':' {
                    Some(i)
                } else {
                    colon_i
                };

                match str[i as usize] {
                    // alright, we found the slash or "?"
                    b'?' | b'/' => {
                        break;
                    }
                    _ => {}
                }
                i += 1;
            }

            self.host = &str[0..i as usize];
            if let Some(colon) = colon_i {
                self.hostname = &str[0..colon as usize];
                self.port = &str[colon as usize + 1..i as usize];
            } else {
                self.hostname = &str[0..i as usize];
            }
        }

        Some(i)
    }
}

// ══════════════════════════════════════════════════════════════════════════
// QueryStringMap & friends
// ══════════════════════════════════════════════════════════════════════════

#[derive(Clone, Copy)]
pub struct Param {
    pub name: api::StringPointer,
    pub name_hash: u64,
    pub value: api::StringPointer,
}

// PERF(port): Zig uses `std.MultiArrayList(Param)` for SoA cache-friendly column
// scans. bun_collections::MultiArrayList exists but requires `MultiArrayElement`
// (no derive macro yet). Using Vec<Param> (AoS) for now — semantically identical;
// revisit once `` lands.
// TODO(port): bun_collections::MultiArrayList derive
pub(crate) type ParamList = Vec<Param>;

/// QueryString array-backed hash table that does few allocations and preserves the original order
pub struct QueryStringMap {
    // PORT NOTE: allocator field dropped — global mimalloc per PORTING.md.
    // TODO(port): `slice` is self-referential (points into `buffer`) when decoding
    // happened, otherwise borrows the caller's query_string. Stored as raw fat ptr.
    slice: *const [u8],
    pub buffer: Vec<u8>,
    pub list: ParamList,
    pub name_count: Option<usize>,
}

impl Clone for QueryStringMap {
    fn clone(&self) -> Self {
        let buffer = self.buffer.clone();
        // Re-derive `slice` so the clone doesn't dangle into the original buffer.
        // If the original `slice` did NOT point into our own buffer (the
        // nothing-needs-decoding fast path borrows the caller's query_string),
        // keep it as-is — both clones borrow the same external slice.
        // SAFETY: `self.slice` is valid for the lifetime of `self` — it either points
        // into `self.buffer` (decoding path) or borrows an external query_string the
        // caller keeps alive (nothing-needs-decoding fast path).
        let self_slice = unsafe { &*self.slice };
        let slice =
            if !self.buffer.is_empty() && bun_alloc::is_slice_in_buffer(self_slice, &self.buffer) {
                let len = self_slice.len();
                &raw const buffer[..len]
            } else {
                self.slice
            };
        Self {
            slice,
            buffer,
            list: self.list.clone(),
            name_count: self.name_count,
        }
    }
}

thread_local! {
    // PORT NOTE: unused in current code (commented-out path in get_name_count)
    static NAME_COUNT_BUF: RefCell<[*const [u8]; 8]> = const { RefCell::new([std::ptr::from_ref::<[u8]>(&[]); 8]) };
}

impl QueryStringMap {
    pub fn get_name_count(&mut self) -> usize {
        self.list.len()
        // if (this.name_count == null) {
        //     var count: usize = 0;
        //     var iterate = this.iter();
        //     while (iterate.next(&_name_count) != null) {
        //         count += 1;
        //     }
        //     this.name_count = count;
        // }
        // return this.name_count.?;
    }

    pub fn iter(&self) -> Iterator<'_> {
        Iterator::init(self)
    }

    pub fn str(&self, ptr: api::StringPointer) -> &[u8] {
        // SAFETY: `slice` is valid for the lifetime of `self` (either borrows
        // `self.buffer` or an external query_string the caller keeps alive).
        let slice = unsafe { &*self.slice };
        &slice[ptr.offset as usize..ptr.offset as usize + ptr.length as usize]
    }

    pub fn get_index(&self, input: &[u8]) -> Option<usize> {
        let hash = wyhash(input);
        self.list.iter().position(|p| p.name_hash == hash)
    }

    pub fn get(&self, input: &[u8]) -> Option<&[u8]> {
        let hash = wyhash(input);
        let i = self.list.iter().position(|p| p.name_hash == hash)?;
        Some(self.str(self.list[i].value))
    }

    pub fn has(&self, input: &[u8]) -> bool {
        self.get_index(input).is_some()
    }

    pub fn get_all<'s>(&'s self, input: &[u8], target: &mut [&'s [u8]]) -> usize {
        let hash = wyhash(input);
        // PERF(port): was @call(bun.callmod_inline, ...) — profile if hot.
        self.get_all_with_hash_from_offset(target, hash, 0)
    }

    pub fn get_all_with_hash_from_offset<'s>(
        &'s self,
        target: &mut [&'s [u8]],
        hash: u64,
        offset: usize,
    ) -> usize {
        let mut remainder = &self.list[offset..];
        let mut target_i: usize = 0;
        while !remainder.is_empty() && target_i < target.len() {
            let Some(i) = remainder.iter().position(|p| p.name_hash == hash) else {
                break;
            };
            target[target_i] = self.str(remainder[i].value);
            remainder = &remainder[i + 1..];
            target_i += 1;
        }
        target_i
    }

    pub fn init_with_scanner(
        mut scanner: CombinedScanner<'_>,
    ) -> Result<Option<QueryStringMap>, bun_alloc::AllocError> {
        let mut list = ParamList::default();

        let mut estimated_str_len: usize = 0;
        let mut count: usize = 0;

        let mut nothing_needs_decoding = true;

        while let Some(result) = scanner.pathname.next() {
            if result.name_needs_decoding || result.value_needs_decoding {
                nothing_needs_decoding = false;
            }
            estimated_str_len += result.name.length as usize + result.value.length as usize;
            count += 1;
        }

        debug_assert!(count > 0); // We should not call initWithScanner when there are no path params

        while count < MAX_QUERY_STRING_PARAMS {
            let Some(result) = scanner.query.next() else {
                break;
            };
            if result.name_needs_decoding || result.value_needs_decoding {
                nothing_needs_decoding = false;
            }
            estimated_str_len += result.name.length as usize + result.value.length as usize;
            count += 1;
        }

        if count == 0 {
            return Ok(None);
        }

        list.reserve(count.min(MAX_QUERY_STRING_PARAMS)); // PERF(port): was ensureTotalCapacity
        scanner.reset();

        // this over-allocates
        // TODO: refactor this to support multiple slices instead of copying the whole thing
        let mut buf: Vec<u8> = Vec::with_capacity(estimated_str_len);
        let mut buf_writer_pos: u32 = 0;

        while let Some(result) = scanner.pathname.next() {
            if list.len() >= MAX_QUERY_STRING_PARAMS {
                break;
            }
            let mut name = result.name;
            let mut value = result.value;
            let name_slice = result.raw_name(scanner.pathname.routename);

            name.length = u32::try_from(name_slice.len()).unwrap();
            name.offset = buf_writer_pos;
            buf.extend_from_slice(name_slice);
            buf_writer_pos += u32::try_from(name_slice.len()).unwrap();

            let name_hash: u64 = wyhash(name_slice);

            value.length = match PercentEncoding::decode(
                &mut buf,
                result.raw_value(scanner.pathname.pathname),
            ) {
                Ok(n) => n,
                Err(_) => continue,
            };
            value.offset = buf_writer_pos;
            buf_writer_pos += value.length;

            // PERF(port): was appendAssumeCapacity
            list.push(Param {
                name,
                value,
                name_hash,
            });
        }

        let route_parameter_begin = list.len();

        while let Some(result) = scanner.query.next() {
            if list.len() >= MAX_QUERY_STRING_PARAMS {
                break;
            }
            let mut name = result.name;
            let mut value = result.value;
            let name_hash: u64;
            if result.name_needs_decoding {
                name.length = match PercentEncoding::decode(
                    &mut buf,
                    &scanner.query.query_string[name.offset as usize..][..name.length as usize],
                ) {
                    Ok(n) => n,
                    Err(_) => continue,
                };
                name.offset = buf_writer_pos;
                buf_writer_pos += name.length;
                name_hash = wyhash(&buf[name.offset as usize..][..name.length as usize]);
            } else {
                name_hash = wyhash(result.raw_name(scanner.query.query_string));
                if let Some(index) = list.iter().position(|p| p.name_hash == name_hash) {
                    // query string parameters should not override route parameters
                    // see https://nextjs.org/docs/routing/dynamic-routes
                    if index < route_parameter_begin {
                        continue;
                    }

                    name = list[index].name;
                } else {
                    name.length = match PercentEncoding::decode(
                        &mut buf,
                        &scanner.query.query_string[name.offset as usize..][..name.length as usize],
                    ) {
                        Ok(n) => n,
                        Err(_) => continue,
                    };
                    name.offset = buf_writer_pos;
                    buf_writer_pos += name.length;
                }
            }

            value.length = match PercentEncoding::decode(
                &mut buf,
                &scanner.query.query_string[value.offset as usize..][..value.length as usize],
            ) {
                Ok(n) => n,
                Err(_) => continue,
            };
            value.offset = buf_writer_pos;
            buf_writer_pos += value.length;

            // PERF(port): was appendAssumeCapacity
            list.push(Param {
                name,
                value,
                name_hash,
            });
        }

        // buf.expandToCapacity() — Vec doesn't expose this; not needed since we slice by buf_writer_pos
        let _ = nothing_needs_decoding;
        let slice_ptr: *const [u8] = &raw const buf[0..buf_writer_pos as usize];
        Ok(Some(QueryStringMap {
            list,
            buffer: buf,
            slice: slice_ptr,
            name_count: None,
        }))
    }

    pub fn init(query_string: &[u8]) -> Result<Option<QueryStringMap>, bun_alloc::AllocError> {
        let mut list = ParamList::default();

        let mut scanner = Scanner::init(query_string);
        let mut count: usize = 0;
        let mut estimated_str_len: usize = 0;

        let mut nothing_needs_decoding = true;
        while count < MAX_QUERY_STRING_PARAMS {
            let Some(result) = scanner.next() else {
                break;
            };
            if result.name_needs_decoding || result.value_needs_decoding {
                nothing_needs_decoding = false;
            }
            estimated_str_len += result.name.length as usize + result.value.length as usize;
            count += 1;
        }

        if count == 0 {
            return Ok(None);
        }

        scanner = Scanner::init(query_string);
        list.reserve(count); // PERF(port): was ensureTotalCapacity

        if nothing_needs_decoding {
            scanner = Scanner::init(query_string);
            while let Some(result) = scanner.next() {
                if list.len() >= MAX_QUERY_STRING_PARAMS {
                    break;
                }
                debug_assert!(!result.name_needs_decoding);
                debug_assert!(!result.value_needs_decoding);

                let name = result.name;
                let value = result.value;
                let name_hash: u64 = wyhash(result.raw_name(query_string));
                // PERF(port): was appendAssumeCapacity
                list.push(Param {
                    name,
                    value,
                    name_hash,
                });
            }

            return Ok(Some(QueryStringMap {
                list,
                buffer: Vec::new(),
                // TODO(port): borrows external query_string; lifetime not tracked here
                slice: std::ptr::from_ref::<[u8]>(query_string),
                name_count: None,
            }));
        }

        let mut buf: Vec<u8> = Vec::with_capacity(estimated_str_len);
        let mut buf_writer_pos: u32 = 0;

        // PORT NOTE: reshaped for borrowck — Zig captured `list.slice()` once outside
        // the loop; here we re-slice per iteration to avoid holding a borrow across push().
        while let Some(result) = scanner.next() {
            if list.len() >= MAX_QUERY_STRING_PARAMS {
                break;
            }
            let mut name = result.name;
            let mut value = result.value;
            let name_hash: u64;
            if result.name_needs_decoding {
                name.length = match PercentEncoding::decode(
                    &mut buf,
                    &query_string[name.offset as usize..][..name.length as usize],
                ) {
                    Ok(n) => n,
                    Err(_) => continue,
                };
                name.offset = buf_writer_pos;
                buf_writer_pos += name.length;
                name_hash = wyhash(&buf[name.offset as usize..][..name.length as usize]);
            } else {
                name_hash = wyhash(result.raw_name(query_string));
                if let Some(index) = list.iter().position(|p| p.name_hash == name_hash) {
                    name = list[index].name;
                } else {
                    name.length = match PercentEncoding::decode(
                        &mut buf,
                        &query_string[name.offset as usize..][..name.length as usize],
                    ) {
                        Ok(n) => n,
                        Err(_) => continue,
                    };
                    name.offset = buf_writer_pos;
                    buf_writer_pos += name.length;
                }
            }

            value.length = match PercentEncoding::decode(
                &mut buf,
                &query_string[value.offset as usize..][..value.length as usize],
            ) {
                Ok(n) => n,
                Err(_) => continue,
            };
            value.offset = buf_writer_pos;
            buf_writer_pos += value.length;

            // PERF(port): was appendAssumeCapacity
            list.push(Param {
                name,
                value,
                name_hash,
            });
        }

        let slice_ptr: *const [u8] = &raw const buf[0..buf_writer_pos as usize];
        Ok(Some(QueryStringMap {
            list,
            buffer: buf,
            slice: slice_ptr,
            name_count: None,
        }))
    }
}

// Browsers typically limit URL lengths to around 64k
// PORT NOTE: Zig `StaticBitSet(2048)` resolves to `ArrayBitSet(usize, 2048)`.
// bun_collections::StaticBitSet currently aliases IntegerBitSet (≤64 bits), so
// pick ArrayBitSet directly. 2048 / 64 == 32 masks.
/// Hard cap on parsed query-string parameters, enforced in `init` /
/// `init_with_scanner` so the fixed-size `VisitedMap` bitset is never indexed
/// out of bounds.
const MAX_QUERY_STRING_PARAMS: usize = 2048;
type VisitedMap = ArrayBitSet<MAX_QUERY_STRING_PARAMS, { num_masks_for(MAX_QUERY_STRING_PARAMS) }>;

pub struct Iterator<'a> {
    pub i: usize,
    pub map: &'a QueryStringMap,
    pub visited: VisitedMap,
}

pub struct IteratorResult<'a, 't> {
    pub name: &'a [u8],
    pub values: &'t mut [&'a [u8]],
}

impl<'a> Iterator<'a> {
    pub fn init(map: &'a QueryStringMap) -> Iterator<'a> {
        debug_assert!(map.list.len() <= MAX_QUERY_STRING_PARAMS);
        Iterator {
            i: 0,
            map,
            visited: VisitedMap::init_empty(),
        }
    }

    // TODO(port): lifetime on `target`/return — values borrow target, name borrows map.slice
    pub fn next<'t>(&mut self, target: &'t mut [&'a [u8]]) -> Option<IteratorResult<'a, 't>>
    where
        'a: 't,
    {
        while self.i < self.map.list.len() && self.visited.is_set(self.i) {
            self.i += 1;
        }
        if self.i >= self.map.list.len() {
            return None;
        }

        let list = &self.map.list;
        let hash = list[self.i].name_hash;
        let name_slice = list[self.i].name;
        debug_assert!(name_slice.length > 0);
        let name = self.map.str(name_slice);
        target[0] = self.map.str(list[self.i].value);

        self.visited.set(self.i);
        self.i += 1;

        let remainder = &list[self.i..];

        let mut target_i: usize = 1;
        let mut current_i: usize = 0;

        while let Some(next_index) = remainder[current_i..]
            .iter()
            .position(|p| p.name_hash == hash)
        {
            let real_i = current_i + next_index + self.i;
            if cfg!(debug_assertions) {
                debug_assert!(!self.visited.is_set(real_i));
            }

            self.visited.set(real_i);
            target[target_i] = self.map.str(remainder[current_i + next_index].value);
            target_i += 1;

            current_i += next_index + 1;
            if target_i >= target.len() {
                return Some(IteratorResult {
                    name,
                    values: &mut target[0..target_i],
                });
            }
            if real_i + 1 >= self.map.list.len() {
                return Some(IteratorResult {
                    name,
                    values: &mut target[0..target_i],
                });
            }
        }

        Some(IteratorResult {
            name,
            values: &mut target[0..target_i],
        })
    }
}

// ══════════════════════════════════════════════════════════════════════════
// PercentEncoding
// ══════════════════════════════════════════════════════════════════════════

pub struct PercentEncoding;

#[derive(Debug)]
pub enum DecodeError {
    DecodingError,
    Write(bun_core::Error),
}
impl From<bun_core::Error> for DecodeError {
    fn from(e: bun_core::Error) -> Self {
        DecodeError::Write(e)
    }
}
impl From<DecodeError> for bun_core::Error {
    fn from(e: DecodeError) -> Self {
        match e {
            DecodeError::DecodingError => bun_core::err!("DecodingError"),
            DecodeError::Write(inner) => inner,
        }
    }
}

impl PercentEncoding {
    pub fn decode(writer: &mut impl bun_core::io::Write, input: &[u8]) -> Result<u32, DecodeError> {
        // PERF(port): was @call(bun.callmod_inline, ...) — profile if hot.
        Self::decode_fault_tolerant::<_, false>(writer, input, None)
    }

    /// Decode percent-encoded input into allocated memory.
    /// Caller owns the returned slice.
    pub fn decode_alloc(input: &[u8]) -> Result<Box<[u8]>, DecodeError> {
        // Allocate enough space - decoded will be at most input.len bytes
        let mut buf: Vec<u8> = Vec::with_capacity(input.len());
        // errdefer allocator.free(buf) — Vec drops automatically on error

        // TODO(port): Zig used fixedBufferStream into a pre-sized [u8; input.len];
        // here we just write into a Vec and truncate.
        let len = Self::decode(&mut buf, input)?;

        buf.truncate(len as usize);
        Ok(buf.into_boxed_slice())
    }

    /// Decode percent-encoded `input` into the caller-provided `out` buffer.
    /// Returns number of bytes written. `out.len()` must be >= `input.len()`.
    pub fn decode_into(out: &mut [u8], input: &[u8]) -> Result<u32, DecodeError> {
        let mut w = bun_core::fmt::SliceCursor::new(out);
        Self::decode(&mut w, input)
    }

    pub fn decode_fault_tolerant<W: bun_core::io::Write, const FAULT_TOLERANT: bool>(
        writer: &mut W,
        input: &[u8],
        needs_redirect: Option<&mut bool>,
    ) -> Result<u32, DecodeError> {
        let mut needs_redirect = needs_redirect;
        let mut i: usize = 0;
        let mut written: u32 = 0;
        // unlike JavaScript's decodeURIComponent, we are not handling invalid surrogate pairs
        // we are assuming the input is valid ascii
        while i < input.len() {
            match input[i] {
                b'%' => {
                    if FAULT_TOLERANT {
                        if !(i + 3 <= input.len()
                            && input[i + 1].is_ascii_hexdigit()
                            && input[i + 2].is_ascii_hexdigit())
                        {
                            // i do not feel good about this
                            // create-react-app's public/index.html uses %PUBLIC_URL% in various tags
                            // This is an invalid %-encoded string, intended to be swapped out at build time by webpack-html-plugin
                            // We don't process HTML, so rewriting this URL path won't happen
                            // But we want to be a little more fault tolerant here than just throwing up an error for something that works in other tools
                            // So we just skip over it and issue a redirect
                            // We issue a redirect because various other tooling client-side may validate URLs
                            // We can't expect other tools to be as fault tolerant
                            if i + b"PUBLIC_URL%".len() < input.len()
                                && &input[i + 1..][..b"PUBLIC_URL%".len()] == b"PUBLIC_URL%"
                            {
                                i += b"PUBLIC_URL%".len() + 1;
                                *needs_redirect.as_deref_mut().unwrap() = true;
                                continue;
                            }
                            return Err(DecodeError::DecodingError);
                        }
                    } else {
                        if !(i + 3 <= input.len()
                            && input[i + 1].is_ascii_hexdigit()
                            && input[i + 2].is_ascii_hexdigit())
                        {
                            return Err(DecodeError::DecodingError);
                        }
                    }

                    writer.write_byte(
                        (strings::to_ascii_hex_value(input[i + 1]) << 4)
                            | strings::to_ascii_hex_value(input[i + 2]),
                    )?;
                    i += 3;
                    written += 1;
                    continue;
                }
                _ => {
                    let start = i;
                    i += 1;

                    // scan ahead assuming .write_all is faster than .write_byte one at a time
                    while i < input.len() && input[i] != b'%' {
                        i += 1;
                    }
                    writer.write_all(&input[start..i])?;
                    written += u32::try_from(i - start).unwrap();
                }
            }
        }

        Ok(written)
    }
}

// TODO(port): FormData re-export removed — bun_runtime (T6) is upward.
// Callers should import from bun_runtime::webcore::form_data
// directly (or move-in pass relocates FormData here if it belongs at T2).
// pub use bun_runtime::webcore::form_data::FormData;

// ══════════════════════════════════════════════════════════════════════════
// Scanners
// ══════════════════════════════════════════════════════════════════════════

#[derive(Clone, Copy)]
pub struct ScannerResult {
    pub name_needs_decoding: bool,
    pub value_needs_decoding: bool,
    pub name: api::StringPointer,
    pub value: api::StringPointer,
}

impl ScannerResult {
    #[inline]
    pub(crate) fn raw_name<'a>(&self, query_string: &'a [u8]) -> &'a [u8] {
        if self.name.length > 0 {
            &query_string[self.name.offset as usize..][..self.name.length as usize]
        } else {
            b""
        }
    }

    #[inline]
    pub(crate) fn raw_value<'a>(&self, query_string: &'a [u8]) -> &'a [u8] {
        if self.value.length > 0 {
            &query_string[self.value.offset as usize..][..self.value.length as usize]
        } else {
            b""
        }
    }
}

pub struct CombinedScanner<'a> {
    pub query: Scanner<'a>,
    pub pathname: PathnameScanner<'a>,
}

impl<'a> CombinedScanner<'a> {
    pub fn init(
        query_string: &'a [u8],
        pathname: &'a [u8],
        routename: &'a [u8],
        url_params: &'a ParamsList<'a>,
    ) -> CombinedScanner<'a> {
        CombinedScanner {
            query: Scanner::init(query_string),
            pathname: PathnameScanner::init(pathname, routename, url_params),
        }
    }

    pub fn reset(&mut self) {
        self.query.reset();
        self.pathname.reset();
    }

    pub fn next(&mut self) -> Option<ScannerResult> {
        self.pathname.next().or_else(|| self.query.next())
    }
}

fn string_pointer_from_strings(parent: &[u8], in_: &[u8]) -> api::StringPointer {
    if in_.is_empty() || parent.is_empty() {
        return api::StringPointer::default();
    }

    if let Some([offset, length]) = bun_core::range_of_slice_in_buffer(in_, parent) {
        return api::StringPointer { offset, length };
    } else {
        if let Some(i) = strings::index_of(parent, in_) {
            debug_assert!(strings::eql_long(&parent[i..][..in_.len()], in_, false));

            return api::StringPointer {
                offset: u32::try_from(i).unwrap(),
                length: u32::try_from(in_.len()).unwrap(),
            };
        }
    }

    api::StringPointer::default()
}

pub struct PathnameScanner<'a> {
    pub params: &'a ParamsList<'a>,
    pub pathname: &'a [u8],
    pub routename: &'a [u8],
    pub i: usize,
}

impl<'a> PathnameScanner<'a> {
    #[inline]
    pub fn is_done(&self) -> bool {
        self.params.len() <= self.i
    }

    pub fn reset(&mut self) {
        self.i = 0;
    }

    pub fn init(
        pathname: &'a [u8],
        routename: &'a [u8],
        params: &'a ParamsList<'a>,
    ) -> PathnameScanner<'a> {
        PathnameScanner {
            pathname,
            routename,
            params,
            i: 0,
        }
    }

    pub fn next(&mut self) -> Option<ScannerResult> {
        if self.is_done() {
            return None;
        }

        let param = self.params[self.i];
        self.i += 1;

        Some(ScannerResult {
            // TODO: fix this technical debt
            name: string_pointer_from_strings(self.routename, param.name),
            name_needs_decoding: false,
            // TODO: fix this technical debt
            value: string_pointer_from_strings(self.pathname, param.value),
            value_needs_decoding: strings::index_of_char(param.value, b'%').is_some(),
        })
    }
}

pub struct Scanner<'a> {
    pub query_string: &'a [u8],
    pub i: usize,
    pub start: usize,
}

impl<'a> Scanner<'a> {
    pub fn init(query_string: &'a [u8]) -> Scanner<'a> {
        if !query_string.is_empty() && query_string[0] == b'?' {
            return Scanner {
                query_string,
                i: 1,
                start: 1,
            };
        }

        Scanner {
            query_string,
            i: 0,
            start: 0,
        }
    }

    #[inline]
    pub fn reset(&mut self) {
        self.i = self.start;
    }

    /// Get the next query string parameter without allocating memory.
    pub fn next(&mut self) -> Option<ScannerResult> {
        let mut relative_i: usize = 0;
        // PORT NOTE: Zig used `defer this.i += relative_i;` — emulated by applying
        // the deferred add at every return point.

        // reuse stack space
        // otherwise we'd recursively call the function
        'outer: loop {
            if self.i >= self.query_string.len() {
                self.i += relative_i;
                return None;
            }

            let slice = &self.query_string[self.i..];
            relative_i = 0;
            let mut name = api::StringPointer {
                offset: u32::try_from(self.i).unwrap(),
                length: 0,
            };
            let mut value = api::StringPointer {
                offset: 0,
                length: 0,
            };
            let mut name_needs_decoding = false;

            while relative_i < slice.len() {
                let char = slice[relative_i];
                match char {
                    b'=' => {
                        name.length = u32::try_from(relative_i).unwrap();
                        relative_i += 1;

                        value.offset = u32::try_from(relative_i + self.i).unwrap();

                        let offset = relative_i;
                        let mut value_needs_decoding = false;
                        while relative_i < slice.len() && slice[relative_i] != b'&' {
                            value_needs_decoding =
                                value_needs_decoding || matches!(slice[relative_i], b'%' | b'+');
                            relative_i += 1;
                        }
                        value.length = u32::try_from(relative_i - offset).unwrap();
                        // If the name is empty and it's just a value, skip it.
                        // This is kind of an opinion. But, it's hard to see where that might be intentional.
                        if name.length == 0 {
                            self.i += relative_i;
                            return None;
                        }
                        self.i += relative_i;
                        return Some(ScannerResult {
                            name,
                            value,
                            name_needs_decoding,
                            value_needs_decoding,
                        });
                    }
                    b'%' | b'+' => {
                        name_needs_decoding = true;
                    }
                    b'&' => {
                        // key&
                        if relative_i > 0 {
                            name.length = u32::try_from(relative_i).unwrap();
                            self.i += relative_i;
                            return Some(ScannerResult {
                                name,
                                value,
                                name_needs_decoding,
                                value_needs_decoding: false,
                            });
                        }

                        // &&&&&&&&&&&&&key=value
                        while relative_i < slice.len() && slice[relative_i] == b'&' {
                            relative_i += 1;
                        }
                        self.i += relative_i;

                        // reuse stack space
                        continue 'outer;
                    }
                    _ => {}
                }

                relative_i += 1;
            }

            if relative_i == 0 {
                self.i += relative_i;
                return None;
            }

            name.length = u32::try_from(relative_i).unwrap();
            self.i += relative_i;
            return Some(ScannerResult {
                name,
                value,
                name_needs_decoding,
                value_needs_decoding: false,
            });
        }
    }
}

// ported from: src/url/url.zig

#[cfg(test)]
mod bare_bracketed_ipv6_tests {
    //! Upstream cfd3bea94: a bare bracketed IPv6 host (no scheme), e.g. the
    //! `[::1]:4873/` left of an .npmrc `//[::1]:4873/:_authToken` key once
    //! its `//` is stripped, must go through `parse_host` instead of falling
    //! through the first-byte dispatch to an empty host.

    use super::URL;

    #[test]
    fn host_with_port_and_trailing_slash() {
        let url = URL::parse(b"[::1]:4873/");
        assert_eq!(url.host, b"[::1]:4873");
        assert_eq!(url.hostname, b"[::1]");
        assert_eq!(url.port, b"4873");
        assert_eq!(url.pathname, b"/");
        assert_eq!(url.protocol, b"");
    }

    #[test]
    fn host_without_port() {
        let url = URL::parse(b"[::1]/");
        assert_eq!(url.host, b"[::1]");
        assert_eq!(url.hostname, b"[::1]");
        assert_eq!(url.port, b"");
        assert_eq!(url.pathname, b"/");
    }

    #[test]
    fn host_with_path() {
        let url = URL::parse(b"[2001:db8::1]:4873/a/b/");
        assert_eq!(url.host, b"[2001:db8::1]:4873");
        assert_eq!(url.hostname, b"[2001:db8::1]");
        assert_eq!(url.port, b"4873");
        assert_eq!(url.pathname, b"/a/b/");
    }

    #[test]
    fn host_without_trailing_slash() {
        let url = URL::parse(b"[::1]:4873");
        assert_eq!(url.host, b"[::1]:4873");
        assert_eq!(url.hostname, b"[::1]");
        assert_eq!(url.port, b"4873");
    }

    #[test]
    fn schemed_bracketed_host_unchanged() {
        // `registry=` lines carry a scheme; they parsed correctly before and
        // must keep the same components so nerf-dart key matching works.
        let url = URL::parse(b"http://[::1]:4873/");
        assert_eq!(url.host, b"[::1]:4873");
        assert_eq!(url.hostname, b"[::1]");
        assert_eq!(url.port, b"4873");
        assert!(!url.protocol.is_empty());
    }
}