bun_install 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
//! Resolves Git URLs and metadata.
//!
//! This library mimics https://www.npmjs.com/package/hosted-git-info. At the time of writing, the
//! latest version is 9.0.0. Although @markovejnovic believes there are bugs in the original
//! library, this library aims to be bug-for-bug compatible with the original.
//!
//! One thing that's really notable is that hosted-git-info supports extensions and we currently
//! offer no support for extensions. This could be added in the future if necessary.
//!
//! # Core Concepts
//!
//! The goal of this library is to transform a Git URL or a "shortcut" (which is a shorthand for a
//! longer URL) into a structured representation of the relevant Git repository.
//!
//! ## Shortcuts
//!
//! A shortcut is a shorthand for a longer URL. For example, `github:user/repo` is a shortcut which
//! resolves to a full Github URL. `gitlab:user/repo` is another example of a shortcut.
//!
//! # Types
//!
//! This library revolves around a couple core types which are briefly described here.
//!
//! ## `HostedGitInfo`
//!
//! This is the main API point of this library. It encapsulates information about a Git repository.
//! To parse URLs into this structure, use the `fromUrl` member function.
//!
//! ## `HostProvider`
//!
//! This enumeration defines all the known Git host providers. Each provider has slightly different
//! properties which need to be accounted for. Further details are provided in its documentation.
//!
//! ## `UrlProtocol`
//!
//! This is a type that encapsulates the different types of protocols that a URL may have. This
//! includes three different cases:
//!
//!   - `well_defined`: A protocol which is directly supported by this library.
//!   - `custom`: A protocol which is not known by this library, but is specified in the URL.
//!               TODO(markovejnovic): How is this handled?
//!   - `unknown`: A protocol which is not specified in the URL.
//!
//! ## `WellDefinedProtocol`
//!
//! This type represents the set of known protocols by this library. Each protocol has slightly
//! different properties which need to be accounted for.
//!
//! It's noteworthy that `WellDefinedProtocol` doesn't refer to "true" protocols, but includes fake
//! tags like `github:` which are handled as "shortcuts" by this library.

use core::ops::Range;
use core::ptr::NonNull;
use std::io::Write as _;

use bstr::BStr;
use bun_alloc::AllocError;
use bun_core::StringBuilder;
use bun_core::{OwnedString, strings};
use bun_url::PercentEncoding;
use bun_url::whatwg::URL as JscUrl;
use enum_map::{Enum, EnumMap};

// ──────────────────────────────────────────────────────────────────────────
// Errors
// ──────────────────────────────────────────────────────────────────────────

#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
pub enum HostedGitInfoError {
    #[error("OutOfMemory")]
    OutOfMemory,
    #[error("InvalidURL")]
    InvalidURL,
}

bun_core::oom_from_alloc!(HostedGitInfoError);

bun_core::named_error_set!(HostedGitInfoError);

#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
pub enum ParseUrlError {
    #[error("InvalidGitUrl")]
    InvalidGitUrl,
    #[error("OutOfMemory")]
    OutOfMemory,
}

bun_core::oom_from_alloc!(ParseUrlError);

bun_core::named_error_set!(ParseUrlError);

// ──────────────────────────────────────────────────────────────────────────
// Representation
// ──────────────────────────────────────────────────────────────────────────

/// Represents how a URL should be reported when formatting it as a string.
///
/// Input strings may be given in any format and they may be formatted in any format. If you wish
/// to format a URL in a specific format, you can use its `format*` methods. However, each input
/// string has a "default" representation which is used when calling `toString()`. Depending on the
/// input, the default representation may be different.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
pub enum Representation {
    /// foo/bar
    Shortcut,
    /// git+ssh://git@domain/user/project.git#committish
    Sshurl,
    /// ssh://domain/user/project.git#committish
    Ssh,
    /// https://domain/user/project.git#committish
    Https,
    /// git://domain/user/project.git#committish
    Git,
    /// http://domain/user/project.git#committish
    Http,
}

// ──────────────────────────────────────────────────────────────────────────
// HostedGitInfo
// ──────────────────────────────────────────────────────────────────────────

// PORT NOTE: reshaped for borrowck. The Zig stores `committish`/`project`/`user`
// as `[]const u8` slices that alias into `_memory_buffer` (a single owned
// allocation). Rust can't express that self-reference safely without lifetimes
// on the struct. We store byte ranges into `_memory_buffer` instead and expose
// slice accessors.
pub struct HostedGitInfo {
    committish: Option<Range<usize>>,
    project: Range<usize>,
    user: Option<Range<usize>>,
    pub host_provider: HostProvider,
    pub default_representation: Representation,

    _memory_buffer: Box<[u8]>,
}

impl HostedGitInfo {
    #[inline]
    pub fn committish(&self) -> Option<&[u8]> {
        self.committish.clone().map(|r| &self._memory_buffer[r])
    }
    #[inline]
    pub fn project(&self) -> &[u8] {
        &self._memory_buffer[self.project.clone()]
    }
    #[inline]
    pub fn user(&self) -> Option<&[u8]> {
        self.user.clone().map(|r| &self._memory_buffer[r])
    }

    /// Helper function to decode a percent-encoded string and append it to a StringBuilder.
    /// Returns the decoded slice and updates the StringBuilder's length.
    ///
    /// The reason we need to do this is because we get URLs like github:user%20name/repo and we
    /// need to decode them to 'user name/repo'. It would be nice if we could get all the
    /// functionality of jsc.URL WITHOUT the percent-encoding, but alas, we cannot. And we need the
    /// jsc.URL functionality for parsing, validating and punycode-decoding the URL.
    ///
    /// Therefore, we use this function to first take a URL string, encode it into a *jsc.URL and
    /// then decode it back to a normal string. Kind of a lot of work, but it works.
    ///
    /// PORT NOTE: returns a `Range<usize>` into the StringBuilder's allocated buffer
    /// instead of a borrowed slice (see struct-level note).
    fn decode_and_append(
        sb: &mut StringBuilder,
        input: &[u8],
    ) -> Result<Range<usize>, HostedGitInfoError> {
        let start = sb.len;
        let writable = sb.writable();
        // PORT NOTE: Zig `PercentEncoding.decode(Writer, writer, input)` ported via the
        // fixed-buffer `decode_into(out, input) -> Result<u32, _>` overload in bun_url.
        let decoded_len = PercentEncoding::decode_into(writable, input)
            .map_err(|_| HostedGitInfoError::InvalidURL)? as usize;
        sb.len += decoded_len;
        Ok(start..start + decoded_len)
    }

    fn copy_from(
        committish: Option<&[u8]>,
        project: &[u8],
        user: Option<&[u8]>,
        host_provider: HostProvider,
        default_representation: Representation,
    ) -> Result<Self, HostedGitInfoError> {
        let mut sb = StringBuilder::default();

        if let Some(u) = user {
            sb.count(u);
        }
        sb.count(project);
        if let Some(c) = committish {
            sb.count(c);
        }

        sb.allocate().map_err(|_| HostedGitInfoError::OutOfMemory)?;

        // Decode user, project, committish while copying
        let user_part = match user {
            Some(u) => Some(Self::decode_and_append(&mut sb, u)?),
            None => None,
        };
        let project_part = Self::decode_and_append(&mut sb, project)?;
        let committish_part = match committish {
            Some(c) => Some(Self::decode_and_append(&mut sb, c)?),
            None => None,
        };

        let owned_buffer = sb.move_to_slice();

        Ok(Self {
            committish: committish_part,
            project: project_part,
            user: user_part,
            host_provider,
            default_representation,
            _memory_buffer: owned_buffer,
        })
    }

    /// Initialize a HostedGitInfo from an extracted structure.
    /// Takes ownership of the extracted structure.
    fn move_from_extracted(
        extracted: &mut ExtractResult,
        host_provider: HostProvider,
        default_representation: Representation,
    ) -> Self {
        let moved = extracted.move_out();
        Self {
            committish: extracted.committish.clone(),
            project: extracted.project.clone(),
            user: extracted.user.clone(),
            host_provider,
            default_representation,
            _memory_buffer: moved,
        }
    }

    // PORT NOTE: `pub fn deinit` → `impl Drop`. Body only freed `_memory_buffer`;
    // `Box<[u8]>` drops automatically, so no explicit Drop impl is needed.

    // PORT NOTE: `pub const toJS = @import("../install_jsc/...")` deleted —
    // `to_js` is an extension-trait method living in `bun_install_jsc`.

    // PORT NOTE: `pub const StringPair` was a Zig-nested struct; hoisted to module
    // scope below (Rust forbids struct defs inside `impl`).

    /// Given a URL-like (including shortcuts) string, parses it into a HostedGitInfo structure.
    /// The HostedGitInfo is valid only for as long as `git_url` is valid.
    pub fn from_url(git_url: &[u8]) -> Result<Option<Self>, HostedGitInfoError> {
        // git_url_mut may carry two ownership semantics:
        //  - It aliases `git_url`, in which case it must not be freed.
        //  - It actually points to a new allocation, in which case it must be freed.
        // PORT NOTE: modeled as Cow-like local; Drop handles the owned case.
        let git_url_owned: Option<Box<[u8]>>;
        let mut git_url_mut: &[u8] = git_url;

        if is_github_shorthand(git_url) {
            // In this case we have to prefix the url with `github:`.
            //
            // NOTE(markovejnovic): I don't exactly understand why this is treated specially.
            //
            // TODO(markovejnovic): Perhaps we can avoid this allocation...
            // This one seems quite easy to get rid of.
            let concatenated = strings::concat(&[b"github:", git_url]);
            git_url_owned = Some(concatenated);
            git_url_mut = git_url_owned.as_deref().unwrap();
        } else {
            git_url_owned = None;
        }
        let _ = &git_url_owned;

        let Ok(parsed) = parse_url(git_url_mut) else {
            return Ok(None);
        };
        // `parsed.url` is `OwnedJscUrl`; Drop handles `defer parsed.url.deinit()`.

        let host_provider = match parsed.proto {
            UrlProtocol::WellFormed(p) => p
                .host_provider()
                .or_else(|| HostProvider::from_url_domain(&parsed.url)),
            UrlProtocol::Unknown => HostProvider::from_url_domain(&parsed.url),
            UrlProtocol::Custom(_) => HostProvider::from_url(&parsed.url),
        };
        let Some(host_provider) = host_provider else {
            return Ok(None);
        };

        let is_shortcut = matches!(parsed.proto, UrlProtocol::WellFormed(p) if p.is_shortcut());
        if !is_shortcut {
            let Some(mut extracted) = host_provider.extract(&parsed.url)? else {
                return Ok(None);
            };
            return Ok(Some(HostedGitInfo::move_from_extracted(
                &mut extracted,
                host_provider,
                parsed.proto.default_representation(),
            )));
        }

        // Shortcut path: github:user/repo, gitlab:user/repo, etc. (from-url.js line 68-96)
        let pathname_owned = parsed.url.pathname().to_owned_slice();
        // Drop handles `defer allocator.free(pathname_owned)`.

        // Strip leading / (from-url.js line 69)
        let mut pathname: &[u8] = strings::trim_prefix(&pathname_owned, b"/");

        // Strip auth (from-url.js line 70-74)
        if let Some(first_at) = strings::index_of_char(pathname, b'@') {
            pathname = &pathname[first_at as usize + 1..];
        }

        // extract user and project from pathname (from-url.js line 76-86)
        let mut user_part: Option<&[u8]> = None;
        let project_part: &[u8] = 'blk: {
            if let Some(last_slash) = strings::last_index_of_char(pathname, b'/') {
                let user_str = &pathname[0..last_slash];
                // We want nulls only, never empty strings (from-url.js line 79-82)
                if !user_str.is_empty() {
                    user_part = Some(user_str);
                }
                break 'blk &pathname[last_slash + 1..];
            } else {
                break 'blk pathname;
            }
        };

        // Strip .git suffix (from-url.js line 88-90)
        let project_trimmed = strings::trim_suffix(project_part, b".git");

        // Get committish from URL fragment (from-url.js line 92-94)
        let fragment = parsed.url.fragment_identifier().to_owned_slice();
        let committish: Option<&[u8]> = if !fragment.is_empty() {
            Some(&fragment)
        } else {
            None
        };

        // copy_from will URL-decode user, project, and committish
        Ok(Some(HostedGitInfo::copy_from(
            committish,
            project_trimmed,
            user_part,
            host_provider,
            Representation::Shortcut, // Shortcuts always use shortcut representation
        )?))
    }
}

// PORT NOTE: Zig nested `pub const StringPair = struct {...}` inside HostedGitInfo;
// Rust can't nest struct defs inside `impl`, so it lives at module scope but is
// re-exported through the type's namespace conceptually.
pub struct StringPair {
    // PORT NOTE: Zig `[]const u8` aliasing-semantics. No constructor in this module
    // (consumed by install_jsc), so own the buffers — callers allocate per use.
    pub save_spec: Box<[u8]>,
    pub fetch_spec: Option<Box<[u8]>>,
}

// ──────────────────────────────────────────────────────────────────────────
// parse_url
// ──────────────────────────────────────────────────────────────────────────

/// RAII handle over a heap-allocated pure-Rust `bun_url::whatwg::URL`.
/// Freed via `deinit` (Box::from_raw) — never free with plain `drop(Box)` of a
/// ZST view; the pointer is produced by `URL::from_string` / `from_utf8`.
pub struct OwnedJscUrl(NonNull<JscUrl>);
impl core::ops::Deref for OwnedJscUrl {
    type Target = JscUrl;
    fn deref(&self) -> &JscUrl {
        // SAFETY: `from_string`/`from_utf8` returned a live heap URL we own.
        unsafe { self.0.as_ref() }
    }
}
impl Drop for OwnedJscUrl {
    fn drop(&mut self) {
        // SAFETY: unique owner of a whatwg::URL from Box::into_raw.
        unsafe { self.0.as_mut() }.deinit();
    }
}

// PORT NOTE: anonymous return struct in Zig → named struct here.
// `url` is OWNED per LIFETIMES.tsv (jsc.URL.fromString creates; caller deinits).
pub struct ParsedUrl<'a> {
    pub url: OwnedJscUrl,
    pub proto: UrlProtocol<'a>,
}

/// Handles input like git:github.com:user/repo and inserting the // after the first : if necessary
///
/// May error with `error.InvalidGitUrl` if the URL is not valid.
///
/// Note that this may or may not allocate but it manages its own memory.
pub fn parse_url(npa_str: &[u8]) -> Result<ParsedUrl<'_>, ParseUrlError> {
    // Certain users can provide values like user:password@github.com:foo/bar and we want to
    // "correct" the protocol to be git+ssh://user:password@github.com:foo/bar
    let proto_pair = normalize_protocol(npa_str);
    // Drop handles `defer proto_pair.deinit()`.

    // TODO(markovejnovic): We might be able to avoid this allocation if we rework how jsc.URL
    //                      accepts strings.
    let maybe_url = proto_pair.to_url();
    if let Some(url) = maybe_url {
        return Ok(ParsedUrl {
            url,
            proto: proto_pair.protocol,
        });
    }

    // Now that may fail, if the URL is not nicely formatted. In that case, we try to correct the
    // URL and parse it.
    let corrected = correct_url(&proto_pair)?;
    let corrected_url = corrected.to_url();
    if let Some(url) = corrected_url {
        return Ok(ParsedUrl {
            url,
            proto: corrected.protocol,
        });
    }

    // Otherwise, we complain.
    Err(ParseUrlError::InvalidGitUrl)
}

// ──────────────────────────────────────────────────────────────────────────
// WellDefinedProtocol
// ──────────────────────────────────────────────────────────────────────────

/// Enumeration of possible URL protocols.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
pub enum WellDefinedProtocol {
    Git,
    GitPlusFile,
    GitPlusFtp,
    GitPlusHttp,
    GitPlusHttps,
    GitPlusRsync,
    GitPlusSsh,
    Http,
    Https,
    Ssh,

    // Non-standard protocols.
    Github,
    Bitbucket,
    Gitlab,
    Gist,
    Sourcehut,
}

/// Buffer type for holding a protocol string with colon (e.g., "git+rsync:").
/// Sized to hold the longest protocol name plus one character for the colon.
// PORT NOTE: hoisted from `impl WellDefinedProtocol` — inherent associated types
// are unstable (E0658).
pub(crate) type StringWithColonBuffer = [u8; WellDefinedProtocol::MAX_PROTOCOL_LENGTH + 1];

impl WellDefinedProtocol {
    /// Mapping from protocol string (without colon) to WellDefinedProtocol.
    pub(crate) const STRINGS: phf::Map<&'static [u8], WellDefinedProtocol> = phf::phf_map! {
        b"bitbucket" => WellDefinedProtocol::Bitbucket,
        b"gist" => WellDefinedProtocol::Gist,
        b"git+file" => WellDefinedProtocol::GitPlusFile,
        b"git+ftp" => WellDefinedProtocol::GitPlusFtp,
        b"git+http" => WellDefinedProtocol::GitPlusHttp,
        b"git+https" => WellDefinedProtocol::GitPlusHttps,
        b"git+rsync" => WellDefinedProtocol::GitPlusRsync,
        b"git+ssh" => WellDefinedProtocol::GitPlusSsh,
        b"git" => WellDefinedProtocol::Git,
        b"github" => WellDefinedProtocol::Github,
        b"gitlab" => WellDefinedProtocol::Gitlab,
        b"http" => WellDefinedProtocol::Http,
        b"https" => WellDefinedProtocol::Https,
        b"sourcehut" => WellDefinedProtocol::Sourcehut,
        b"ssh" => WellDefinedProtocol::Ssh,
    };

    // PORT NOTE: Zig `strings.getKey(self)` did reverse lookup; provide explicit map.
    fn protocol_str(self) -> &'static [u8] {
        match self {
            Self::Bitbucket => b"bitbucket",
            Self::Gist => b"gist",
            Self::GitPlusFile => b"git+file",
            Self::GitPlusFtp => b"git+ftp",
            Self::GitPlusHttp => b"git+http",
            Self::GitPlusHttps => b"git+https",
            Self::GitPlusRsync => b"git+rsync",
            Self::GitPlusSsh => b"git+ssh",
            Self::Git => b"git",
            Self::Github => b"github",
            Self::Gitlab => b"gitlab",
            Self::Http => b"http",
            Self::Https => b"https",
            Self::Sourcehut => b"sourcehut",
            Self::Ssh => b"ssh",
        }
    }

    /// Look up a protocol from a string that includes the trailing colon (e.g., "https:").
    /// This method strips the colon before looking up in the strings map.
    pub(crate) fn from_string_with_colon(protocol_with_colon: &[u8]) -> Option<Self> {
        if protocol_with_colon.is_empty() {
            None
        } else {
            Self::STRINGS
                .get(strings::trim_suffix(protocol_with_colon, b":"))
                .copied()
        }
    }

    /// Maximum length of any protocol string in the strings map (computed at compile time).
    // PORT NOTE: Zig computed this with a comptime loop over `strings.kvs`. The
    // longest keys ("git+https", "git+rsync", "sourcehut", "bitbucket") are 9 bytes.
    pub(crate) const MAX_PROTOCOL_LENGTH: usize = 9;

    /// Get the protocol string with colon (e.g., "https:") for a given protocol enum.
    /// Takes a buffer pointer to hold the result.
    /// Returns a slice into that buffer containing the protocol string with colon.
    pub(crate) fn to_string_with_colon(self, buf: &mut StringWithColonBuffer) -> &[u8] {
        // Look up the protocol string (without colon) from the map
        let protocol_str = self.protocol_str();

        // Copy to buffer and append colon
        buf[0..protocol_str.len()].copy_from_slice(protocol_str);
        buf[protocol_str.len()] = b':';
        &buf[0..protocol_str.len() + 1]
    }

    /// The set of characters that must appear between <protocol><resource-identifier>.
    /// For example, in `git+ssh://user@host:repo`, the `//` is the magic string. Some protocols
    /// don't support this, for example `github:user/repo` is valid.
    ///
    /// Kind of arbitrary and implemented to match hosted-git-info's behavior.
    fn protocol_resource_identifier_concatenation_token(self) -> &'static [u8] {
        match self {
            Self::Git
            | Self::GitPlusFile
            | Self::GitPlusFtp
            | Self::GitPlusHttp
            | Self::GitPlusHttps
            | Self::GitPlusRsync
            | Self::GitPlusSsh
            | Self::Http
            | Self::Https
            | Self::Ssh => b"//",
            Self::Github | Self::Bitbucket | Self::Gitlab | Self::Gist | Self::Sourcehut => b"",
        }
    }

    /// Determine the default representation for this protocol.
    /// Mirrors the logic in from-url.js line 110.
    fn default_representation(self) -> Representation {
        match self {
            Self::GitPlusSsh | Self::Ssh | Self::GitPlusHttp => Representation::Sshurl,
            Self::GitPlusHttps => Representation::Https,
            Self::GitPlusFile | Self::GitPlusFtp | Self::GitPlusRsync | Self::Git => {
                Representation::Git
            }
            Self::Http => Representation::Http,
            Self::Https => Representation::Https,
            Self::Github | Self::Bitbucket | Self::Gitlab | Self::Gist | Self::Sourcehut => {
                Representation::Shortcut
            }
        }
    }

    /// Certain protocols will have associated host providers. This method returns the associated
    /// host provider, if one exists.
    fn host_provider(self) -> Option<HostProvider> {
        match self {
            Self::Github => Some(HostProvider::Github),
            Self::Bitbucket => Some(HostProvider::Bitbucket),
            Self::Gitlab => Some(HostProvider::Gitlab),
            Self::Gist => Some(HostProvider::Gist),
            Self::Sourcehut => Some(HostProvider::Sourcehut),
            _ => None,
        }
    }

    fn is_shortcut(self) -> bool {
        matches!(
            self,
            Self::Github | Self::Bitbucket | Self::Gitlab | Self::Gist | Self::Sourcehut
        )
    }
}

// ──────────────────────────────────────────────────────────────────────────
// isGitHubShorthand
// ──────────────────────────────────────────────────────────────────────────

/// Test whether the given node-package-arg string is a GitHub shorthand.
///
/// This mirrors the implementation of hosted-git-info, though it is significantly faster.
pub(crate) fn is_github_shorthand(npa_str: &[u8]) -> bool {
    // The implementation in hosted-git-info is a multi-pass algorithm. We've opted to implement a
    // single-pass algorithm for better performance.
    //
    // This could be even faster with SIMD but this is probably good enough for now.
    if npa_str.is_empty() {
        return false;
    }

    // Implements doesNotStartWithDot
    if npa_str[0] == b'.' || npa_str[0] == b'/' {
        return false;
    }

    let mut pound_idx: Option<usize> = None;
    let mut seen_slash = false;

    for (i, &c) in npa_str.iter().enumerate() {
        match c {
            // Implement atOnlyAfterHash and colonOnlyAfterHash
            b':' | b'@' => {
                if pound_idx.is_none() {
                    return false;
                }
            }

            b'#' => {
                pound_idx = Some(i);
            }
            b'/' => {
                // Implements secondSlashOnlyAfterHash
                if seen_slash && pound_idx.is_none() {
                    return false;
                }

                seen_slash = true;
            }
            _ => {
                // Implement spaceOnlyAfterHash
                // PORT NOTE: match Zig std.ascii.isWhitespace exactly (includes VT 0x0B and FF 0x0C;
                // Rust u8::is_ascii_whitespace excludes VT).
                if matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C) && pound_idx.is_none() {
                    return false;
                }
            }
        }
    }

    // Implements doesNotEndWithSlash
    let does_not_end_with_slash = if let Some(pi) = pound_idx {
        pi == 0 || npa_str[pi - 1] != b'/'
    } else {
        !npa_str.is_empty() && npa_str[npa_str.len() - 1] != b'/'
    };

    // Implement hasSlash
    seen_slash && does_not_end_with_slash
}

// ──────────────────────────────────────────────────────────────────────────
// UrlProtocol / UrlProtocolPair
// ──────────────────────────────────────────────────────────────────────────

// PORT NOTE: Zig `union(enum) { custom: []const u8 }` borrowed the input `npa_str`.
// Carries a BORROW_PARAM lifetime; lives only for the duration of `parse_url`.
#[derive(Debug, Clone, Copy)]
pub enum UrlProtocol<'a> {
    WellFormed(WellDefinedProtocol),

    /// A protocol which is not known by the library. Includes the : character, but not the
    /// double-slash, so `foo://bar` would yield `foo:`.
    Custom(&'a [u8]),

    /// Either no protocol was specified or the library couldn't figure it out.
    Unknown,
}

impl<'a> UrlProtocol<'a> {
    /// Deduces the default representation for this protocol.
    pub(crate) fn default_representation(self) -> Representation {
        match self {
            UrlProtocol::WellFormed(p) => p.default_representation(),
            _ => Representation::Sshurl, // Unknown/custom protocols default to sshurl
        }
    }
}

// PORT NOTE: `url: union(enum) { managed: {buf, allocator}, unmanaged: []const u8 }`
// → enum with `Managed(Box<[u8]>)` / `Unmanaged(&'a [u8])`. Allocator dropped.
pub(crate) enum UrlProtocolPairUrl<'a> {
    Managed(Box<[u8]>),
    Unmanaged(&'a [u8]),
}

pub(crate) struct UrlProtocolPair<'a> {
    pub url: UrlProtocolPairUrl<'a>,
    pub protocol: UrlProtocol<'a>,
}

impl<'a> UrlProtocolPair<'a> {
    pub(crate) fn url_slice(&self) -> &[u8] {
        match &self.url {
            UrlProtocolPairUrl::Managed(s) => s,
            UrlProtocolPairUrl::Unmanaged(s) => s,
        }
    }

    // PORT NOTE: `deinit` → Drop; `Managed(Box<[u8]>)` frees automatically.

    /// Given a protocol pair, create a jsc.URL if possible. May allocate, but owns its memory.
    fn to_url(&self) -> Option<OwnedJscUrl> {
        // Ehhh.. Old IE's max path length was 2K so let's just use that. I searched for a
        // statistical distribution of URL lengths and found nothing.
        const _LONG_URL_THRESH: usize = 2048;
        // PERF(port): was stack-fallback (std.heap.stackFallback) — profile if it shows up on a hot path

        let mut protocol_buf: StringWithColonBuffer =
            [0u8; WellDefinedProtocol::MAX_PROTOCOL_LENGTH + 1];

        match self.protocol {
            // If we have no protocol, we can assume it is git+ssh.
            UrlProtocol::Unknown => Self::concat_parts_to_url(&[b"git+ssh://", self.url_slice()]),
            UrlProtocol::Custom(proto_str) => {
                Self::concat_parts_to_url(&[proto_str, b"//", self.url_slice()])
            }
            // This feels counter-intuitive but is correct. It's not github://foo/bar, it's
            // github:foo/bar.
            UrlProtocol::WellFormed(proto_tag) => Self::concat_parts_to_url(&[
                proto_tag.to_string_with_colon(&mut protocol_buf),
                // Wordy name for a double-slash or empty string. github:foo/bar is valid, but
                // git+ssh://foo/bar is also valid.
                proto_tag.protocol_resource_identifier_concatenation_token(),
                self.url_slice(),
            ]),
        }
    }

    fn concat_parts_to_url(parts: &[&[u8]]) -> Option<OwnedJscUrl> {
        // TODO(markovejnovic): There is a sad unnecessary allocation here that I don't know how to
        // get rid of -- in theory, URL.zig could allocate once.
        let new_str = strings::concat(parts);
        // Drop handles `defer allocator.free(new_str)`.
        JscUrl::from_utf8(&new_str).map(OwnedJscUrl)
    }
}

// ──────────────────────────────────────────────────────────────────────────
// normalize_protocol / correct_url
// ──────────────────────────────────────────────────────────────────────────

/// Given a loose string that may or may not be a valid URL, attempt to normalize it.
///
/// Returns a struct containing the URL string with the `protocol://` part removed and a tagged
/// enumeration. If the protocol is known, it is returned as a WellDefinedProtocol. If the protocol
/// is specified in the URL, it is given as a slice and if it is not specified, the `unknown` field
/// is returned. The result is a view into `npa_str` which must, consequently, remain stable.
///
/// This mirrors the `correctProtocol` function in `hosted-git-info/parse-url.js`.
fn normalize_protocol(npa_str: &[u8]) -> UrlProtocolPair<'_> {
    let mut first_colon_idx: i32 = -1;
    if let Some(idx) = strings::index_of_char(npa_str, b':') {
        first_colon_idx = i32::try_from(idx).expect("int cast");
    }

    // The cast here is safe -- first_colon_idx is guaranteed to be [-1, infty)
    let proto_slice = &npa_str[0..usize::try_from(first_colon_idx + 1).expect("int cast")];

    if let Some(url_protocol) = WellDefinedProtocol::from_string_with_colon(proto_slice) {
        // We need to slice off the protocol from the string. Note there are two very annoying
        // cases -- one where the protocol string is foo://bar and one where it is foo:bar.
        let post_colon = strings::substring(
            npa_str,
            Some(usize::try_from(first_colon_idx + 1).expect("int cast")),
            None,
        );

        return UrlProtocolPair {
            url: UrlProtocolPairUrl::Unmanaged(if post_colon.starts_with(b"//") {
                &post_colon[2..post_colon.len()]
            } else {
                post_colon
            }),
            protocol: UrlProtocol::WellFormed(url_protocol),
        };
    }

    // Now we search for the @ character to see if we have a user@host:path GIT+SSH style URL.
    let first_at_idx = strings::index_of_char(npa_str, b'@');
    if let Some(at_idx) = first_at_idx {
        // We have an @ in the string
        if first_colon_idx != -1 {
            // We have a : in the string.
            if i32::try_from(at_idx).expect("int cast") > first_colon_idx {
                // The @ is after the :, so we have something like user:pass@host which is a valid
                // URL. and should be promoted to git_plus_ssh. It's guaranteed that the issue is
                // not that we have proto://user@host:path because we would've caught that above.
                return UrlProtocolPair {
                    url: UrlProtocolPairUrl::Unmanaged(npa_str),
                    protocol: UrlProtocol::WellFormed(WellDefinedProtocol::GitPlusSsh),
                };
            } else {
                // Otherwise we have something like user@host:path which is also a valid URL.
                // Things are, however, different, since we don't really know what the protocol is.
                // Remember, we would've hit the proto://user@host:path above.

                // NOTE(markovejnovic): I don't, at this moment, understand how exactly
                // hosted-git-info and npm-package-arg handle this "unknown" protocol as of now.
                // We can't really guess either -- there's no :// which comes before @
                return UrlProtocolPair {
                    url: UrlProtocolPairUrl::Unmanaged(npa_str),
                    protocol: UrlProtocol::Unknown,
                };
            }
        } else {
            // Something like user@host which is also a valid URL. Since no :, that means that the
            // URL is as good as it gets. No need to slice.
            return UrlProtocolPair {
                url: UrlProtocolPairUrl::Unmanaged(npa_str),
                protocol: UrlProtocol::WellFormed(WellDefinedProtocol::GitPlusSsh),
            };
        }
    }

    // The next thing we can try is to search for the double slash and treat this protocol as a
    // custom one.
    //
    // NOTE(markovejnovic): I also think this is wrong in parse-url.js.
    // They:
    // 1. Test the protocol against known protocols (which is fine)
    // 2. Then, if not found, they go through that hoop of checking for @ and : guessing if it is a
    //    git+ssh URL or not
    // 3. And finally, they search for ://.
    //
    // The last two steps feel like they should happen in reverse order:
    //
    // If I have a foobar://user:host@path URL (and foobar is not given as a known protocol), their
    // implementation will not report this as a foobar protocol, but rather as
    // git+ssh://foobar://user:host@path which, I think, is wrong.
    //
    // I even tested it: https://tinyurl.com/5y4e6zrw
    //
    // Our goal is to be bug-for-bug compatible, at least for now, so this is how I re-implemented
    // it.
    let maybe_dup_slash_idx = strings::index_of(npa_str, b"//");
    if let Some(dup_slash_idx) = maybe_dup_slash_idx {
        if i32::try_from(dup_slash_idx).expect("int cast") == first_colon_idx + 1 {
            return UrlProtocolPair {
                url: UrlProtocolPairUrl::Unmanaged(strings::substring(
                    npa_str,
                    Some(dup_slash_idx + 2),
                    None,
                )),
                protocol: UrlProtocol::Custom(&npa_str[0..dup_slash_idx]),
            };
        }
    }

    // Well, otherwise we have to split the original URL into two pieces,
    // right at the colon.
    if first_colon_idx != -1 {
        return UrlProtocolPair {
            url: UrlProtocolPairUrl::Unmanaged(strings::substring(
                npa_str,
                Some(usize::try_from(first_colon_idx + 1).expect("int cast")),
                None,
            )),
            protocol: UrlProtocol::Custom(
                &npa_str[0..usize::try_from(first_colon_idx + 1).expect("int cast")],
            ),
        };
    }

    // Well we couldn't figure out anything.
    UrlProtocolPair {
        url: UrlProtocolPairUrl::Unmanaged(npa_str),
        protocol: UrlProtocol::Unknown,
    }
}

/// Attempt to correct an scp-style URL into a proper URL, parsable with jsc.URL.
///
/// This function assumes that the input is an scp-style URL.
pub(crate) fn correct_url<'a>(
    url_proto_pair: &UrlProtocolPair<'a>,
) -> Result<UrlProtocolPair<'a>, AllocError> {
    let at_idx: isize = if let Some(idx) =
        strings::last_index_before_char(url_proto_pair.url_slice(), b'@', b'#')
    {
        isize::try_from(idx).expect("int cast")
    } else {
        -1
    };

    let col_idx: isize = if let Some(idx) =
        strings::last_index_before_char(url_proto_pair.url_slice(), b':', b'#')
    {
        isize::try_from(idx).expect("int cast")
    } else {
        -1
    };

    if col_idx > at_idx {
        let mut duped: Box<[u8]> = Box::from(url_proto_pair.url_slice());
        duped[usize::try_from(col_idx).expect("int cast")] = b'/';

        return Ok(UrlProtocolPair {
            url: UrlProtocolPairUrl::Managed(duped),
            protocol: UrlProtocol::WellFormed(WellDefinedProtocol::GitPlusSsh),
        });
    }

    if col_idx == -1 && matches!(url_proto_pair.protocol, UrlProtocol::Unknown) {
        // PORT NOTE: Zig copies `url_proto_pair.url` (a tagged union) by value. Here
        // we know `normalize_protocol` only ever returns `Unmanaged`, so re-borrow.
        return Ok(UrlProtocolPair {
            url: match &url_proto_pair.url {
                UrlProtocolPairUrl::Unmanaged(s) => UrlProtocolPairUrl::Unmanaged(s),
                UrlProtocolPairUrl::Managed(s) => UrlProtocolPairUrl::Managed(s.clone()),
            },
            protocol: UrlProtocol::WellFormed(WellDefinedProtocol::GitPlusSsh),
        });
    }

    Ok(UrlProtocolPair {
        url: match &url_proto_pair.url {
            UrlProtocolPairUrl::Unmanaged(s) => UrlProtocolPairUrl::Unmanaged(s),
            UrlProtocolPairUrl::Managed(s) => UrlProtocolPairUrl::Managed(s.clone()),
        },
        protocol: url_proto_pair.protocol,
    })
}

// ──────────────────────────────────────────────────────────────────────────
// HostProvider
// ──────────────────────────────────────────────────────────────────────────

/// This enumeration encapsulates all known host providers and their configurations.
///
/// Providers each have different configuration fields and, on top of that, have different
/// mechanisms for formatting URLs. For example, GitHub will format SSH URLs as
/// `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, while `gist`
/// will format URLs as `git+ssh://git@${domain}/${project}.git${maybeJoin('#', committish)}`. This
/// structure encapsulates the differences between providers and how they handle all of that.
///
/// Effectively, this enumeration acts as a registry of all known providers and a vtable for
/// jumping between different behavior for different providers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Enum, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
pub enum HostProvider {
    Bitbucket,
    Gist,
    Github,
    Gitlab,
    Sourcehut,
}

impl HostProvider {
    const ALL: [HostProvider; 5] = [
        HostProvider::Bitbucket,
        HostProvider::Gist,
        HostProvider::Github,
        HostProvider::Gitlab,
        HostProvider::Sourcehut,
    ];

    fn extract(self, url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError> {
        (configs()[self].format_extract)(url)
    }

    /// Return the string representation of the provider.
    pub fn type_str(self) -> &'static str {
        <&'static str>::from(self)
    }

    fn shortcut(self) -> &'static [u8] {
        configs()[self].shortcut
    }

    pub fn domain(self) -> &'static [u8] {
        configs()[self].domain
    }

    fn shortcut_without_colon(self) -> &'static [u8] {
        let shct = self.shortcut();
        &shct[0..shct.len() - 1]
    }

    /// Find the appropriate host provider by its shortcut (e.g. "github:").
    ///
    /// The second parameter allows you to declare whether the given string includes the protocol:
    /// colon or not.
    // PERF(port): was comptime monomorphization — profile if it shows up on a hot path
    fn from_shortcut(shortcut_str: &[u8], with_colon: bool) -> Option<HostProvider> {
        // PORT NOTE: Zig used `inline for (std.meta.fields(Self))` (comptime reflection).
        for provider in Self::ALL {
            let shortcut_matches = if with_colon {
                provider.shortcut() == shortcut_str
            } else {
                provider.shortcut_without_colon() == shortcut_str
            };

            if shortcut_matches {
                return Some(provider);
            }
        }

        None
    }

    /// Find the appropriate host provider by its domain (e.g. "github.com").
    fn from_domain(domain_str: &[u8]) -> Option<HostProvider> {
        // PORT NOTE: Zig used `inline for (std.meta.fields(Self))` (comptime reflection).
        Self::ALL
            .into_iter()
            .find(|&provider| provider.domain() == domain_str)
    }

    /// Parse a URL and return the appropriate host provider, if any.
    fn from_url(url: &JscUrl) -> Option<HostProvider> {
        let proto_str = OwnedString::new(url.protocol());

        // Try shortcut first (github:, gitlab:, etc.)
        if let Some(provider) = HostProvider::from_shortcut(proto_str.byte_slice(), false) {
            return Some(provider);
        }

        HostProvider::from_url_domain(url)
    }

    /// Given a URL, use the domain in the URL to find the appropriate host provider.
    fn from_url_domain(url: &JscUrl) -> Option<HostProvider> {
        const _MAX_HOSTNAME_LEN: usize = 253;
        // PERF(port): was stack-fallback (FixedBufferAllocator) — profile if it shows up on a hot path

        let hostname_str = OwnedString::new(url.hostname());

        let hostname_utf8 = hostname_str.to_utf8();
        let hostname = strings::without_prefix(hostname_utf8.slice(), b"www.");

        HostProvider::from_domain(hostname)
    }
}

// ──────────────────────────────────────────────────────────────────────────
// HostProvider::Config
// ──────────────────────────────────────────────────────────────────────────

pub struct Config {
    pub protocols: &'static [WellDefinedProtocol],
    pub domain: &'static [u8],
    pub shortcut: &'static [u8],
    pub tree_path: Option<&'static [u8]>,
    pub blob_path: Option<&'static [u8]>,
    pub edit_path: Option<&'static [u8]>,

    pub format_ssh: formatters::ssh::Type,
    pub format_sshurl: formatters::ssh_url::Type,
    pub format_https: formatters::https::Type,
    pub format_shortcut: formatters::shortcut::Type,
    pub format_git: formatters::git::Type,
    pub format_extract: formatters::extract::Type,
}

// PORT NOTE: `ExtractResult` corresponds to `Config.formatters.extract.Result`.
// Reshaped to use `Range<usize>` into `_owned_buffer` (see HostedGitInfo note).
pub struct ExtractResult {
    pub user: Option<Range<usize>>,
    pub project: Range<usize>,
    pub committish: Option<Range<usize>>,
    _owned_buffer: Option<Box<[u8]>>,
}

impl ExtractResult {
    // PORT NOTE: `deinit` → Drop; `Option<Box<[u8]>>` frees automatically.

    /// Return the buffer which owns this Result and the allocator responsible for
    /// freeing it.
    ///
    /// Same semantics as C++ STL. Safe-to-deinit Result after this, not safe to
    /// use it.
    fn move_out(&mut self) -> Box<[u8]> {
        let Some(buffer) = self._owned_buffer.take() else {
            panic!(
                "Cannot move an empty Result. This is a bug in Bun. Please \
                 report this issue on GitHub."
            );
        };
        buffer
    }
}

/// Encapsulates all the various foramtters that different hosts may have. Usually this has
/// to do with URLs, but could be other things.
pub mod formatters {
    use super::*;

    pub(super) fn requires_user(user: Option<&[u8]>) {
        if user.is_none() {
            panic!(
                "Attempted to format a default SSH URL without a user. This is an \
                 irrecoverable programming bug in Bun. Please report this issue \
                 on GitHub."
            );
        }
    }

    /// Mirrors hosts.js's sshtemplate
    pub mod ssh {
        use super::*;

        pub type Type = fn(
            self_: HostProvider,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError>;

        pub(crate) fn default(
            self_: HostProvider,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            requires_user(user);
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git@{}:{}/{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(user.unwrap()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }

        pub(crate) fn gist(
            self_: HostProvider,
            _user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git@{}:{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }
    }

    /// Mirrors hosts.js's sshurltemplate
    pub mod ssh_url {
        use super::*;

        pub type Type = fn(
            self_: HostProvider,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError>;

        pub(crate) fn default(
            self_: HostProvider,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            requires_user(user);
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git+ssh://git@{}/{}/{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(user.unwrap()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }

        pub(crate) fn gist(
            self_: HostProvider,
            _user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git+ssh://git@{}/{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }
    }

    /// Mirrors hosts.js's httpstemplate
    pub mod https {
        use super::*;

        pub type Type = fn(
            self_: HostProvider,
            auth: Option<&[u8]>,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError>;

        pub(crate) fn default(
            self_: HostProvider,
            auth: Option<&[u8]>,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            requires_user(user);

            let auth_str: &[u8] = auth.unwrap_or(b"");
            let auth_sep: &[u8] = if !auth_str.is_empty() { b"@" } else { b"" };
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git+https://{}{}{}/{}/{}.git{}{}",
                BStr::new(auth_str),
                BStr::new(auth_sep),
                BStr::new(self_.domain()),
                BStr::new(user.unwrap()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }

        pub(crate) fn gist(
            self_: HostProvider,
            _auth: Option<&[u8]>,
            _user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git+https://{}/{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }

        pub(crate) fn sourcehut(
            self_: HostProvider,
            _auth: Option<&[u8]>,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            requires_user(user);

            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "https://{}/{}/{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(user.unwrap()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }
    }

    /// Mirrors hosts.js's shortcuttemplate
    pub mod shortcut {
        use super::*;

        pub type Type = fn(
            self_: HostProvider,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError>;

        pub(crate) fn default(
            self_: HostProvider,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            requires_user(user);

            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "{}{}/{}{}{}",
                BStr::new(self_.shortcut()),
                BStr::new(user.unwrap()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }

        pub(crate) fn gist(
            self_: HostProvider,
            _user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "{}{}{}{}",
                BStr::new(self_.shortcut()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }
    }

    /// Mirrors hosts.js's extract function
    pub mod extract {
        use super::*;

        pub type Type = fn(url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError>;

        pub(crate) fn github(url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError> {
            let pathname_owned = url.pathname().to_owned_slice();
            let pathname = strings::trim_prefix(&pathname_owned, b"/");

            let mut iter = pathname.split(|&b| b == b'/');
            let Some(user_part) = iter.next() else {
                return Ok(None);
            };
            let Some(project_part) = iter.next() else {
                return Ok(None);
            };
            let type_part = iter.next();
            let committish_part = iter.next();

            let project = strings::trim_suffix(project_part, b".git");

            if user_part.is_empty() || project.is_empty() {
                return Ok(None);
            }

            // If the type part says something other than "tree", we're not looking at a
            // github URL that we understand.
            if let Some(tp) = type_part {
                if tp != b"tree" {
                    return Ok(None);
                }
            }

            // PORT NOTE: in Zig the `committish` borrow from `fragment_utf8` is freed
            // before being copied into the StringBuilder. We hold the owned fragment
            // here to keep the borrow valid until copied.
            let fragment_utf8;
            let committish: Option<&[u8]> = if type_part.is_none() {
                let fragment_str = OwnedString::new(url.fragment_identifier());
                fragment_utf8 = fragment_str.to_utf8();
                let fragment = fragment_utf8.slice();
                if !fragment.is_empty() {
                    Some(fragment)
                } else {
                    None
                }
            } else {
                committish_part
            };

            let mut sb = StringBuilder::default();
            sb.count(user_part);
            sb.count(project);
            if let Some(c) = committish {
                sb.count(c);
            }

            sb.allocate()?;

            let user_slice = HostedGitInfo::decode_and_append(&mut sb, user_part)?;
            let project_slice = HostedGitInfo::decode_and_append(&mut sb, project)?;
            let committish_slice = match committish {
                Some(c) => Some(HostedGitInfo::decode_and_append(&mut sb, c)?),
                None => None,
            };

            Ok(Some(ExtractResult {
                user: Some(user_slice),
                project: project_slice,
                committish: committish_slice,
                _owned_buffer: Some(sb.move_to_slice()),
            }))
        }

        pub(crate) fn bitbucket(url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError> {
            let pathname_owned = url.pathname().to_owned_slice();
            let pathname = strings::trim_prefix(&pathname_owned, b"/");

            let mut iter = pathname.split(|&b| b == b'/');
            let Some(user_part) = iter.next() else {
                return Ok(None);
            };
            let Some(project_part) = iter.next() else {
                return Ok(None);
            };
            let aux = iter.next();

            if let Some(a) = aux {
                if a == b"get" {
                    return Ok(None);
                }
            }

            let project = strings::trim_suffix(project_part, b".git");

            if user_part.is_empty() || project.is_empty() {
                return Ok(None);
            }

            let fragment_str = OwnedString::new(url.fragment_identifier());
            let fragment_utf8 = fragment_str.to_utf8();
            let fragment = fragment_utf8.slice();
            let committish: Option<&[u8]> = if !fragment.is_empty() {
                Some(fragment)
            } else {
                None
            };

            let mut sb = StringBuilder::default();
            sb.count(user_part);
            sb.count(project);
            if let Some(c) = committish {
                sb.count(c);
            }

            sb.allocate()?;

            let user_slice = HostedGitInfo::decode_and_append(&mut sb, user_part)?;
            let project_slice = HostedGitInfo::decode_and_append(&mut sb, project)?;
            let committish_slice = match committish {
                Some(c) => Some(HostedGitInfo::decode_and_append(&mut sb, c)?),
                None => None,
            };

            Ok(Some(ExtractResult {
                user: Some(user_slice),
                project: project_slice,
                committish: committish_slice,
                _owned_buffer: Some(sb.move_to_slice()),
            }))
        }

        pub(crate) fn gitlab(url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError> {
            let pathname_owned = url.pathname().to_owned_slice();
            let pathname = strings::trim_prefix(&pathname_owned, b"/");

            if strings::index_of(pathname, b"/-/").is_some()
                || strings::index_of(pathname, b"/archive.tar.gz").is_some()
            {
                return Ok(None);
            }

            let Some(end_slash) = strings::last_index_of_char(pathname, b'/') else {
                return Ok(None);
            };
            let project_part = &pathname[end_slash + 1..];
            let user_part = &pathname[0..end_slash];

            let project = strings::trim_suffix(project_part, b".git");

            if user_part.is_empty() || project.is_empty() {
                return Ok(None);
            }

            let fragment_str = OwnedString::new(url.fragment_identifier());
            let fragment_utf8 = fragment_str.to_utf8();
            let committish = fragment_utf8.slice();

            let mut sb = StringBuilder::default();
            sb.count(user_part);
            sb.count(project);
            if !committish.is_empty() {
                sb.count(committish);
            }

            sb.allocate()?;

            let user_slice = HostedGitInfo::decode_and_append(&mut sb, user_part)?;
            let project_slice = HostedGitInfo::decode_and_append(&mut sb, project)?;
            let committish_slice = if !committish.is_empty() {
                let Ok(r) = HostedGitInfo::decode_and_append(&mut sb, committish) else {
                    return Ok(None);
                };
                Some(r)
            } else {
                None
            };

            Ok(Some(ExtractResult {
                user: Some(user_slice),
                project: project_slice,
                committish: committish_slice,
                _owned_buffer: Some(sb.move_to_slice()),
            }))
        }

        pub(crate) fn gist(url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError> {
            let pathname_owned = url.pathname().to_owned_slice();
            let pathname = strings::trim_prefix(&pathname_owned, b"/");

            let mut iter = pathname.split(|&b| b == b'/');
            let Some(mut user_part) = iter.next() else {
                return Ok(None);
            };
            let mut project_part = iter.next();
            let aux = iter.next();

            if let Some(a) = aux {
                if a == b"raw" {
                    return Ok(None);
                }
            }

            if project_part.is_none() || project_part.unwrap().is_empty() {
                project_part = Some(user_part);
                user_part = b"";
            }

            let project = strings::trim_suffix(project_part.unwrap(), b".git");
            let user: Option<&[u8]> = if !user_part.is_empty() {
                Some(user_part)
            } else {
                None
            };

            if project.is_empty() {
                return Ok(None);
            }

            let fragment_str = OwnedString::new(url.fragment_identifier());
            let fragment_utf8 = fragment_str.to_utf8();
            let fragment = fragment_utf8.slice();
            let committish: Option<&[u8]> = if !fragment.is_empty() {
                Some(fragment)
            } else {
                None
            };

            let mut sb = StringBuilder::default();
            if let Some(u) = user {
                sb.count(u);
            }
            sb.count(project);
            if let Some(c) = committish {
                sb.count(c);
            }

            let Ok(()) = sb.allocate() else {
                return Ok(None);
            };

            let user_slice = match user {
                Some(u) => {
                    let Ok(r) = HostedGitInfo::decode_and_append(&mut sb, u) else {
                        return Ok(None);
                    };
                    Some(r)
                }
                None => None,
            };
            let Ok(project_slice) = HostedGitInfo::decode_and_append(&mut sb, project) else {
                return Ok(None);
            };
            let committish_slice = match committish {
                Some(c) => {
                    let Ok(r) = HostedGitInfo::decode_and_append(&mut sb, c) else {
                        return Ok(None);
                    };
                    Some(r)
                }
                None => None,
            };

            Ok(Some(ExtractResult {
                user: user_slice,
                project: project_slice,
                committish: committish_slice,
                _owned_buffer: Some(sb.move_to_slice()),
            }))
        }

        pub(crate) fn sourcehut(url: &JscUrl) -> Result<Option<ExtractResult>, HostedGitInfoError> {
            let pathname_owned = url.pathname().to_owned_slice();
            let pathname = strings::trim_prefix(&pathname_owned, b"/");

            let mut iter = pathname.split(|&b| b == b'/');
            let Some(user_part) = iter.next() else {
                return Ok(None);
            };
            let Some(project_part) = iter.next() else {
                return Ok(None);
            };
            let aux = iter.next();

            if let Some(a) = aux {
                if a == b"archive" {
                    return Ok(None);
                }
            }

            let project = strings::trim_suffix(project_part, b".git");

            if user_part.is_empty() || project.is_empty() {
                return Ok(None);
            }

            let fragment_str = OwnedString::new(url.fragment_identifier());
            let fragment_utf8 = fragment_str.to_utf8();
            let fragment = fragment_utf8.slice();
            let committish: Option<&[u8]> = if !fragment.is_empty() {
                Some(fragment)
            } else {
                None
            };

            let mut sb = StringBuilder::default();
            sb.count(user_part);
            sb.count(project);
            if let Some(c) = committish {
                sb.count(c);
            }

            let Ok(()) = sb.allocate() else {
                return Ok(None);
            };

            // PORT NOTE: Zig inlines PercentEncoding.decode here instead of calling
            // decodeAndAppend (returns null instead of erroring on decode failure).
            let user_slice = 'blk: {
                let start = sb.len;
                let writable = sb.writable();
                let Ok(decoded_len) = PercentEncoding::decode_into(writable, user_part) else {
                    return Ok(None);
                };
                let decoded_len = decoded_len as usize;
                sb.len += decoded_len;
                break 'blk start..start + decoded_len;
            };
            let project_slice = 'blk: {
                let start = sb.len;
                let writable = sb.writable();
                let Ok(decoded_len) = PercentEncoding::decode_into(writable, project) else {
                    return Ok(None);
                };
                let decoded_len = decoded_len as usize;
                sb.len += decoded_len;
                break 'blk start..start + decoded_len;
            };
            let committish_slice = if let Some(c) = committish {
                let start = sb.len;
                let writable = sb.writable();
                let Ok(decoded_len) = PercentEncoding::decode_into(writable, c) else {
                    return Ok(None);
                };
                let decoded_len = decoded_len as usize;
                sb.len += decoded_len;
                Some(start..start + decoded_len)
            } else {
                None
            };

            Ok(Some(ExtractResult {
                user: Some(user_slice),
                project: project_slice,
                committish: committish_slice,
                _owned_buffer: Some(sb.move_to_slice()),
            }))
        }
    }

    /// Mirrors hosts.js's gittemplate
    pub mod git {
        use super::*;

        pub type Type = Option<
            fn(
                self_: HostProvider,
                auth: Option<&[u8]>,
                user: Option<&[u8]>,
                project: &[u8],
                committish: Option<&[u8]>,
            ) -> Result<Vec<u8>, AllocError>,
        >;

        pub(crate) const DEFAULT: Type = None;

        pub(crate) fn github(
            self_: HostProvider,
            auth: Option<&[u8]>,
            user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            requires_user(user);

            let auth_str: &[u8] = auth.unwrap_or(b"");
            let auth_sep: &[u8] = if !auth_str.is_empty() { b"@" } else { b"" };
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git://{}{}{}/{}/{}.git{}{}",
                BStr::new(auth_str),
                BStr::new(auth_sep),
                BStr::new(self_.domain()),
                BStr::new(user.unwrap()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }

        pub(crate) fn gist(
            self_: HostProvider,
            _auth: Option<&[u8]>,
            _user: Option<&[u8]>,
            project: &[u8],
            committish: Option<&[u8]>,
        ) -> Result<Vec<u8>, AllocError> {
            let cmsh: &[u8] = committish.unwrap_or(b"");
            let cmsh_sep: &[u8] = if !cmsh.is_empty() { b"#" } else { b"" };

            let mut v = Vec::new();
            write!(
                &mut v,
                "git://{}/{}.git{}{}",
                BStr::new(self_.domain()),
                BStr::new(project),
                BStr::new(cmsh_sep),
                BStr::new(cmsh),
            )
            .map_err(|_| AllocError)?;
            Ok(v)
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// configs (std.enums.EnumArray)
// ──────────────────────────────────────────────────────────────────────────

// PERF(port): was `std.enums.EnumArray(Self, Config).init(.{...})` (comptime
// dense array indexed by enum). `enum_map::EnumMap` can't be const-initialized
// with fn pointers, so this uses a `OnceLock` static — flatten into a
// `match`-based accessor if it shows up on a hot path.
fn configs() -> &'static EnumMap<HostProvider, Config> {
    use std::sync::OnceLock;
    static CONFIGS: OnceLock<EnumMap<HostProvider, Config>> = OnceLock::new();
    CONFIGS.get_or_init(|| {
        EnumMap::from_fn(|k| match k {
            HostProvider::Bitbucket => Config {
                protocols: &[
                    WellDefinedProtocol::GitPlusHttp,
                    WellDefinedProtocol::GitPlusHttps,
                    WellDefinedProtocol::Ssh,
                    WellDefinedProtocol::Https,
                ],
                domain: b"bitbucket.org",
                shortcut: b"bitbucket:",
                tree_path: Some(b"src"),
                blob_path: Some(b"src"),
                edit_path: Some(b"?mode=edit"),
                format_ssh: formatters::ssh::default,
                format_sshurl: formatters::ssh_url::default,
                format_https: formatters::https::default,
                format_shortcut: formatters::shortcut::default,
                format_git: formatters::git::DEFAULT,
                format_extract: formatters::extract::bitbucket,
            },
            HostProvider::Gist => Config {
                protocols: &[
                    WellDefinedProtocol::Git,
                    WellDefinedProtocol::GitPlusSsh,
                    WellDefinedProtocol::GitPlusHttps,
                    WellDefinedProtocol::Ssh,
                    WellDefinedProtocol::Https,
                ],
                domain: b"gist.github.com",
                shortcut: b"gist:",
                tree_path: None,
                blob_path: None,
                edit_path: Some(b"edit"),
                format_ssh: formatters::ssh::gist,
                format_sshurl: formatters::ssh_url::gist,
                format_https: formatters::https::gist,
                format_shortcut: formatters::shortcut::gist,
                format_git: Some(formatters::git::gist),
                format_extract: formatters::extract::gist,
            },
            HostProvider::Github => Config {
                protocols: &[
                    WellDefinedProtocol::Git,
                    WellDefinedProtocol::Http,
                    WellDefinedProtocol::GitPlusSsh,
                    WellDefinedProtocol::GitPlusHttps,
                    WellDefinedProtocol::Ssh,
                    WellDefinedProtocol::Https,
                ],
                domain: b"github.com",
                shortcut: b"github:",
                tree_path: Some(b"tree"),
                blob_path: Some(b"blob"),
                edit_path: Some(b"edit"),
                format_ssh: formatters::ssh::default,
                format_sshurl: formatters::ssh_url::default,
                format_https: formatters::https::default,
                format_shortcut: formatters::shortcut::default,
                format_git: Some(formatters::git::github),
                format_extract: formatters::extract::github,
            },
            HostProvider::Gitlab => Config {
                protocols: &[
                    WellDefinedProtocol::GitPlusSsh,
                    WellDefinedProtocol::GitPlusHttps,
                    WellDefinedProtocol::Ssh,
                    WellDefinedProtocol::Https,
                ],
                domain: b"gitlab.com",
                shortcut: b"gitlab:",
                tree_path: Some(b"tree"),
                blob_path: Some(b"tree"),
                edit_path: Some(b"-/edit"),
                format_ssh: formatters::ssh::default,
                format_sshurl: formatters::ssh_url::default,
                format_https: formatters::https::default,
                format_shortcut: formatters::shortcut::default,
                format_git: formatters::git::DEFAULT,
                format_extract: formatters::extract::gitlab,
            },
            HostProvider::Sourcehut => Config {
                protocols: &[WellDefinedProtocol::GitPlusSsh, WellDefinedProtocol::Https],
                domain: b"git.sr.ht",
                shortcut: b"sourcehut:",
                tree_path: Some(b"tree"),
                blob_path: Some(b"tree"),
                edit_path: None,
                format_ssh: formatters::ssh::default,
                format_sshurl: formatters::ssh_url::default,
                format_https: formatters::https::sourcehut,
                format_shortcut: formatters::shortcut::default,
                format_git: formatters::git::DEFAULT,
                format_extract: formatters::extract::sourcehut,
            },
        })
    })
}

// ──────────────────────────────────────────────────────────────────────────
// TestingAPIs
// ──────────────────────────────────────────────────────────────────────────

// PORT NOTE (layering): `pub const X = @import("../install_jsc/...")` aliases deleted —
// `js_parse_url` / `js_from_url` live in `bun_install_jsc` (higher tier). Re-exporting
// them here would re-introduce the install ↔ jsc cycle. Module kept as a marker so
// Zig grep for `TestingAPIs` still lands here.
pub mod testing_apis {}

// ported from: src/install/hosted_git_info.zig