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
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
|
const std = @import("std");
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const hasRef = std.meta.trait.hasField("ref");
const C_API = @import("root").bun.JSC.C;
const StringPointer = @import("../../api/schema.zig").Api.StringPointer;
const Exports = @import("./exports.zig");
const strings = bun.strings;
const ErrorableZigString = Exports.ErrorableZigString;
const ErrorableResolvedSource = Exports.ErrorableResolvedSource;
const ZigException = Exports.ZigException;
const ZigStackTrace = Exports.ZigStackTrace;
const is_bindgen: bool = std.meta.globalOption("bindgen", bool) orelse false;
const ArrayBuffer = @import("../base.zig").ArrayBuffer;
const JSC = @import("root").bun.JSC;
const Shimmer = JSC.Shimmer;
const FFI = @import("./FFI.zig");
const NullableAllocator = @import("../../nullable_allocator.zig").NullableAllocator;
const MutableString = bun.MutableString;
const JestPrettyFormat = @import("../test/pretty_format.zig").JestPrettyFormat;
const String = bun.String;
const ErrorableString = JSC.ErrorableString;
pub const JSObject = extern struct {
pub const shim = Shimmer("JSC", "JSObject", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSObject.h";
pub const name = "JSC::JSObject";
pub const namespace = "JSC";
pub fn getArrayLength(this: *JSObject) usize {
return cppFn("getArrayLength", .{
this,
});
}
const InitializeCallback = *const fn (ctx: ?*anyopaque, obj: [*c]JSObject, global: [*c]JSGlobalObject) callconv(.C) void;
pub fn create(global_object: *JSGlobalObject, length: usize, ctx: *anyopaque, initializer: InitializeCallback) JSValue {
return cppFn("create", .{
global_object,
length,
ctx,
initializer,
});
}
pub fn Initializer(comptime Ctx: type, comptime func: fn (*Ctx, obj: *JSObject, global: *JSGlobalObject) void) type {
return struct {
pub fn call(this: ?*anyopaque, obj: [*c]JSObject, global: [*c]JSGlobalObject) callconv(.C) void {
@call(.always_inline, func, .{ @as(*Ctx, @ptrCast(@alignCast(this.?))), obj.?, global.? });
}
};
}
pub fn createWithInitializer(comptime Ctx: type, creator: *Ctx, global: *JSGlobalObject, length: usize) JSValue {
const Type = Initializer(Ctx, Ctx.create);
return create(global, length, creator, Type.call);
}
pub fn getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSValue {
return cppFn("getIndex", .{
this,
globalThis,
i,
});
}
pub fn putRecord(this: *JSObject, global: *JSGlobalObject, key: *ZigString, values: [*]ZigString, values_len: usize) void {
return cppFn("putRecord", .{ this, global, key, values, values_len });
}
pub fn getDirect(this: *JSObject, globalThis: *JSGlobalObject, str: *const ZigString) JSValue {
return cppFn("getDirect", .{
this,
globalThis,
str,
});
}
pub const Extern = [_][]const u8{
"putRecord",
"create",
"getArrayLength",
"getIndex",
"putAtIndex",
"getDirect",
};
};
/// Prefer using bun.String instead of ZigString in new code.
pub const ZigString = extern struct {
/// This can be a UTF-16, Latin1, or UTF-8 string.
/// The pointer itself is tagged, so it cannot be used without untagging it first
/// Accessing it directly is unsafe.
_unsafe_ptr_do_not_use: [*]const u8,
len: usize,
pub const ByteString = union(enum) {
latin1: []const u8,
utf16: []const u16,
};
pub fn fromBytes(slice_: []const u8) ZigString {
if (!strings.isAllASCII(slice_))
return fromUTF8(slice_);
return init(slice_);
}
pub inline fn as(this: ZigString) ByteString {
return if (this.is16Bit()) .{ .utf16 = this.utf16SliceAligned() } else .{ .latin1 = this.slice() };
}
pub fn encode(this: ZigString, encoding: JSC.Node.Encoding) []u8 {
return switch (this.as()) {
inline else => |repr| switch (encoding) {
inline else => |enc| JSC.WebCore.Encoder.constructFrom(std.meta.Child(@TypeOf(repr)), repr, enc),
},
};
}
pub fn dupeForJS(utf8: []const u8, allocator: std.mem.Allocator) !ZigString {
if (try strings.toUTF16Alloc(allocator, utf8, false)) |utf16| {
var out = ZigString.init16(utf16);
out.mark();
out.markUTF16();
return out;
} else {
var out = ZigString.init(try allocator.dupe(u8, utf8));
out.mark();
return out;
}
}
pub fn toJS(this: ZigString, ctx: *JSC.JSGlobalObject, _: JSC.C.ExceptionRef) JSValue {
if (this.isGloballyAllocated()) {
return this.toExternalValue(ctx);
}
return this.toValueAuto(ctx);
}
/// This function is not optimized!
pub fn eqlCaseInsensitive(this: ZigString, other: ZigString) bool {
var fallback = std.heap.stackFallback(1024, bun.default_allocator);
var fallback_allocator = fallback.get();
var utf16_slice = this.toSliceLowercase(fallback_allocator);
var latin1_slice = other.toSliceLowercase(fallback_allocator);
defer utf16_slice.deinit();
defer latin1_slice.deinit();
return strings.eqlLong(utf16_slice.slice(), latin1_slice.slice(), true);
}
pub fn toSliceLowercase(this: ZigString, allocator: std.mem.Allocator) Slice {
if (this.len == 0)
return Slice.empty;
var fallback = std.heap.stackFallback(512, allocator);
var fallback_allocator = fallback.get();
var uppercase_buffer = this.toOwnedSlice(fallback_allocator) catch unreachable;
var buffer = allocator.alloc(u8, uppercase_buffer.len) catch unreachable;
var out = strings.copyLowercase(uppercase_buffer, buffer);
return Slice{
.allocator = NullableAllocator.init(allocator),
.ptr = out.ptr,
.len = @as(u32, @truncate(out.len)),
};
}
pub fn indexOfAny(this: ZigString, comptime chars: []const u8) ?strings.OptionalUsize {
if (this.is16Bit()) {
return strings.indexOfAny16(this.utf16SliceAligned(), chars);
} else {
return strings.indexOfAny(this.slice(), chars);
}
}
pub fn charAt(this: ZigString, offset: usize) u8 {
if (this.is16Bit()) {
return @as(u8, @truncate(this.utf16SliceAligned()[offset]));
} else {
return @as(u8, @truncate(this.slice()[offset]));
}
}
pub fn eql(this: ZigString, other: ZigString) bool {
if (this.len == 0 or other.len == 0)
return this.len == other.len;
const left_utf16 = this.is16Bit();
const right_utf16 = other.is16Bit();
if (left_utf16 == right_utf16 and left_utf16) {
return strings.eqlLong(std.mem.sliceAsBytes(this.utf16SliceAligned()), std.mem.sliceAsBytes(other.utf16SliceAligned()), true);
} else if (left_utf16 == right_utf16) {
return strings.eqlLong(this.slice(), other.slice(), true);
}
const utf16: ZigString = if (left_utf16) this else other;
const latin1: ZigString = if (left_utf16) other else this;
if (latin1.isAllASCII()) {
return strings.utf16EqlString(utf16.utf16SliceAligned(), latin1.slice());
}
// slow path
var utf16_slice = utf16.toSlice(bun.default_allocator);
var latin1_slice = latin1.toSlice(bun.default_allocator);
defer utf16_slice.deinit();
defer latin1_slice.deinit();
return strings.eqlLong(utf16_slice.slice(), latin1_slice.slice(), true);
}
pub fn isAllASCII(this: ZigString) bool {
if (this.is16Bit()) {
return strings.firstNonASCII16([]const u16, this.utf16SliceAligned()) == null;
}
return strings.isAllASCII(this.slice());
}
pub fn clone(this: ZigString, allocator: std.mem.Allocator) !ZigString {
var sliced = this.toSlice(allocator);
if (!sliced.isAllocated()) {
var str = ZigString.init(try allocator.dupe(u8, sliced.slice()));
str.mark();
str.markUTF8();
return str;
}
return this;
}
extern fn ZigString__toJSONObject(this: *const ZigString, *JSC.JSGlobalObject) callconv(.C) JSC.JSValue;
pub fn toJSONObject(this: ZigString, globalThis: *JSC.JSGlobalObject) JSValue {
JSC.markBinding(@src());
return ZigString__toJSONObject(&this, globalThis);
}
pub fn hasPrefixChar(this: ZigString, char: u8) bool {
if (this.len == 0)
return false;
if (this.is16Bit()) {
return this.utf16SliceAligned()[0] == char;
}
return this.slice()[0] == char;
}
pub fn substringWithLen(this: ZigString, offset: usize, len: usize) ZigString {
if (this.is16Bit()) {
return ZigString.from16Slice(this.utf16SliceAligned()[@min(this.len, offset)..len]);
}
var out = ZigString.init(this.slice()[@min(this.len, offset)..len]);
if (this.isUTF8()) {
out.markUTF8();
}
if (this.isGloballyAllocated()) {
out.mark();
}
return out;
}
pub fn substring(this: ZigString, offset: usize, maxlen: usize) ZigString {
var len: usize = undefined;
if (maxlen == 0) {
len = this.len;
} else {
len = @max(this.len, maxlen);
}
return this.substringWithLen(offset, len);
}
pub fn maxUTF8ByteLength(this: ZigString) usize {
if (this.isUTF8())
return this.len;
if (this.is16Bit()) {
return this.utf16SliceAligned().len * 3;
}
// latin1
return this.len * 2;
}
pub fn utf16ByteLength(this: ZigString) usize {
if (this.isUTF8()) {
return bun.simdutf.length.utf16.from.utf8.le(this.slice());
}
if (this.is16Bit()) {
return this.len * 2;
}
return JSC.WebCore.Encoder.byteLengthU8(this.slice().ptr, this.slice().len, .utf16le);
}
pub fn latin1ByteLength(this: ZigString) usize {
if (this.isUTF8()) {
@panic("TODO");
}
return this.len;
}
/// Count the number of bytes in the UTF-8 version of the string.
/// This function is slow. Use maxUITF8ByteLength() to get a quick estimate
pub fn utf8ByteLength(this: ZigString) usize {
if (this.isUTF8()) {
return this.len;
}
if (this.is16Bit()) {
return JSC.WebCore.Encoder.byteLengthU16(this.utf16SliceAligned().ptr, this.utf16Slice().len, .utf8);
}
return JSC.WebCore.Encoder.byteLengthU8(this.slice().ptr, this.slice().len, .utf8);
}
pub fn toOwnedSlice(this: ZigString, allocator: std.mem.Allocator) ![]u8 {
if (this.isUTF8())
return try allocator.dupeZ(u8, this.slice());
var list = std.ArrayList(u8).init(allocator);
list = if (this.is16Bit())
try strings.toUTF8ListWithType(list, []const u16, this.utf16SliceAligned())
else
try strings.allocateLatin1IntoUTF8WithList(list, 0, []const u8, this.slice());
if (list.capacity > list.items.len) {
list.items.ptr[list.items.len] = 0;
}
return list.items;
}
pub fn toOwnedSliceZ(this: ZigString, allocator: std.mem.Allocator) ![:0]u8 {
if (this.isUTF8())
return allocator.dupeZ(u8, this.slice());
var list = std.ArrayList(u8).init(allocator);
list = if (this.is16Bit())
try strings.toUTF8ListWithType(list, []const u16, this.utf16SliceAligned())
else
try strings.allocateLatin1IntoUTF8WithList(list, 0, []const u8, this.slice());
try list.append(0);
return list.items[0 .. list.items.len - 1 :0];
}
pub fn trunc(this: ZigString, len: usize) ZigString {
return .{ ._unsafe_ptr_do_not_use = this._unsafe_ptr_do_not_use, .len = @min(len, this.len) };
}
pub fn eqlComptime(this: ZigString, comptime other: []const u8) bool {
if (this.is16Bit()) {
return strings.eqlComptimeUTF16(this.utf16SliceAligned(), other);
}
if (comptime strings.isAllASCIISimple(other)) {
if (this.len != other.len)
return false;
return strings.eqlComptimeIgnoreLen(this.slice(), other);
}
@compileError("Not implemented yet for latin1");
}
pub const shim = Shimmer("", "ZigString", @This());
pub inline fn length(this: ZigString) usize {
return this.len;
}
pub fn byteSlice(this: ZigString) []const u8 {
if (this.is16Bit()) {
return std.mem.sliceAsBytes(this.utf16SliceAligned());
}
return this.slice();
}
pub fn markStatic(this: *ZigString) void {
this.ptr = @as([*]const u8, @ptrFromInt(@intFromPtr(this.ptr) | (1 << 60)));
}
pub fn isStatic(this: *const ZigString) bool {
return @intFromPtr(this.ptr) & (1 << 60) != 0;
}
pub const Slice = struct {
allocator: NullableAllocator = .{},
ptr: [*]const u8 = undefined,
len: u32 = 0,
pub fn init(allocator: std.mem.Allocator, input: []const u8) Slice {
return .{
.ptr = input.ptr,
.len = @as(u32, @truncate(input.len)),
.allocator = NullableAllocator.init(allocator),
};
}
pub fn toZigString(this: Slice) ZigString {
if (this.isAllocated())
return ZigString.initUTF8(this.ptr[0..this.len]);
return ZigString.init(this.slice());
}
pub inline fn length(this: Slice) usize {
return this.len;
}
pub const byteSlice = Slice.slice;
pub fn from(input: []u8, allocator: std.mem.Allocator) Slice {
return .{
.ptr = input.ptr,
.len = @as(u32, @truncate(input.len)),
.allocator = NullableAllocator.init(allocator),
};
}
pub fn fromUTF8NeverFree(input: []const u8) Slice {
return .{
.ptr = input.ptr,
.len = @as(u32, @truncate(input.len)),
.allocator = .{},
};
}
pub const empty = Slice{ .ptr = undefined, .len = 0 };
pub inline fn isAllocated(this: Slice) bool {
return !this.allocator.isNull();
}
pub fn clone(this: Slice, allocator: std.mem.Allocator) !Slice {
if (this.isAllocated()) {
return Slice{ .allocator = this.allocator, .ptr = this.ptr, .len = this.len };
}
var duped = try allocator.dupe(u8, this.ptr[0..this.len]);
return Slice{ .allocator = NullableAllocator.init(allocator), .ptr = duped.ptr, .len = this.len };
}
pub fn cloneIfNeeded(this: Slice, allocator: std.mem.Allocator) !Slice {
if (this.isAllocated()) {
return this;
}
var duped = try allocator.dupe(u8, this.ptr[0..this.len]);
return Slice{ .allocator = NullableAllocator.init(allocator), .ptr = duped.ptr, .len = this.len };
}
pub fn cloneWithTrailingSlash(this: Slice, allocator: std.mem.Allocator) !Slice {
var buf = try strings.cloneNormalizingSeparators(allocator, this.slice());
return Slice{ .allocator = NullableAllocator.init(allocator), .ptr = buf.ptr, .len = @as(u32, @truncate(buf.len)) };
}
pub fn cloneZ(this: Slice, allocator: std.mem.Allocator) !Slice {
if (this.isAllocated() or this.len == 0) {
return this;
}
var duped = try allocator.dupeZ(u8, this.ptr[0..this.len]);
return Slice{ .allocator = NullableAllocator.init(allocator), .ptr = duped.ptr, .len = this.len };
}
pub fn slice(this: Slice) []const u8 {
return this.ptr[0..this.len];
}
pub fn sliceZ(this: Slice) [:0]const u8 {
return bun.cstring(this.ptr[0..this.len]);
}
pub fn toSliceZ(this: Slice, buf: []u8) [:0]const u8 {
if (this.len == 0) {
return "";
}
if (this.ptr[this.len] == 0) {
return this.sliceZ();
}
if (this.len >= buf.len) {
return "";
}
bun.copy(u8, buf, this.slice());
buf[this.len] = 0;
return bun.cstring(buf[0..this.len]);
}
pub fn mut(this: Slice) []u8 {
return @as([*]u8, @ptrFromInt(@intFromPtr(this.ptr)))[0..this.len];
}
/// Does nothing if the slice is not allocated
pub fn deinit(this: *const Slice) void {
if (this.allocator.get()) |allocator| {
if (bun.String.isWTFAllocator(allocator)) {
// workaround for https://github.com/ziglang/zig/issues/4298
bun.String.StringImplAllocator.free(allocator.ptr, bun.constStrToU8(this.slice()), 0, 0);
return;
}
allocator.free(this.slice());
}
}
};
pub const name = "ZigString";
pub const namespace = "";
pub inline fn is16Bit(this: *const ZigString) bool {
return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 63)) != 0;
}
pub inline fn utf16Slice(this: *const ZigString) []align(1) const u16 {
if (comptime bun.Environment.allow_assert) {
if (this.len > 0 and !this.is16Bit()) {
@panic("ZigString.utf16Slice() called on a latin1 string.\nPlease use .toSlice() instead or carefully check that .is16Bit() is false first.");
}
}
return @as([*]align(1) const u16, @ptrCast(untagged(this._unsafe_ptr_do_not_use)))[0..this.len];
}
pub inline fn utf16SliceAligned(this: *const ZigString) []const u16 {
if (comptime bun.Environment.allow_assert) {
if (this.len > 0 and !this.is16Bit()) {
@panic("ZigString.utf16SliceAligned() called on a latin1 string.\nPlease use .toSlice() instead or carefully check that .is16Bit() is false first.");
}
}
return @as([*]const u16, @ptrCast(@alignCast(untagged(this._unsafe_ptr_do_not_use))))[0..this.len];
}
pub inline fn isEmpty(this: *const ZigString) bool {
return this.len == 0;
}
pub fn fromStringPointer(ptr: StringPointer, buf: string, to: *ZigString) void {
to.* = ZigString{
.len = ptr.length,
._unsafe_ptr_do_not_use = buf[ptr.offset..][0..ptr.length].ptr,
};
}
pub fn sortDesc(slice_: []ZigString) void {
std.sort.block(ZigString, slice_, {}, cmpDesc);
}
pub fn cmpDesc(_: void, a: ZigString, b: ZigString) bool {
return strings.cmpStringsDesc({}, a.slice(), b.slice());
}
pub fn sortAsc(slice_: []ZigString) void {
std.sort.block(ZigString, slice_, {}, cmpAsc);
}
pub fn cmpAsc(_: void, a: ZigString, b: ZigString) bool {
return strings.cmpStringsAsc({}, a.slice(), b.slice());
}
pub inline fn init(slice_: []const u8) ZigString {
return ZigString{ ._unsafe_ptr_do_not_use = slice_.ptr, .len = slice_.len };
}
pub fn initUTF8(slice_: []const u8) ZigString {
var out = init(slice_);
out.markUTF8();
return out;
}
pub fn fromUTF8(slice_: []const u8) ZigString {
var out = init(slice_);
if (!strings.isAllASCII(slice_))
out.markUTF8();
return out;
}
pub fn static(comptime slice_: []const u8) *const ZigString {
const Holder = struct {
pub const value = ZigString{ ._unsafe_ptr_do_not_use = slice_.ptr, .len = slice_.len };
};
return &Holder.value;
}
pub const GithubActionFormatter = struct {
text: ZigString,
pub fn format(this: GithubActionFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
var bytes = this.text.toSlice(bun.default_allocator);
defer bytes.deinit();
try strings.githubActionWriter(writer, bytes.slice());
}
};
pub fn githubAction(this: ZigString) GithubActionFormatter {
return GithubActionFormatter{ .text = this };
}
pub fn toAtomicValue(this: *const ZigString, globalThis: *JSC.JSGlobalObject) JSValue {
return shim.cppFn("toAtomicValue", .{ this, globalThis });
}
pub fn init16(slice_: []const u16) ZigString {
var out = ZigString{ ._unsafe_ptr_do_not_use = std.mem.sliceAsBytes(slice_).ptr, .len = slice_.len };
out.markUTF16();
return out;
}
pub fn from(slice_: JSC.C.JSValueRef, ctx: JSC.C.JSContextRef) ZigString {
return JSC.JSValue.fromRef(slice_).getZigString(ctx.ptr());
}
pub fn from16Slice(slice_: []const u16) ZigString {
return from16(slice_.ptr, slice_.len);
}
/// Globally-allocated memory only
pub fn from16(slice_: [*]const u16, len: usize) ZigString {
var str = init(@as([*]const u8, @ptrCast(slice_))[0..len]);
str.markUTF16();
str.mark();
str.assertGlobal();
return str;
}
pub fn toBase64DataURL(this: ZigString, allocator: std.mem.Allocator) ![]const u8 {
const slice_ = this.slice();
const size = std.base64.standard.Encoder.calcSize(slice_.len);
var buf = try allocator.alloc(u8, size + "data:;base64,".len);
var encoded = std.base64.url_safe.Encoder.encode(buf["data:;base64,".len..], slice_);
buf[0.."data:;base64,".len].* = "data:;base64,".*;
return buf[0 .. "data:;base64,".len + encoded.len];
}
pub fn detectEncoding(this: *ZigString) void {
if (!strings.isAllASCII(this.slice())) {
this.markUTF16();
}
}
pub fn toExternalU16(ptr: [*]const u16, len: usize, global: *JSGlobalObject) JSValue {
return shim.cppFn("toExternalU16", .{ ptr, len, global });
}
pub fn isUTF8(this: ZigString) bool {
return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 61)) != 0;
}
pub fn markUTF8(this: *ZigString) void {
this._unsafe_ptr_do_not_use = @as([*]const u8, @ptrFromInt(@intFromPtr(this._unsafe_ptr_do_not_use) | (1 << 61)));
}
pub fn markUTF16(this: *ZigString) void {
this._unsafe_ptr_do_not_use = @as([*]const u8, @ptrFromInt(@intFromPtr(this._unsafe_ptr_do_not_use) | (1 << 63)));
}
pub fn setOutputEncoding(this: *ZigString) void {
if (!this.is16Bit()) this.detectEncoding();
if (this.is16Bit()) this.markUTF8();
}
pub inline fn isGloballyAllocated(this: ZigString) bool {
return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 62)) != 0;
}
pub inline fn deinitGlobal(this: ZigString) void {
bun.default_allocator.free(this.slice());
}
pub const mark = markGlobal;
pub inline fn markGlobal(this: *ZigString) void {
this._unsafe_ptr_do_not_use = @as([*]const u8, @ptrFromInt(@intFromPtr(this._unsafe_ptr_do_not_use) | (1 << 62)));
}
pub fn format(self: ZigString, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
if (self.isUTF8()) {
try writer.writeAll(self.slice());
return;
}
if (self.is16Bit()) {
try strings.formatUTF16(self.utf16Slice(), writer);
return;
}
try strings.formatLatin1(self.slice(), writer);
}
pub inline fn toRef(slice_: []const u8, global: *JSGlobalObject) C_API.JSValueRef {
return init(slice_).toValue(global).asRef();
}
pub const Empty = ZigString{ ._unsafe_ptr_do_not_use = "", .len = 0 };
inline fn untagged(ptr: [*]const u8) [*]const u8 {
// this can be null ptr, so long as it's also a 0 length string
@setRuntimeSafety(false);
return @as([*]const u8, @ptrFromInt(@as(u53, @truncate(@intFromPtr(ptr)))));
}
pub fn slice(this: *const ZigString) []const u8 {
if (comptime bun.Environment.allow_assert) {
if (this.len > 0 and this.is16Bit()) {
@panic("ZigString.slice() called on a UTF-16 string.\nPlease use .toSlice() instead or carefully check that .is16Bit() is false first.");
}
}
return untagged(this._unsafe_ptr_do_not_use)[0..@min(this.len, std.math.maxInt(u32))];
}
pub fn dupe(this: ZigString, allocator: std.mem.Allocator) ![]const u8 {
return try allocator.dupe(u8, this.slice());
}
pub fn toSliceFast(this: ZigString, allocator: std.mem.Allocator) Slice {
if (this.len == 0)
return Slice.empty;
if (is16Bit(&this)) {
var buffer = this.toOwnedSlice(allocator) catch unreachable;
return Slice{
.ptr = buffer.ptr,
.len = @as(u32, @truncate(buffer.len)),
.allocator = NullableAllocator.init(allocator),
};
}
return Slice{
.ptr = untagged(this._unsafe_ptr_do_not_use),
.len = @as(u32, @truncate(this.len)),
};
}
/// This function checks if the input is latin1 non-ascii
/// It is slow but safer when the input is from JavaScript
pub fn toSlice(this: ZigString, allocator: std.mem.Allocator) Slice {
if (this.len == 0)
return Slice.empty;
if (is16Bit(&this)) {
const buffer = this.toOwnedSlice(allocator) catch unreachable;
return Slice{
.allocator = NullableAllocator.init(allocator),
.ptr = buffer.ptr,
.len = @as(u32, @truncate(buffer.len)),
};
}
if (!this.isUTF8() and !strings.isAllASCII(untagged(this._unsafe_ptr_do_not_use)[0..this.len])) {
const buffer = this.toOwnedSlice(allocator) catch unreachable;
return Slice{
.allocator = NullableAllocator.init(allocator),
.ptr = buffer.ptr,
.len = @as(u32, @truncate(buffer.len)),
};
}
return Slice{
.ptr = untagged(this._unsafe_ptr_do_not_use),
.len = @as(u32, @truncate(this.len)),
};
}
pub fn toSliceClone(this: ZigString, allocator: std.mem.Allocator) Slice {
if (this.len == 0)
return Slice.empty;
const buffer = this.toOwnedSlice(allocator) catch unreachable;
return Slice{
.allocator = NullableAllocator.init(allocator),
.ptr = buffer.ptr,
.len = @as(u32, @truncate(buffer.len)),
};
}
pub fn toSliceZ(this: ZigString, allocator: std.mem.Allocator) Slice {
if (this.len == 0)
return Slice.empty;
if (is16Bit(&this)) {
var buffer = this.toOwnedSliceZ(allocator) catch unreachable;
return Slice{
.ptr = buffer.ptr,
.len = @as(u32, @truncate(buffer.len)),
.allocator = NullableAllocator.init(allocator),
};
}
return Slice{
.ptr = untagged(this._unsafe_ptr_do_not_use),
.len = @as(u32, @truncate(this.len)),
};
}
pub fn sliceZBuf(this: ZigString, buf: *[bun.MAX_PATH_BYTES]u8) ![:0]const u8 {
return try std.fmt.bufPrintZ(buf, "{}", .{this});
}
pub inline fn full(this: *const ZigString) []const u8 {
return untagged(this._unsafe_ptr_do_not_use)[0..this.len];
}
pub fn trimmedSlice(this: *const ZigString) []const u8 {
return strings.trim(this.full(), " \r\n");
}
pub fn toValueAuto(this: *const ZigString, global: *JSGlobalObject) JSValue {
if (!this.is16Bit()) {
return this.toValue(global);
} else {
return this.to16BitValue(global);
}
}
inline fn assertGlobalIfNeeded(this: *const ZigString) void {
if (comptime bun.Environment.allow_assert) {
if (this.isGloballyAllocated()) {
this.assertGlobal();
}
}
}
inline fn assertGlobal(this: *const ZigString) void {
if (comptime bun.Environment.allow_assert) {
std.debug.assert(this.len == 0 or
bun.Mimalloc.mi_is_in_heap_region(untagged(this._unsafe_ptr_do_not_use)) or
bun.Mimalloc.mi_check_owned(untagged(this._unsafe_ptr_do_not_use)));
}
}
pub fn toValue(this: *const ZigString, global: *JSGlobalObject) JSValue {
this.assertGlobalIfNeeded();
return shim.cppFn("toValue", .{ this, global });
}
pub fn toExternalValue(this: *const ZigString, global: *JSGlobalObject) JSValue {
this.assertGlobal();
return shim.cppFn("toExternalValue", .{ this, global });
}
pub fn toExternalValueWithCallback(
this: *const ZigString,
global: *JSGlobalObject,
callback: *const fn (ctx: ?*anyopaque, ptr: ?*anyopaque, len: usize) callconv(.C) void,
) JSValue {
return shim.cppFn("toExternalValueWithCallback", .{ this, global, callback });
}
pub fn external(
this: *const ZigString,
global: *JSGlobalObject,
ctx: ?*anyopaque,
callback: *const fn (ctx: ?*anyopaque, ptr: ?*anyopaque, len: usize) callconv(.C) void,
) JSValue {
return shim.cppFn("external", .{ this, global, ctx, callback });
}
pub fn to16BitValue(this: *const ZigString, global: *JSGlobalObject) JSValue {
this.assertGlobal();
return shim.cppFn("to16BitValue", .{ this, global });
}
pub fn toValueGC(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toValueGC", .{ this, global });
}
pub fn withEncoding(this: *const ZigString) ZigString {
var out = this.*;
out.setOutputEncoding();
return out;
}
pub fn toJSStringRef(this: *const ZigString) C_API.JSStringRef {
if (comptime @hasDecl(@import("root").bun, "bindgen")) {
return undefined;
}
return if (this.is16Bit())
C_API.JSStringCreateWithCharactersNoCopy(@as([*]const u16, @ptrCast(@alignCast(untagged(this._unsafe_ptr_do_not_use)))), this.len)
else
C_API.JSStringCreateStatic(untagged(this._unsafe_ptr_do_not_use), this.len);
}
pub fn toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toErrorInstance", .{ this, global });
}
pub fn toTypeErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toTypeErrorInstance", .{ this, global });
}
pub fn toSyntaxErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toSyntaxErrorInstance", .{ this, global });
}
pub fn toRangeErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toRangeErrorInstance", .{ this, global });
}
pub const Extern = [_][]const u8{
"toAtomicValue",
"toValue",
"toExternalValue",
"to16BitValue",
"toValueGC",
"toErrorInstance",
"toExternalU16",
"toExternalValueWithCallback",
"external",
"toTypeErrorInstance",
"toSyntaxErrorInstance",
"toRangeErrorInstance",
};
};
pub const DOMURL = opaque {
pub const shim = Shimmer("WebCore", "DOMURL", @This());
const cppFn = shim.cppFn;
pub const name = "WebCore::DOMURL";
pub fn cast_(value: JSValue, vm: *VM) ?*DOMURL {
return shim.cppFn("cast_", .{ value, vm });
}
pub fn cast(value: JSValue) ?*DOMURL {
return cast_(value, JSC.VirtualMachine.get().global.vm());
}
pub fn href_(this: *DOMURL, out: *ZigString) void {
return shim.cppFn("href_", .{ this, out });
}
pub fn href(this: *DOMURL) ZigString {
var out = ZigString.Empty;
this.href_(&out);
return out;
}
pub fn fileSystemPath(this: *DOMURL) bun.String {
return shim.cppFn("fileSystemPath", .{this});
}
pub fn pathname_(this: *DOMURL, out: *ZigString) void {
return shim.cppFn("pathname_", .{ this, out });
}
pub fn pathname(this: *DOMURL) ZigString {
var out = ZigString.Empty;
this.pathname_(&out);
return out;
}
pub const Extern = [_][]const u8{
"cast_",
"href_",
"pathname_",
"fileSystemPath",
};
};
const Api = @import("../../api/schema.zig").Api;
pub const DOMFormData = opaque {
pub const shim = Shimmer("WebCore", "DOMFormData", @This());
pub const name = "WebCore::DOMFormData";
pub const include = "DOMFormData.h";
pub const namespace = "WebCore";
const cppFn = shim.cppFn;
pub fn create(
global: *JSGlobalObject,
) JSValue {
return shim.cppFn("create", .{
global,
});
}
pub fn createFromURLQuery(
global: *JSGlobalObject,
query: *ZigString,
) JSValue {
return shim.cppFn("createFromURLQuery", .{
global,
query,
});
}
extern fn DOMFormData__toQueryString(
*DOMFormData,
ctx: *anyopaque,
callback: *const fn (ctx: *anyopaque, *ZigString) callconv(.C) void,
) void;
pub fn toQueryString(
this: *DOMFormData,
comptime Ctx: type,
ctx: Ctx,
comptime callback: fn (ctx: Ctx, ZigString) callconv(.C) void,
) void {
const Wrapper = struct {
const cb = callback;
pub fn run(c: *anyopaque, str: *ZigString) callconv(.C) void {
cb(@as(Ctx, @ptrCast(c)), str.*);
}
};
DOMFormData__toQueryString(this, ctx, &Wrapper.run);
}
pub fn fromJS(
value: JSValue,
) ?*DOMFormData {
return shim.cppFn("fromJS", .{
value,
});
}
pub fn append(
this: *DOMFormData,
name_: *ZigString,
value_: *ZigString,
) void {
return shim.cppFn("append", .{
this,
name_,
value_,
});
}
pub fn appendBlob(
this: *DOMFormData,
global: *JSC.JSGlobalObject,
name_: *ZigString,
blob: *anyopaque,
filename_: *ZigString,
) void {
return shim.cppFn("appendBlob", .{
this,
global,
name_,
blob,
filename_,
});
}
pub fn count(
this: *DOMFormData,
) usize {
return shim.cppFn("count", .{
this,
});
}
const ForEachFunction = *const fn (
ctx_ptr: ?*anyopaque,
name: *ZigString,
value_ptr: *anyopaque,
filename: ?*ZigString,
is_blob: u8,
) callconv(.C) void;
extern fn DOMFormData__forEach(*DOMFormData, ?*anyopaque, ForEachFunction) void;
pub const FormDataEntry = union(enum) {
string: ZigString,
file: struct {
blob: *JSC.WebCore.Blob,
filename: ZigString,
},
};
pub fn forEach(
this: *DOMFormData,
comptime Context: type,
ctx: *Context,
comptime callback_wrapper: *const fn (ctx: *Context, name: ZigString, value: FormDataEntry) void,
) void {
const Wrap = struct {
const wrapper = callback_wrapper;
pub fn forEachWrapper(
ctx_ptr: ?*anyopaque,
name_: *ZigString,
value_ptr: *anyopaque,
filename: ?*ZigString,
is_blob: u8,
) callconv(.C) void {
var ctx_ = bun.cast(*Context, ctx_ptr.?);
const value = if (is_blob == 0)
FormDataEntry{ .string = bun.cast(*ZigString, value_ptr).* }
else
FormDataEntry{
.file = .{
.blob = bun.cast(*JSC.WebCore.Blob, value_ptr),
.filename = (filename orelse &ZigString.Empty).*,
},
};
wrapper(ctx_, name_.*, value);
}
};
JSC.markBinding(@src());
DOMFormData__forEach(this, ctx, Wrap.forEachWrapper);
}
pub const Extern = [_][]const u8{
"create",
"fromJS",
"append",
"appendBlob",
"count",
"createFromURLQuery",
};
};
pub const FetchHeaders = opaque {
pub const shim = Shimmer("WebCore", "FetchHeaders", @This());
pub const name = "WebCore::FetchHeaders";
pub const include = "FetchHeaders.h";
pub const namespace = "WebCore";
const cppFn = shim.cppFn;
pub fn createValue(
global: *JSGlobalObject,
names: [*c]Api.StringPointer,
values: [*c]Api.StringPointer,
buf: *const ZigString,
count_: u32,
) JSValue {
return shim.cppFn("createValue", .{
global,
names,
values,
buf,
count_,
});
}
pub fn createFromJS(
global: *JSGlobalObject,
value: JSValue,
) ?*FetchHeaders {
return shim.cppFn("createFromJS", .{
global,
value,
});
}
pub fn putDefault(this: *FetchHeaders, name_: []const u8, value: []const u8, global: *JSGlobalObject) void {
if (this.has(&ZigString.init(name_), global)) {
return;
}
this.put_(&ZigString.init(name_), &ZigString.init(value), global);
}
pub fn from(
global: *JSGlobalObject,
names: [*c]Api.StringPointer,
values: [*c]Api.StringPointer,
buf: *const ZigString,
count_: u32,
) JSValue {
return shim.cppFn("createValue", .{
global,
names,
values,
buf,
count_,
});
}
pub fn isEmpty(this: *FetchHeaders) bool {
return shim.cppFn("isEmpty", .{
this,
});
}
pub fn createFromUWS(
global: *JSGlobalObject,
uws_request: *anyopaque,
) *FetchHeaders {
return shim.cppFn("createFromUWS", .{
global,
uws_request,
});
}
pub fn toUWSResponse(
headers: *FetchHeaders,
is_ssl: bool,
uws_response: *anyopaque,
) void {
return shim.cppFn("toUWSResponse", .{
headers,
is_ssl,
uws_response,
});
}
const PicoHeaders = extern struct {
ptr: ?*const anyopaque,
len: usize,
};
pub fn createEmpty() *FetchHeaders {
return shim.cppFn("createEmpty", .{});
}
pub fn createFromPicoHeaders(
pico_headers: anytype,
) *FetchHeaders {
const out = PicoHeaders{ .ptr = pico_headers.ptr, .len = pico_headers.len };
const result = shim.cppFn("createFromPicoHeaders_", .{
&out,
});
return result;
}
pub fn createFromPicoHeaders_(
pico_headers: *const anyopaque,
) *FetchHeaders {
return shim.cppFn("createFromPicoHeaders_", .{
pico_headers,
});
}
pub fn append(
this: *FetchHeaders,
name_: *const ZigString,
value: *const ZigString,
global: *JSGlobalObject,
) void {
return shim.cppFn("append", .{
this,
name_,
value,
global,
});
}
pub fn put_(
this: *FetchHeaders,
name_: *const ZigString,
value: *const ZigString,
global: *JSGlobalObject,
) void {
return shim.cppFn("put_", .{
this,
name_,
value,
global,
});
}
pub fn put(
this: *FetchHeaders,
name_: []const u8,
value: []const u8,
global: *JSGlobalObject,
) void {
this.put_(&ZigString.init(name_), &ZigString.init(value), global);
}
pub fn get_(
this: *FetchHeaders,
name_: *const ZigString,
out: *ZigString,
global: *JSGlobalObject,
) void {
shim.cppFn("get_", .{
this,
name_,
out,
global,
});
}
pub fn get(
this: *FetchHeaders,
name_: []const u8,
global: *JSGlobalObject,
) ?[]const u8 {
var out = ZigString.Empty;
get_(this, &ZigString.init(name_), &out, global);
if (out.len > 0) {
return out.slice();
}
return null;
}
pub fn has(
this: *FetchHeaders,
name_: *const ZigString,
global: *JSGlobalObject,
) bool {
return shim.cppFn("has", .{
this,
name_,
global,
});
}
pub fn fastHas(
this: *FetchHeaders,
name_: HTTPHeaderName,
) bool {
return fastHas_(this, @intFromEnum(name_));
}
pub fn fastGet(
this: *FetchHeaders,
name_: HTTPHeaderName,
) ?ZigString {
var str = ZigString.init("");
fastGet_(this, @intFromEnum(name_), &str);
if (str.len == 0) {
return null;
}
return str;
}
pub fn fastHas_(
this: *FetchHeaders,
name_: u8,
) bool {
return shim.cppFn("fastHas_", .{
this,
name_,
});
}
pub fn fastGet_(
this: *FetchHeaders,
name_: u8,
str: *ZigString,
) void {
return shim.cppFn("fastGet_", .{
this,
name_,
str,
});
}
pub const HTTPHeaderName = enum(u8) {
Accept,
AcceptCharset,
AcceptEncoding,
AcceptLanguage,
AcceptRanges,
AccessControlAllowCredentials,
AccessControlAllowHeaders,
AccessControlAllowMethods,
AccessControlAllowOrigin,
AccessControlExposeHeaders,
AccessControlMaxAge,
AccessControlRequestHeaders,
AccessControlRequestMethod,
Age,
Authorization,
CacheControl,
Connection,
ContentDisposition,
ContentEncoding,
ContentLanguage,
ContentLength,
ContentLocation,
ContentRange,
ContentSecurityPolicy,
ContentSecurityPolicyReportOnly,
ContentType,
Cookie,
Cookie2,
CrossOriginEmbedderPolicy,
CrossOriginEmbedderPolicyReportOnly,
CrossOriginOpenerPolicy,
CrossOriginOpenerPolicyReportOnly,
CrossOriginResourcePolicy,
DNT,
Date,
DefaultStyle,
ETag,
Expect,
Expires,
Host,
IcyMetaInt,
IcyMetadata,
IfMatch,
IfModifiedSince,
IfNoneMatch,
IfRange,
IfUnmodifiedSince,
KeepAlive,
LastEventID,
LastModified,
Link,
Location,
Origin,
PingFrom,
PingTo,
Pragma,
ProxyAuthorization,
Purpose,
Range,
Referer,
ReferrerPolicy,
Refresh,
ReportTo,
SecFetchDest,
SecFetchMode,
SecWebSocketAccept,
SecWebSocketExtensions,
SecWebSocketKey,
SecWebSocketProtocol,
SecWebSocketVersion,
ServerTiming,
ServiceWorker,
ServiceWorkerAllowed,
ServiceWorkerNavigationPreload,
SetCookie,
SetCookie2,
SourceMap,
StrictTransportSecurity,
TE,
TimingAllowOrigin,
Trailer,
TransferEncoding,
Upgrade,
UpgradeInsecureRequests,
UserAgent,
Vary,
Via,
XContentTypeOptions,
XDNSPrefetchControl,
XFrameOptions,
XSourceMap,
XTempTablet,
XXSSProtection,
};
pub fn fastRemove(
this: *FetchHeaders,
header: HTTPHeaderName,
) void {
return fastRemove_(this, @intFromEnum(header));
}
pub fn fastRemove_(
this: *FetchHeaders,
header: u8,
) void {
return shim.cppFn("fastRemove_", .{
this,
header,
});
}
pub fn remove(
this: *FetchHeaders,
name_: *const ZigString,
global: *JSGlobalObject,
) void {
return shim.cppFn("remove", .{
this,
name_,
global,
});
}
pub fn cast_(value: JSValue, vm: *VM) ?*FetchHeaders {
return shim.cppFn("cast_", .{ value, vm });
}
pub fn cast(value: JSValue) ?*FetchHeaders {
return cast_(value, JSC.VirtualMachine.get().global.vm());
}
pub fn toJS(this: *FetchHeaders, globalThis: *JSGlobalObject) JSValue {
return shim.cppFn("toJS", .{ this, globalThis });
}
pub fn count(
this: *FetchHeaders,
names: *u32,
buf_len: *u32,
) void {
return shim.cppFn("count", .{
this,
names,
buf_len,
});
}
pub fn clone(
this: *FetchHeaders,
global: *JSGlobalObject,
) JSValue {
return shim.cppFn("clone", .{
this,
global,
});
}
pub fn cloneThis(
this: *FetchHeaders,
global: *JSGlobalObject,
) ?*FetchHeaders {
return shim.cppFn("cloneThis", .{
this,
global,
});
}
pub fn deref(
this: *FetchHeaders,
) void {
return shim.cppFn("deref", .{
this,
});
}
pub fn copyTo(
this: *FetchHeaders,
names: [*c]Api.StringPointer,
values: [*c]Api.StringPointer,
buf: [*]u8,
) void {
return shim.cppFn("copyTo", .{
this,
names,
values,
buf,
});
}
pub const Extern = [_][]const u8{
"fastRemove_",
"fastGet_",
"fastHas_",
"append",
"cast_",
"clone",
"cloneThis",
"copyTo",
"count",
"createFromJS",
"createEmpty",
"createFromPicoHeaders_",
"createFromUWS",
"createValue",
"deref",
"get_",
"has",
"put_",
"remove",
"toJS",
"toUWSResponse",
"isEmpty",
};
};
pub const SystemError = extern struct {
errno: c_int = 0,
/// label for errno
code: String = String.empty,
message: String = String.empty,
path: String = String.empty,
syscall: String = String.empty,
fd: i32 = -1,
pub fn Maybe(comptime Result: type) type {
return union(enum) {
err: SystemError,
result: Result,
};
}
pub const shim = Shimmer("", "SystemError", @This());
pub const name = "SystemError";
pub const namespace = "";
pub fn toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue {
return shim.cppFn("toErrorInstance", .{ this, global });
}
pub fn format(self: SystemError, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
// TODO: remove this hardcoding
switch (bun.Output.enable_ansi_colors_stderr) {
inline else => |enable_colors| try writer.print(
comptime bun.Output.prettyFmt(
"<r><red>{}<r><d>:<r> {} <d>({}())<r>",
enable_colors,
),
.{
self.code,
self.message,
self.syscall,
},
),
}
}
pub const Extern = [_][]const u8{
"toErrorInstance",
};
};
pub const ReturnableException = *?*Exception;
pub const Sizes = @import("../bindings/sizes.zig");
pub const JSUint8Array = opaque {
pub const name = "Uint8Array_alias";
pub fn ptr(this: *JSUint8Array) [*]u8 {
return @as(*[*]u8, @ptrFromInt(@intFromPtr(this) + Sizes.Bun_FFI_PointerOffsetToTypedArrayVector)).*;
}
pub fn len(this: *JSUint8Array) usize {
return @as(*usize, @ptrFromInt(@intFromPtr(this) + Sizes.Bun_FFI_PointerOffsetToTypedArrayLength)).*;
}
pub fn slice(this: *JSUint8Array) []u8 {
return this.ptr()[0..this.len()];
}
};
pub const JSCell = extern struct {
pub const shim = Shimmer("JSC", "JSCell", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSCell.h";
pub const name = "JSC::JSCell";
pub const namespace = "JSC";
const CellType = enum(u8) { _ };
pub fn getObject(this: *JSCell) *JSObject {
return shim.cppFn("getObject", .{this});
}
pub fn getType(this: *JSCell) u8 {
return shim.cppFn("getType", .{
this,
});
}
pub const Extern = [_][]const u8{ "getObject", "getType" };
};
pub const JSString = extern struct {
pub const shim = Shimmer("JSC", "JSString", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSString.h";
pub const name = "JSC::JSString";
pub const namespace = "JSC";
pub fn toObject(this: *JSString, global: *JSGlobalObject) ?*JSObject {
return shim.cppFn("toObject", .{ this, global });
}
pub fn toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *JSC.ZigString) void {
return shim.cppFn("toZigString", .{ this, global, zig_str });
}
pub fn getZigString(this: *JSString, global: *JSGlobalObject) JSC.ZigString {
var out = JSC.ZigString.init("");
this.toZigString(global, &out);
return out;
}
// doesn't always allocate
pub fn toSlice(
this: *JSString,
global: *JSGlobalObject,
allocator: std.mem.Allocator,
) ZigString.Slice {
var str = ZigString.init("");
this.toZigString(global, &str);
return str.toSlice(allocator);
}
pub fn toSliceClone(
this: *JSString,
global: *JSGlobalObject,
allocator: std.mem.Allocator,
) ZigString.Slice {
var str = ZigString.init("");
this.toZigString(global, &str);
return str.toSliceClone(allocator);
}
pub fn toSliceZ(
this: *JSString,
global: *JSGlobalObject,
allocator: std.mem.Allocator,
) ZigString.Slice {
var str = ZigString.init("");
this.toZigString(global, &str);
return str.toSliceZ(allocator);
}
pub fn eql(this: *const JSString, global: *JSGlobalObject, other: *JSString) bool {
return shim.cppFn("eql", .{ this, global, other });
}
pub fn iterator(this: *JSString, globalObject: *JSGlobalObject, iter: *anyopaque) void {
return shim.cppFn("iterator", .{ this, globalObject, iter });
}
pub fn length(this: *const JSString) usize {
return shim.cppFn("length", .{
this,
});
}
pub fn is8Bit(this: *const JSString) bool {
return shim.cppFn("is8Bit", .{
this,
});
}
pub const JStringIteratorAppend8Callback = *const fn (*Iterator, [*]const u8, u32) callconv(.C) void;
pub const JStringIteratorAppend16Callback = *const fn (*Iterator, [*]const u16, u32) callconv(.C) void;
pub const JStringIteratorWrite8Callback = *const fn (*Iterator, [*]const u8, u32, u32) callconv(.C) void;
pub const JStringIteratorWrite16Callback = *const fn (*Iterator, [*]const u16, u32, u32) callconv(.C) void;
pub const Iterator = extern struct {
data: ?*anyopaque,
stop: u8,
append8: ?JStringIteratorAppend8Callback,
append16: ?JStringIteratorAppend16Callback,
write8: ?JStringIteratorWrite8Callback,
write16: ?JStringIteratorWrite16Callback,
};
pub const Extern = [_][]const u8{ "toZigString", "iterator", "toObject", "eql", "value", "length", "is8Bit", "createFromOwnedString", "createFromString" };
};
pub const JSPromiseRejectionOperation = enum(u32) {
Reject = 0,
Handle = 1,
};
pub fn NewGlobalObject(comptime Type: type) type {
return struct {
const importNotImpl = "Import not implemented";
const resolveNotImpl = "resolve not implemented";
const moduleNotImpl = "Module fetch not implemented";
pub fn import(global: *JSGlobalObject, specifier: *String, source: *String) callconv(.C) ErrorableString {
if (comptime @hasDecl(Type, "import")) {
return @call(.always_inline, Type.import, .{ global, specifier.*, source.* });
}
return ErrorableString.err(error.ImportFailed, String.init(importNotImpl).toErrorInstance(global).asVoid());
}
pub fn resolve(
res: *ErrorableString,
global: *JSGlobalObject,
specifier: *String,
source: *String,
query_string: *ZigString,
) callconv(.C) void {
if (comptime @hasDecl(Type, "resolve")) {
@call(.always_inline, Type.resolve, .{ res, global, specifier.*, source.*, query_string, true });
return;
}
res.* = ErrorableString.err(error.ResolveFailed, String.init(resolveNotImpl).toErrorInstance(global).asVoid());
}
pub fn fetch(ret: *ErrorableResolvedSource, global: *JSGlobalObject, specifier: *String, source: *String) callconv(.C) void {
if (comptime @hasDecl(Type, "fetch")) {
@call(.always_inline, Type.fetch, .{ ret, global, specifier.*, source.* });
return;
}
ret.* = ErrorableResolvedSource.err(error.FetchFailed, String.init(moduleNotImpl).toErrorInstance(global).asVoid());
}
pub fn promiseRejectionTracker(global: *JSGlobalObject, promise: *JSPromise, rejection: JSPromiseRejectionOperation) callconv(.C) JSValue {
if (comptime @hasDecl(Type, "promiseRejectionTracker")) {
return @call(.always_inline, Type.promiseRejectionTracker, .{ global, promise, rejection });
}
return JSValue.jsUndefined();
}
pub fn reportUncaughtException(global: *JSGlobalObject, exception: *Exception) callconv(.C) JSValue {
if (comptime @hasDecl(Type, "reportUncaughtException")) {
return @call(.always_inline, Type.reportUncaughtException, .{ global, exception });
}
return JSValue.jsUndefined();
}
pub fn onCrash() callconv(.C) void {
if (comptime @hasDecl(Type, "onCrash")) {
return @call(.always_inline, Type.onCrash, .{});
}
Output.flush();
const Reporter = @import("../../report.zig");
Reporter.fatal(null, "A C++ exception occurred");
}
};
}
pub const JSModuleLoader = extern struct {
pub const shim = Shimmer("JSC", "JSModuleLoader", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSModuleLoader.h";
pub const name = "JSC::JSModuleLoader";
pub const namespace = "JSC";
pub fn evaluate(
globalObject: *JSGlobalObject,
sourceCodePtr: [*]const u8,
sourceCodeLen: usize,
originUrlPtr: [*]const u8,
originUrlLen: usize,
referrerUrlPtr: [*]const u8,
referrerUrlLen: usize,
thisValue: JSValue,
exception: [*]JSValue,
) JSValue {
return shim.cppFn("evaluate", .{
globalObject,
sourceCodePtr,
sourceCodeLen,
originUrlPtr,
originUrlLen,
referrerUrlPtr,
referrerUrlLen,
thisValue,
exception,
});
}
pub fn loadAndEvaluateModule(globalObject: *JSGlobalObject, module_name: *const bun.String) *JSInternalPromise {
return shim.cppFn("loadAndEvaluateModule", .{
globalObject,
module_name,
});
}
// pub fn dependencyKeysIfEvaluated(this: *JSModuleLoader, globalObject: *JSGlobalObject, moduleRecord: *JSModuleRecord) *JSValue {
// return shim.cppFn("dependencyKeysIfEvaluated", .{ this, globalObject, moduleRecord });
// }
pub const Extern = [_][]const u8{
"evaluate",
"loadAndEvaluateModule",
"importModule",
"checkSyntax",
};
};
pub fn PromiseCallback(comptime Type: type, comptime CallbackFunction: fn (*Type, *JSGlobalObject, []const JSValue) anyerror!JSValue) type {
return struct {
pub fn callback(
ctx: ?*anyopaque,
globalThis: *JSGlobalObject,
arguments: [*]const JSValue,
arguments_len: usize,
) callconv(.C) JSValue {
return CallbackFunction(@as(*Type, @ptrCast(@alignCast(ctx.?))), globalThis, arguments[0..arguments_len]) catch |err| brk: {
break :brk ZigString.init(bun.asByteSlice(@errorName(err))).toErrorInstance(globalThis);
};
}
}.callback;
}
pub const AbortSignal = extern opaque {
pub const shim = Shimmer("WebCore", "AbortSignal", @This());
const cppFn = shim.cppFn;
pub const include = "webcore/AbortSignal.h";
pub const name = "WebCore::AbortSignal";
pub const namespace = "WebCore";
pub fn listen(
this: *AbortSignal,
comptime Context: type,
ctx: *Context,
comptime cb: *const fn (*Context, JSValue) void,
) *AbortSignal {
const Wrapper = struct {
const call = cb;
pub fn callback(
ptr: ?*anyopaque,
reason: JSValue,
) callconv(.C) void {
var val = bun.cast(*Context, ptr.?);
call(val, reason);
}
};
return this.addListener(@as(?*anyopaque, @ptrCast(ctx)), Wrapper.callback);
}
pub fn addListener(
this: *AbortSignal,
ctx: ?*anyopaque,
callback: *const fn (?*anyopaque, JSValue) callconv(.C) void,
) *AbortSignal {
return cppFn("addListener", .{ this, ctx, callback });
}
pub fn cleanNativeBindings(this: *AbortSignal, ctx: ?*anyopaque) void {
return cppFn("cleanNativeBindings", .{ this, ctx });
}
pub fn signal(
this: *AbortSignal,
reason: JSValue,
) *AbortSignal {
return cppFn("signal", .{ this, reason });
}
/// This function is not threadsafe. aborted is a boolean, not an atomic!
pub fn aborted(this: *AbortSignal) bool {
return cppFn("aborted", .{this});
}
/// This function is not threadsafe. JSValue cannot safely be passed between threads.
pub fn abortReason(this: *AbortSignal) JSValue {
return cppFn("abortReason", .{this});
}
pub fn ref(
this: *AbortSignal,
) *AbortSignal {
return cppFn("ref", .{this});
}
pub fn unref(
this: *AbortSignal,
) *AbortSignal {
return cppFn("unref", .{this});
}
pub fn detach(this: *AbortSignal, ctx: ?*anyopaque) void {
this.cleanNativeBindings(ctx);
_ = this.unref();
}
pub fn fromJS(value: JSValue) ?*AbortSignal {
return cppFn("fromJS", .{value});
}
pub fn toJS(this: *AbortSignal, global: *JSGlobalObject) JSValue {
return cppFn("toJS", .{ this, global });
}
pub fn create(global: *JSGlobalObject) JSValue {
return cppFn("create", .{global});
}
pub fn createAbortError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue {
return cppFn("createAbortError", .{ message, code, global });
}
pub fn createTimeoutError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue {
return cppFn("createTimeoutError", .{ message, code, global });
}
pub const Extern = [_][]const u8{ "createAbortError", "createTimeoutError", "create", "ref", "unref", "signal", "abortReason", "aborted", "addListener", "fromJS", "toJS", "cleanNativeBindings" };
};
pub const JSPromise = extern struct {
pub const shim = Shimmer("JSC", "JSPromise", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSPromise.h";
pub const name = "JSC::JSPromise";
pub const namespace = "JSC";
pub const Status = enum(u32) {
Pending = 0, // Making this as 0, so that, we can change the status from Pending to others without masking.
Fulfilled = 1,
Rejected = 2,
};
pub const Strong = struct {
strong: JSC.Strong = .{},
pub fn reject(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void {
this.swap().reject(globalThis, val);
}
pub fn rejectOnNextTick(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void {
this.swap().rejectOnNextTick(globalThis, val);
}
pub fn resolve(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void {
this.swap().resolve(globalThis, val);
}
pub fn resolveOnNextTick(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void {
this.swap().resolveOnNextTick(globalThis, val);
}
pub fn init(globalThis: *JSC.JSGlobalObject) Strong {
return Strong{
.strong = JSC.Strong.create(
JSC.JSPromise.create(globalThis).asValue(globalThis),
globalThis,
),
};
}
pub fn get(this: *Strong) *JSC.JSPromise {
return this.strong.get().?.asPromise().?;
}
pub fn value(this: *Strong) JSValue {
return this.strong.get().?;
}
pub fn swap(this: *Strong) *JSC.JSPromise {
var prom = this.strong.swap().asPromise().?;
this.strong.deinit();
return prom;
}
};
pub fn wrap(
globalObject: *JSGlobalObject,
value: JSValue,
) JSValue {
if (value.isEmpty()) {
return resolvedPromiseValue(globalObject, JSValue.jsUndefined());
} else if (value.isEmptyOrUndefinedOrNull() or !value.isCell()) {
return resolvedPromiseValue(globalObject, value);
}
if (value.jsType() == .JSPromise) {
return value;
}
if (value.isAnyError()) {
return rejectedPromiseValue(globalObject, value);
}
return resolvedPromiseValue(globalObject, value);
}
pub fn status(this: *const JSPromise, vm: *VM) Status {
return shim.cppFn("status", .{ this, vm });
}
pub fn result(this: *JSPromise, vm: *VM) JSValue {
return cppFn("result", .{ this, vm });
}
pub fn isHandled(this: *const JSPromise, vm: *VM) bool {
return cppFn("isHandled", .{ this, vm });
}
pub fn setHandled(this: *JSPromise, vm: *VM) void {
cppFn("setHandled", .{ this, vm });
}
pub fn rejectWithCaughtException(this: *JSPromise, globalObject: *JSGlobalObject, scope: ThrowScope) void {
return cppFn("rejectWithCaughtException", .{ this, globalObject, scope });
}
pub fn resolvedPromise(globalThis: *JSGlobalObject, value: JSValue) *JSPromise {
return cppFn("resolvedPromise", .{ globalThis, value });
}
pub fn resolveOnNextTick(promise: *JSC.JSPromise, globalThis: *JSGlobalObject, value: JSC.JSValue) void {
return cppFn("resolveOnNextTick", .{ promise, globalThis, value });
}
pub fn rejectOnNextTick(promise: *JSC.JSPromise, globalThis: *JSGlobalObject, value: JSC.JSValue) void {
return rejectOnNextTickWithHandled(promise, globalThis, value, false);
}
pub fn rejectOnNextTickAsHandled(promise: *JSC.JSPromise, globalThis: *JSGlobalObject, value: JSC.JSValue) void {
return rejectOnNextTickWithHandled(promise, globalThis, value, true);
}
pub fn rejectOnNextTickWithHandled(promise: *JSC.JSPromise, globalThis: *JSGlobalObject, value: JSC.JSValue, handled: bool) void {
return cppFn("rejectOnNextTickWithHandled", .{ promise, globalThis, value, handled });
}
/// Create a new promise with an already fulfilled value
/// This is the faster function for doing that.
pub fn resolvedPromiseValue(globalThis: *JSGlobalObject, value: JSValue) JSValue {
return cppFn("resolvedPromiseValue", .{ globalThis, value });
}
pub fn rejectedPromise(globalThis: *JSGlobalObject, value: JSValue) *JSPromise {
return cppFn("rejectedPromise", .{ globalThis, value });
}
pub fn rejectedPromiseValue(globalThis: *JSGlobalObject, value: JSValue) JSValue {
return cppFn("rejectedPromiseValue", .{ globalThis, value });
}
/// Fulfill an existing promise with the value
/// The value can be another Promise
/// If you want to create a new Promise that is already resolved, see JSPromise.resolvedPromiseValue
pub fn resolve(this: *JSPromise, globalThis: *JSGlobalObject, value: JSValue) void {
cppFn("resolve", .{ this, globalThis, value });
}
pub fn reject(this: *JSPromise, globalThis: *JSGlobalObject, value: JSValue) void {
cppFn("reject", .{ this, globalThis, value });
}
pub fn rejectAsHandled(this: *JSPromise, globalThis: *JSGlobalObject, value: JSValue) void {
cppFn("rejectAsHandled", .{ this, globalThis, value });
}
// pub fn rejectException(this: *JSPromise, globalThis: *JSGlobalObject, value: *Exception) void {
// cppFn("rejectException", .{ this, globalThis, value });
// }
pub fn rejectAsHandledException(this: *JSPromise, globalThis: *JSGlobalObject, value: *Exception) void {
cppFn("rejectAsHandledException", .{ this, globalThis, value });
}
pub fn create(globalThis: *JSGlobalObject) *JSPromise {
return cppFn("create", .{globalThis});
}
pub fn asValue(this: *JSPromise, globalThis: *JSGlobalObject) JSValue {
return cppFn("asValue", .{ this, globalThis });
}
pub const Extern = [_][]const u8{
"asValue",
"create",
"isHandled",
"setHandled",
"reject",
"rejectAsHandled",
"rejectAsHandledException",
"rejectOnNextTickWithHandled",
"rejectWithCaughtException",
"rejectedPromise",
"rejectedPromiseValue",
"resolve",
"resolveOnNextTick",
"resolvedPromise",
"resolvedPromiseValue",
"result",
"status",
// "rejectException",
};
};
pub const JSInternalPromise = extern struct {
pub const shim = Shimmer("JSC", "JSInternalPromise", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSInternalPromise.h";
pub const name = "JSC::JSInternalPromise";
pub const namespace = "JSC";
pub fn status(this: *const JSInternalPromise, vm: *VM) JSPromise.Status {
return shim.cppFn("status", .{ this, vm });
}
pub fn result(this: *const JSInternalPromise, vm: *VM) JSValue {
return cppFn("result", .{ this, vm });
}
pub fn isHandled(this: *const JSInternalPromise, vm: *VM) bool {
return cppFn("isHandled", .{ this, vm });
}
pub fn setHandled(this: *JSInternalPromise, vm: *VM) void {
cppFn("setHandled", .{ this, vm });
}
pub fn rejectWithCaughtException(this: *JSInternalPromise, globalObject: *JSGlobalObject, scope: ThrowScope) void {
return cppFn("rejectWithCaughtException", .{ this, globalObject, scope });
}
pub fn resolvedPromise(globalThis: *JSGlobalObject, value: JSValue) *JSInternalPromise {
return cppFn("resolvedPromise", .{ globalThis, value });
}
pub fn rejectedPromise(globalThis: *JSGlobalObject, value: JSValue) *JSInternalPromise {
return cppFn("rejectedPromise", .{ globalThis, value });
}
pub fn resolve(this: *JSInternalPromise, globalThis: *JSGlobalObject, value: JSValue) void {
cppFn("resolve", .{ this, globalThis, value });
}
pub fn reject(this: *JSInternalPromise, globalThis: *JSGlobalObject, value: JSValue) void {
cppFn("reject", .{ this, globalThis, value });
}
pub fn rejectAsHandled(this: *JSInternalPromise, globalThis: *JSGlobalObject, value: JSValue) void {
cppFn("rejectAsHandled", .{ this, globalThis, value });
}
// pub fn rejectException(this: *JSInternalPromise, globalThis: *JSGlobalObject, value: *Exception) void {
// cppFn("rejectException", .{ this, globalThis, value });
// }
pub fn rejectAsHandledException(this: *JSInternalPromise, globalThis: *JSGlobalObject, value: *Exception) void {
cppFn("rejectAsHandledException", .{ this, globalThis, value });
}
// pub const PromiseCallbackPrimitive = *const fn (
// ctx: ?*anyopaque,
// globalThis: *JSGlobalObject,
// arguments: [*]const JSValue,
// arguments_len: usize,
// ) callconv(.C) JSValue;
// pub fn then_(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// resolve_ctx: ?*anyopaque,
// onResolve: PromiseCallbackPrimitive,
// reject_ctx: ?*anyopaque,
// onReject: PromiseCallbackPrimitive,
// ) *JSInternalPromise {
// return cppFn("then_", .{ this, globalThis, resolve_ctx, onResolve, reject_ctx, onReject });
// }
// pub const Completion = struct {
// result: []const JSValue,
// global: *JSGlobalObject,
// resolved: bool = false,
// pub const PromiseTask = struct {
// frame: @Frame(JSInternalPromise._wait),
// completion: Completion,
// pub fn onResolve(this: *PromiseTask, global: *JSGlobalObject, arguments: []const JSValue) anyerror!JSValue {
// this.completion.global = global;
// this.completion.resolved = true;
// this.completion.result = arguments;
// return resume this.frame;
// }
// pub fn onReject(this: *PromiseTask, global: *JSGlobalObject, arguments: []const JSValue) anyerror!JSValue {
// this.completion.global = global;
// this.completion.resolved = false;
// this.completion.result = arguments;
// return resume this.frame;
// }
// };
// };
// pub fn _wait(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// internal: *Completion.PromiseTask,
// ) void {
// this.then(
// globalThis,
// Completion.PromiseTask,
// internal,
// Completion.PromiseTask.onResolve,
// Completion.PromiseTask,
// internal,
// Completion.PromiseTask.onReject,
// );
// suspend {
// internal.frame = @frame().*;
// }
// }
// pub fn wait(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// allocator: std.mem.Allocator,
// ) callconv(.Async) anyerror!Completion {
// var internal = try allocator.create(Completion.PromiseTask);
// defer allocator.destroy(internal);
// internal.* = Completion.Internal{
// .frame = undefined,
// .completion = Completion{
// .global = globalThis,
// .resolved = false,
// .result = &[_]JSValue{},
// },
// };
// this._wait(globalThis, internal);
// return internal.completion;
// }
// pub fn then(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// comptime Resolve: type,
// resolver: *Resolve,
// comptime onResolve: fn (*Resolve, *JSGlobalObject, []const JSValue) anyerror!JSValue,
// comptime Reject: type,
// rejecter: *Reject,
// comptime onReject: fn (*Reject, *JSGlobalObject, []const JSValue) anyerror!JSValue,
// ) *JSInternalPromise {
// return then_(this, globalThis, resolver, PromiseCallback(Resolve, onResolve), Reject, rejecter, PromiseCallback(Reject, onReject));
// }
// pub fn thenResolve(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// comptime Resolve: type,
// resolver: *Resolve,
// comptime onResolve: fn (*Resolve, *JSGlobalObject, []const JSValue) anyerror!JSValue,
// ) *JSInternalPromise {
// return thenResolve_(this, globalThis, resolver, PromiseCallback(Resolve, onResolve));
// }
// pub fn thenResolve_(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// resolve_ctx: ?*anyopaque,
// onResolve: PromiseCallbackPrimitive,
// ) *JSInternalPromise {
// return cppFn("thenResolve_", .{
// this,
// globalThis,
// resolve_ctx,
// onResolve,
// });
// }
// pub fn thenReject_(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// resolve_ctx: ?*anyopaque,
// onResolve: PromiseCallbackPrimitive,
// ) *JSInternalPromise {
// return cppFn("thenReject_", .{
// this,
// globalThis,
// resolve_ctx,
// onResolve,
// });
// }
// pub fn thenReject(
// this: *JSInternalPromise,
// globalThis: *JSGlobalObject,
// comptime Resolve: type,
// resolver: *Resolve,
// comptime onResolve: fn (*Resolve, *JSGlobalObject, []const JSValue) anyerror!JSValue,
// ) *JSInternalPromise {
// return thenReject_(this, globalThis, resolver, PromiseCallback(Resolve, onResolve));
// }
pub fn create(globalThis: *JSGlobalObject) *JSInternalPromise {
return cppFn("create", .{globalThis});
}
pub const Extern = [_][]const u8{
"create",
// "then_",
"rejectWithCaughtException",
"status",
"result",
"isHandled",
"setHandled",
"resolvedPromise",
"rejectedPromise",
"resolve",
"reject",
"rejectAsHandled",
// "thenResolve_",
// "thenReject_",
// "rejectException",
"rejectAsHandledException",
};
};
pub const AnyPromise = union(enum) {
Normal: *JSPromise,
Internal: *JSInternalPromise,
pub fn status(this: AnyPromise, vm: *VM) JSPromise.Status {
return switch (this) {
inline else => |promise| promise.status(vm),
};
}
pub fn result(this: AnyPromise, vm: *VM) JSValue {
return switch (this) {
inline else => |promise| promise.result(vm),
};
}
pub fn isHandled(this: AnyPromise, vm: *VM) bool {
return switch (this) {
inline else => |promise| promise.isHandled(vm),
};
}
pub fn setHandled(this: AnyPromise, vm: *VM) void {
switch (this) {
inline else => |promise| promise.setHandled(vm),
}
}
pub fn rejectWithCaughtException(this: AnyPromise, globalObject: *JSGlobalObject, scope: ThrowScope) void {
switch (this) {
inline else => |promise| promise.rejectWithCaughtException(globalObject, scope),
}
}
pub fn resolve(this: AnyPromise, globalThis: *JSGlobalObject, value: JSValue) void {
switch (this) {
inline else => |promise| promise.resolve(globalThis, value),
}
}
pub fn reject(this: AnyPromise, globalThis: *JSGlobalObject, value: JSValue) void {
switch (this) {
inline else => |promise| promise.reject(globalThis, value),
}
}
pub fn rejectAsHandled(this: AnyPromise, globalThis: *JSGlobalObject, value: JSValue) void {
switch (this) {
inline else => |promise| promise.rejectAsHandled(globalThis, value),
}
}
pub fn rejectAsHandledException(this: AnyPromise, globalThis: *JSGlobalObject, value: *Exception) void {
switch (this) {
inline else => |promise| promise.rejectAsHandledException(globalThis, value),
}
}
};
// SourceProvider.h
pub const SourceType = enum(u8) {
Program = 0,
Module = 1,
WebAssembly = 2,
};
pub const Thenables = opaque {};
pub const JSFunction = extern struct {
pub const shim = Shimmer("JSC", "JSFunction", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSFunction.h";
pub const name = "JSC::JSFunction";
pub const namespace = "JSC";
// pub fn createFromSourceCode(
// global: *JSGlobalObject,
// function_name: ?[*]const u8,
// function_name_len: u16,
// args: ?[*]JSValue,
// args_len: u16,
// source: *const SourceCode,
// origin: *SourceOrigin,
// exception: *?*JSObject,
// ) *JSFunction {
// return cppFn("createFromSourceCode", .{
// global,
// function_name,
// function_name_len,
// args,
// args_len,
// source,
// origin,
// exception,
// });
// }
pub fn optimizeSoon(value: JSValue) void {
cppFn("optimizeSoon", .{value});
}
// pub fn toString(this: *JSFunction, globalThis: *JSGlobalObject) *const JSString {
// return cppFn("toString", .{ this, globalThis });
// }
pub const Extern = [_][]const u8{
"fromString",
// "createFromSourceCode",
"getName",
"displayName",
"calculatedDisplayName",
"optimizeSoon",
};
};
pub const JSGlobalObject = extern struct {
pub const shim = Shimmer("JSC", "JSGlobalObject", @This());
bytes: shim.Bytes,
pub const include = "JavaScriptCore/JSGlobalObject.h";
pub const name = "JSC::JSGlobalObject";
pub const namespace = "JSC";
pub fn allocator(this: *JSGlobalObject) std.mem.Allocator {
return this.bunVM().allocator;
}
pub fn throwOutOfMemory(this: *JSGlobalObject) void {
this.throwValue(this.createErrorInstance("Out of memory", .{}));
}
extern fn JSGlobalObject__clearTerminationException(this: *JSGlobalObject) void;
extern fn JSGlobalObject__throwTerminationException(this: *JSGlobalObject) void;
pub const throwTerminationException = JSGlobalObject__throwTerminationException;
pub const clearTerminationException = JSGlobalObject__clearTerminationException;
extern fn JSGlobalObject__setTimeZone(this: *JSGlobalObject, timeZone: *const ZigString) bool;
pub fn setTimeZone(this: *JSGlobalObject, timeZone: *const ZigString) bool {
return JSGlobalObject__setTimeZone(this, timeZone);
}
pub inline fn toJS(globalThis: *JSGlobalObject) JSValue {
return @enumFromInt(@as(JSValue.Type, @bitCast(@intFromPtr(globalThis))));
}
pub fn throwInvalidArguments(
this: *JSGlobalObject,
comptime fmt: string,
args: anytype,
) void {
var err = JSC.toInvalidArguments(fmt, args, this);
this.vm().throwError(this, err);
}
pub fn createInvalidArgumentType(
this: *JSGlobalObject,
comptime name_: []const u8,
comptime field: []const u8,
comptime typename: []const u8,
) JSC.JSValue {
return JSC.JSValue.createTypeError(
ZigString.static(
comptime std.fmt.comptimePrint("Expected {s} to be a {s} for '{s}'.", .{ field, typename, name_ }),
),
ZigString.static("ERR_INVALID_ARG_TYPE"),
this,
);
}
pub fn throwInvalidArgumentType(
this: *JSGlobalObject,
comptime name_: []const u8,
comptime field: []const u8,
comptime typename: []const u8,
) void {
this.throwValue(this.createInvalidArgumentType(name_, field, typename));
}
pub fn createNotEnoughArguments(
this: *JSGlobalObject,
comptime name_: []const u8,
comptime expected: usize,
got: usize,
) JSC.JSValue {
return JSC.toTypeErrorWithCode(
"NOT_ENOUGH_ARGUMENTS",
"Not enough arguments to '" ++ name_ ++ "'. Expected {d}, got {d}.",
.{ expected, got },
this,
);
}
pub fn throwNotEnoughArguments(
this: *JSGlobalObject,
comptime name_: []const u8,
comptime expected: usize,
got: usize,
) void {
this.throwValue(this.createNotEnoughArguments(name_, expected, got));
}
pub fn reload(this: *JSC.JSGlobalObject) void {
this.vm().drainMicrotasks();
this.vm().collectAsync();
return cppFn("reload", .{this});
}
pub const BunPluginTarget = enum(u8) {
bun = 0,
node = 1,
browser = 2,
};
extern fn Bun__runOnLoadPlugins(*JSC.JSGlobalObject, ?*const bun.String, *const bun.String, BunPluginTarget) JSValue;
extern fn Bun__runOnResolvePlugins(*JSC.JSGlobalObject, ?*const bun.String, *const bun.String, *const String, BunPluginTarget) JSValue;
pub fn runOnLoadPlugins(this: *JSGlobalObject, namespace_: bun.String, path: bun.String, target: BunPluginTarget) ?JSValue {
JSC.markBinding(@src());
const result = Bun__runOnLoadPlugins(this, if (namespace_.length() > 0) &namespace_ else null, &path, target);
if (result.isEmptyOrUndefinedOrNull()) {
return null;
}
return result;
}
pub fn runOnResolvePlugins(this: *JSGlobalObject, namespace_: bun.String, path: bun.String, source: bun.String, target: BunPluginTarget) ?JSValue {
JSC.markBinding(@src());
const result = Bun__runOnResolvePlugins(this, if (namespace_.length() > 0) &namespace_ else null, &path, &source, target);
if (result.isEmptyOrUndefinedOrNull()) {
return null;
}
return result;
}
pub fn createSyntheticModule_(this: *JSGlobalObject, export_names: [*]const ZigString, export_len: usize, value_ptrs: [*]const JSValue, values_len: usize) void {
shim.cppFn("createSyntheticModule_", .{ this, export_names, export_len, value_ptrs, values_len });
}
pub fn createSyntheticModule(this: *JSGlobalObject, comptime module: anytype) void {
const names = comptime std.meta.fieldNames(@TypeOf(module));
var export_names: [names.len]ZigString = undefined;
var export_values: [names.len]JSValue = undefined;
inline for (comptime names, 0..) |export_name, i| {
export_names[i] = ZigString.init(export_name);
const function = @field(module, export_name).@"0";
const len = @field(module, export_name).@"1";
export_values[i] = JSC.NewFunction(this, &export_names[i], len, function, true);
}
createSyntheticModule_(this, &export_names, names.len, &export_values, names.len);
}
pub fn createErrorInstance(this: *JSGlobalObject, comptime fmt: string, args: anytype) JSValue {
if (comptime std.meta.fieldNames(@TypeOf(args)).len > 0) {
var stack_fallback = std.heap.stackFallback(1024 * 4, this.allocator());
var buf = bun.MutableString.init2048(stack_fallback.get()) catch unreachable;
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch
// if an exception occurs in the middle of formatting the error message, it's better to just return the formatting string than an error about an error
return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
return str.toErrorInstance(this);
} else {
return ZigString.static(fmt).toErrorInstance(this);
}
}
pub fn createErrorInstanceWithCode(this: *JSGlobalObject, code: JSC.Node.ErrorCode, comptime fmt: string, args: anytype) JSValue {
var err = this.createErrorInstance(fmt, args);
err.put(this, ZigString.static("code"), ZigString.init(@tagName(code)).toValue(this));
return err;
}
pub fn createTypeErrorInstance(this: *JSGlobalObject, comptime fmt: string, args: anytype) JSValue {
if (comptime std.meta.fieldNames(@TypeOf(args)).len > 0) {
var stack_fallback = std.heap.stackFallback(1024 * 4, this.allocator());
var buf = bun.MutableString.init2048(stack_fallback.get()) catch unreachable;
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
return str.toTypeErrorInstance(this);
} else {
return ZigString.static(fmt).toTypeErrorInstance(this);
}
}
pub fn createSyntaxErrorInstance(this: *JSGlobalObject, comptime fmt: string, args: anytype) JSValue {
if (comptime std.meta.fieldNames(@TypeOf(args)).len > 0) {
var stack_fallback = std.heap.stackFallback(1024 * 4, this.allocator());
var buf = bun.MutableString.init2048(stack_fallback.get()) catch unreachable;
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
return str.toSyntaxErrorInstance(this);
} else {
return ZigString.static(fmt).toSyntaxErrorInstance(this);
}
}
pub fn createRangeErrorInstance(this: *JSGlobalObject, comptime fmt: string, args: anytype) JSValue {
if (comptime std.meta.fieldNames(@TypeOf(args)).len > 0) {
var stack_fallback = std.heap.stackFallback(1024 * 4, this.allocator());
var buf = bun.MutableString.init2048(stack_fallback.get()) catch unreachable;
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
return str.toRangeErrorInstance(this);
} else {
return ZigString.static(fmt).toRangeErrorInstance(this);
}
}
pub fn createRangeErrorInstanceWithCode(this: *JSGlobalObject, code: JSC.Node.ErrorCode, comptime fmt: string, args: anytype) JSValue {
var err = this.createRangeErrorInstance(fmt, args);
err.put(this, ZigString.static("code"), ZigString.init(@tagName(code)).toValue(this));
return err;
}
pub fn createRangeError(this: *JSGlobalObject, comptime fmt: string, args: anytype) JSValue {
const err = createErrorInstance(this, fmt, args);
err.put(this, ZigString.static("code"), ZigString.static(@tagName(JSC.Node.ErrorCode.ERR_OUT_OF_RANGE)).toValue(this));
return err;
}
pub fn createInvalidArgs(this: *JSGlobalObject, comptime fmt: string, args: anytype) JSValue {
const err = createErrorInstance(this, fmt, args);
err.put(this, ZigString.static("code"), ZigString.static(@tagName(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE)).toValue(this));
return err;
}
pub fn createError(
this: *JSGlobalObject,
code: JSC.Node.ErrorCode,
error_name: string,
comptime message: string,
args: anytype,
) JSValue {
const err = createErrorInstance(this, message, args);
err.put(this, ZigString.static("code"), ZigString.init(@tagName(code)).toValue(this));
err.put(this, ZigString.static("name"), ZigString.init(error_name).toValue(this));
return err;
}
pub fn throw(
this: *JSGlobalObject,
comptime fmt: string,
args: anytype,
) void {
this.vm().throwError(this, this.createErrorInstance(fmt, args));
}
pub fn throwPretty(
this: *JSGlobalObject,
comptime fmt: string,
args: anytype,
) void {
if (Output.enable_ansi_colors) {
this.vm().throwError(this, this.createErrorInstance(Output.prettyFmt(fmt, true), args));
} else {
this.vm().throwError(this, this.createErrorInstance(Output.prettyFmt(fmt, false), args));
}
}
extern fn JSC__JSGlobalObject__queueMicrotaskCallback(*JSGlobalObject, *anyopaque, Function: *const (fn (*anyopaque) callconv(.C) void)) void;
pub fn queueMicrotaskCallback(
this: *JSGlobalObject,
ctx_val: anytype,
comptime Function: fn (ctx: @TypeOf(ctx_val)) void,
) void {
JSC.markBinding(@src());
const Fn = Function;
const ContextType = @TypeOf(ctx_val);
const Wrapper = struct {
pub fn call(p: *anyopaque) callconv(.C) void {
Fn(bun.cast(ContextType, p));
}
};
JSC__JSGlobalObject__queueMicrotaskCallback(this, ctx_val, &Wrapper.call);
}
pub fn queueMicrotask(
this: *JSGlobalObject,
function: JSValue,
args: []JSC.JSValue,
) void {
this.queueMicrotaskJob(
function,
if (args.len > 0) args[0] else .zero,
if (args.len > 1) args[1] else .zero,
);
}
pub fn queueMicrotaskJob(
this: *JSGlobalObject,
function: JSValue,
first: JSValue,
second: JSValue,
) void {
shim.cppFn("queueMicrotaskJob", .{
this,
function,
first,
second,
});
}
pub fn throwValue(
this: *JSGlobalObject,
value: JSC.JSValue,
) void {
this.vm().throwError(this, value);
}
pub fn throwError(
this: *JSGlobalObject,
err: anyerror,
comptime fmt: string,
) void {
var str = ZigString.init(std.fmt.allocPrint(this.bunVM().allocator, "{s} " ++ fmt, .{@errorName(err)}) catch return);
str.markUTF8();
var err_value = str.toErrorInstance(this);
this.vm().throwError(this, err_value);
this.bunVM().allocator.free(ZigString.untagged(str._unsafe_ptr_do_not_use)[0..str.len]);
}
pub fn handleError(
this: *JSGlobalObject,
err: anyerror,
comptime fmt: string,
) JSValue {
this.throwError(err, fmt);
return JSValue.jsUndefined();
}
// pub fn createError(globalObject: *JSGlobalObject, error_type: ErrorType, message: *String) *JSObject {
// return cppFn("createError", .{ globalObject, error_type, message });
// }
// pub fn throwError(
// globalObject: *JSGlobalObject,
// err: *JSObject,
// ) *JSObject {
// return cppFn("throwError", .{
// globalObject,
// err,
// });
// }
const cppFn = shim.cppFn;
pub fn ref(this: *JSGlobalObject) C_API.JSContextRef {
return @as(C_API.JSContextRef, @ptrCast(this));
}
pub const ctx = ref;
pub inline fn ptr(this: *JSGlobalObject) *JSGlobalObject {
return this;
}
pub fn createAggregateError(globalObject: *JSGlobalObject, errors: [*]*anyopaque, errors_len: u16, message: *const ZigString) JSValue {
return cppFn("createAggregateError", .{ globalObject, errors, errors_len, message });
}
pub fn generateHeapSnapshot(this: *JSGlobalObject) JSValue {
return cppFn("generateHeapSnapshot", .{this});
}
pub fn putCachedObject(this: *JSGlobalObject, key: *const ZigString, value: JSValue) JSValue {
return cppFn("putCachedObject", .{ this, key, value });
}
pub fn getCachedObject(this: *JSGlobalObject, key: *const ZigString) JSValue {
return cppFn("getCachedObject", .{ this, key });
}
pub fn vm(this: *JSGlobalObject) *VM {
return cppFn("vm", .{this});
}
pub fn deleteModuleRegistryEntry(this: *JSGlobalObject, name_: *ZigString) void {
return cppFn("deleteModuleRegistryEntry", .{ this, name_ });
}
pub fn bunVM_(this: *JSGlobalObject) *anyopaque {
return cppFn("bunVM", .{this});
}
pub fn bunVM(this: *JSGlobalObject) *JSC.VirtualMachine {
if (comptime bun.Environment.allow_assert) {
// if this fails
// you most likely need to run
// make clean-jsc-bindings
// make bindings -j10
const assertion = this.bunVM_() == @as(*anyopaque, @ptrCast(JSC.VirtualMachine.get()));
if (!assertion) @breakpoint();
std.debug.assert(assertion);
}
return @as(*JSC.VirtualMachine, @ptrCast(@alignCast(this.bunVM_())));
}
/// We can't do the threadlocal check when queued from another thread
pub fn bunVMConcurrently(this: *JSGlobalObject) *JSC.VirtualMachine {
return @as(*JSC.VirtualMachine, @ptrCast(@alignCast(this.bunVM_())));
}
pub fn handleRejectedPromises(this: *JSGlobalObject) void {
return cppFn("handleRejectedPromises", .{this});
}
pub fn startRemoteInspector(this: *JSGlobalObject, host: [:0]const u8, port: u16) bool {
return cppFn("startRemoteInspector", .{ this, host, port });
}
extern fn ZigGlobalObject__readableStreamToArrayBuffer(*JSGlobalObject, JSValue) JSValue;
extern fn ZigGlobalObject__readableStreamToText(*JSGlobalObject, JSValue) JSValue;
extern fn ZigGlobalObject__readableStreamToJSON(*JSGlobalObject, JSValue) JSValue;
extern fn ZigGlobalObject__readableStreamToFormData(*JSGlobalObject, JSValue, JSValue) JSValue;
extern fn ZigGlobalObject__readableStreamToBlob(*JSGlobalObject, JSValue) JSValue;
pub fn readableStreamToArrayBuffer(this: *JSGlobalObject, value: JSValue) JSValue {
if (comptime is_bindgen) unreachable;
return ZigGlobalObject__readableStreamToArrayBuffer(this, value);
}
pub fn readableStreamToText(this: *JSGlobalObject, value: JSValue) JSValue {
if (comptime is_bindgen) unreachable;
return ZigGlobalObject__readableStreamToText(this, value);
}
pub fn readableStreamToJSON(this: *JSGlobalObject, value: JSValue) JSValue {
if (comptime is_bindgen) unreachable;
return ZigGlobalObject__readableStreamToJSON(this, value);
}
pub fn readableStreamToBlob(this: *JSGlobalObject, value: JSValue) JSValue {
if (comptime is_bindgen) unreachable;
return ZigGlobalObject__readableStreamToBlob(this, value);
}
pub fn readableStreamToFormData(this: *JSGlobalObject, value: JSValue, content_type: JSValue) JSValue {
if (comptime is_bindgen) unreachable;
return ZigGlobalObject__readableStreamToFormData(this, value, content_type);
}
pub const Extern = [_][]const u8{
"reload",
"bunVM",
"putCachedObject",
"getCachedObject",
"createAggregateError",
"deleteModuleRegistryEntry",
"vm",
"generateHeapSnapshot",
"startRemoteInspector",
"handleRejectedPromises",
"createSyntheticModule_",
"queueMicrotaskJob",
// "createError",
// "throwError",
};
};
pub const JSNativeFn = *const fn (*JSGlobalObject, *CallFrame) callconv(.C) JSValue;
pub const JSArrayIterator = struct {
i: u32 = 0,
len: u32 = 0,
array: JSValue,
global: *JSGlobalObject,
pub fn init(value: JSValue, global: *JSGlobalObject) JSArrayIterator {
return .{
.array = value,
.global = global,
.len = @as(u32, @truncate(value.getLength(global))),
};
}
pub fn next(this: *JSArrayIterator) ?JSValue {
if (!(this.i < this.len)) {
return null;
}
const i = this.i;
this.i += 1;
return JSObject.getIndex(this.array, this.global, i);
}
};
pub const JSMap = opaque {
pub const shim = Shimmer("JSC", "JSMap", @This());
pub const Type = JSMap;
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSMap.h";
pub const name = "JSC::JSMap";
pub const namespace = "JSC";
pub fn create(globalObject: *JSGlobalObject) JSValue {
return cppFn("create", .{globalObject});
}
pub fn set(this: *JSMap, globalObject: *JSGlobalObject, key: JSValue, value: JSValue) void {
return cppFn("set", .{ this, globalObject, key, value });
}
pub fn get_(this: *JSMap, globalObject: *JSGlobalObject, key: JSValue) JSValue {
return cppFn("get", .{ this, globalObject, key });
}
pub fn get(this: *JSMap, globalObject: *JSGlobalObject, key: JSValue) ?JSValue {
const value = get_(this, globalObject, key);
if (value.isEmpty()) {
return null;
}
return value;
}
pub fn has(this: *JSMap, globalObject: *JSGlobalObject, key: JSValue) bool {
return cppFn("has", .{ this, globalObject, key });
}
pub fn remove(this: *JSMap, globalObject: *JSGlobalObject, key: JSValue) bool {
return cppFn("remove", .{ this, globalObject, key });
}
pub fn fromJS(value: JSValue) ?*JSMap {
if (value.jsTypeLoose() == .JSMap) {
return bun.cast(*JSMap, value.asEncoded().asPtr.?);
}
return null;
}
pub const Extern = [_][]const u8{
"create",
"set",
"get_",
"has",
"remove",
};
};
pub const JSValueReprInt = i64;
pub const JSValue = enum(JSValueReprInt) {
zero = 0,
undefined = @as(JSValueReprInt, @bitCast(@as(i64, 0xa))),
null = @as(JSValueReprInt, @bitCast(@as(i64, 0x2))),
true = @as(JSValueReprInt, @bitCast(@as(i64, 0x4))),
false = @as(JSValueReprInt, @bitCast(@as(i64, 0x6))),
_,
pub const Type = JSValueReprInt;
pub const shim = Shimmer("JSC", "JSValue", @This());
pub const is_pointer = false;
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/JSValue.h";
pub const name = "JSC::JSValue";
pub const namespace = "JSC";
pub const JSType = enum(u8) {
// The Cell value must come before any JS that is a JSCell.
Cell,
Structure,
String,
HeapBigInt,
Symbol,
GetterSetter,
CustomGetterSetter,
/// For 32-bit architectures, this wraps a 64-bit JSValue
APIValueWrapper,
NativeExecutable,
ProgramExecutable,
ModuleProgramExecutable,
EvalExecutable,
FunctionExecutable,
UnlinkedFunctionExecutable,
UnlinkedProgramCodeBlock,
UnlinkedModuleProgramCodeBlock,
UnlinkedEvalCodeBlock,
UnlinkedFunctionCodeBlock,
CodeBlock,
JSImmutableButterfly,
JSSourceCode,
JSScriptFetcher,
JSScriptFetchParameters,
// The Object value must come before any JS that is a subclass of JSObject.
Object,
FinalObject,
JSCallee,
JSFunction,
InternalFunction,
NullSetterFunction,
BooleanObject,
NumberObject,
ErrorInstance,
GlobalProxy,
DirectArguments,
ScopedArguments,
ClonedArguments,
// Start JSArray s.
Array,
DerivedArray,
// End JSArray s.
ArrayBuffer,
// Start JSArrayBufferView s. Keep in sync with the order of FOR_EACH_D_ARRAY__EXCLUDING_DATA_VIEW.
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
BigInt64Array,
BigUint64Array,
DataView,
// End JSArrayBufferView s.
// JSScope <- JSWithScope
// <- StrictEvalActivation
// <- JSSymbolTableObject <- JSLexicalEnvironment <- JSModuleEnvironment
// <- JSSegmentedVariableObject <- JSGlobalLexicalEnvironment
// <- JSGlobalObject
// Start JSScope s.
// Start environment record s.
GlobalObject,
GlobalLexicalEnvironment,
LexicalEnvironment,
ModuleEnvironment,
StrictEvalActivation,
// End environment record s.
WithScope,
// End JSScope s.
ModuleNamespaceObject,
ShadowRealm,
RegExpObject,
JSDate,
ProxyObject,
JSGenerator,
JSAsyncGenerator,
JSArrayIterator,
JSMapIterator,
JSSetIterator,
JSStringIterator,
JSPromise,
JSMap,
JSSet,
JSWeakMap,
JSWeakSet,
WebAssemblyModule,
WebAssemblyInstance,
WebAssemblyGCObject,
// Start StringObject s.
StringObject,
DerivedStringObject,
// End StringObject s.
InternalFieldTuple,
MaxJS = 0b11111111,
Event = 0b11101111,
DOMWrapper = 0b11101110,
Blob = 0b11111100,
/// This means that we don't have Zig bindings for the type yet, but it
/// implements .toJSON()
JSAsJSONType = 0b11110000 | 1,
_,
pub fn canGet(this: JSType) bool {
return switch (this) {
.Array,
.ArrayBuffer,
.BigInt64Array,
.BigUint64Array,
.BooleanObject,
.DOMWrapper,
.DataView,
.DerivedArray,
.DerivedStringObject,
.ErrorInstance,
.Event,
.FinalObject,
.Float32Array,
.Float64Array,
.GlobalObject,
.Int16Array,
.Int32Array,
.Int8Array,
.InternalFunction,
.JSArrayIterator,
.JSAsyncGenerator,
.JSDate,
.JSFunction,
.JSGenerator,
.JSMap,
.JSMapIterator,
.JSPromise,
.JSSet,
.JSSetIterator,
.JSStringIterator,
.JSWeakMap,
.JSWeakSet,
.ModuleNamespaceObject,
.NumberObject,
.Object,
.ProxyObject,
.RegExpObject,
.ShadowRealm,
.StringObject,
.Uint16Array,
.Uint32Array,
.Uint8Array,
.Uint8ClampedArray,
.WebAssemblyModule,
.WebAssemblyInstance,
.WebAssemblyGCObject,
=> true,
else => false,
};
}
pub fn isObject(this: JSType) bool {
// inline constexpr bool isObjectType(JSType type) { return type >= ObjectType; }
return @intFromEnum(this) >= @intFromEnum(JSType.Object);
}
pub fn isFunction(this: JSType) bool {
return switch (this) {
.JSFunction, .FunctionExecutable, .InternalFunction => true,
else => false,
};
}
pub fn isTypedArray(this: JSType) bool {
return switch (this) {
.ArrayBuffer,
.BigInt64Array,
.BigUint64Array,
.Float32Array,
.Float64Array,
.Int16Array,
.Int32Array,
.Int8Array,
.Uint16Array,
.Uint32Array,
.Uint8Array,
.Uint8ClampedArray,
=> true,
else => false,
};
}
pub fn toC(this: JSType) C_API.JSTypedArrayType {
return switch (this) {
.Int8Array => .kJSTypedArrayTypeInt8Array,
.Int16Array => .kJSTypedArrayTypeInt16Array,
.Int32Array => .kJSTypedArrayTypeInt32Array,
.Uint8Array => .kJSTypedArrayTypeUint8Array,
.Uint8ClampedArray => .kJSTypedArrayTypeUint8ClampedArray,
.Uint16Array => .kJSTypedArrayTypeUint16Array,
.Uint32Array => .kJSTypedArrayTypeUint32Array,
.Float32Array => .kJSTypedArrayTypeFloat32Array,
.Float64Array => .kJSTypedArrayTypeFloat64Array,
.ArrayBuffer => .kJSTypedArrayTypeArrayBuffer,
// .DataView => .kJSTypedArrayTypeDataView,
else => .kJSTypedArrayTypeNone,
};
}
pub fn isHidden(this: JSType) bool {
return switch (this) {
.APIValueWrapper,
.NativeExecutable,
.ProgramExecutable,
.ModuleProgramExecutable,
.EvalExecutable,
.FunctionExecutable,
.UnlinkedFunctionExecutable,
.UnlinkedProgramCodeBlock,
.UnlinkedModuleProgramCodeBlock,
.UnlinkedEvalCodeBlock,
.UnlinkedFunctionCodeBlock,
.CodeBlock,
.JSImmutableButterfly,
.JSSourceCode,
.JSScriptFetcher,
.JSScriptFetchParameters,
=> true,
else => false,
};
}
pub const LastMaybeFalsyCellPrimitive = JSType.HeapBigInt;
pub const LastJSCObject = JSType.DerivedStringObject; // This is the last "JSC" Object type. After this, we have embedder's (e.g., WebCore) extended object types.
pub inline fn isString(this: JSType) bool {
return this == .String;
}
pub inline fn isStringLike(this: JSType) bool {
return switch (this) {
.String, .StringObject, .DerivedStringObject => true,
else => false,
};
}
pub inline fn isArray(this: JSType) bool {
return switch (this) {
.Array, .DerivedArray => true,
else => false,
};
}
pub inline fn isArrayLike(this: JSType) bool {
return switch (this) {
.Array,
.DerivedArray,
.ArrayBuffer,
.BigInt64Array,
.BigUint64Array,
.Float32Array,
.Float64Array,
.Int16Array,
.Int32Array,
.Int8Array,
.Uint16Array,
.Uint32Array,
.Uint8Array,
.Uint8ClampedArray,
=> true,
else => false,
};
}
pub inline fn isSet(this: JSType) bool {
return switch (this) {
.JSSet, .JSWeakSet => true,
else => false,
};
}
pub inline fn isMap(this: JSType) bool {
return switch (this) {
.JSMap, .JSWeakMap => true,
else => false,
};
}
pub inline fn isIndexable(this: JSType) bool {
return switch (this) {
.Object,
.FinalObject,
.Array,
.DerivedArray,
.ErrorInstance,
.JSFunction,
.InternalFunction,
.ArrayBuffer,
.BigInt64Array,
.BigUint64Array,
.Float32Array,
.Float64Array,
.Int16Array,
.Int32Array,
.Int8Array,
.Uint16Array,
.Uint32Array,
.Uint8Array,
.Uint8ClampedArray,
=> true,
else => false,
};
}
};
pub inline fn cast(ptr: anytype) JSValue {
return @as(JSValue, @enumFromInt(@as(i64, @bitCast(@intFromPtr(ptr)))));
}
pub fn coerceToInt32(this: JSValue, globalThis: *JSC.JSGlobalObject) i32 {
return cppFn("coerceToInt32", .{ this, globalThis });
}
pub fn coerceToInt64(this: JSValue, globalThis: *JSC.JSGlobalObject) i64 {
return cppFn("coerceToInt64", .{ this, globalThis });
}
pub fn getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSValue {
return JSC.JSObject.getIndex(this, globalThis, i);
}
const PropertyIteratorFn = *const fn (
globalObject_: *JSGlobalObject,
ctx_ptr: ?*anyopaque,
key: [*c]ZigString,
value: JSValue,
is_symbol: bool,
) callconv(.C) void;
pub fn forEachProperty(
this: JSValue,
globalThis: *JSC.JSGlobalObject,
ctx: ?*anyopaque,
callback: PropertyIteratorFn,
) void {
cppFn("forEachProperty", .{ this, globalThis, ctx, callback });
}
pub fn forEachPropertyOrdered(
this: JSValue,
globalObject: *JSC.JSGlobalObject,
ctx: ?*anyopaque,
callback: PropertyIteratorFn,
) void {
cppFn("forEachPropertyOrdered", .{ this, globalObject, ctx, callback });
}
pub fn coerceToDouble(
this: JSValue,
globalObject: *JSC.JSGlobalObject,
) f64 {
return cppFn("coerceToDouble", .{ this, globalObject });
}
pub fn coerce(this: JSValue, comptime T: type, globalThis: *JSC.JSGlobalObject) T {
return switch (T) {
ZigString => this.getZigString(globalThis),
bool => this.toBooleanSlow(globalThis),
f64 => {
if (this.isNumber()) {
return this.asDouble();
}
return this.coerceToDouble(globalThis);
},
i32 => {
if (this.isInt32()) {
return this.asInt32();
}
if (this.isNumber()) {
return @as(i32, @truncate(this.coerceDoubleTruncatingIntoInt64()));
}
return this.coerceToInt32(globalThis);
},
else => @compileError("Unsupported coercion type"),
};
}
/// This does not call [Symbol.toPrimitive] or [Symbol.toStringTag].
/// This is only safe when you don't want to do conversions across non-primitive types.
pub fn to(this: JSValue, comptime T: type) T {
return switch (comptime T) {
u32 => toU32(this),
u16 => toU16(this),
c_uint => @as(c_uint, @intCast(toU32(this))),
c_int => @as(c_int, @intCast(toInt32(this))),
?AnyPromise => asAnyPromise(this),
u52 => @as(u52, @truncate(@as(u64, @intCast(@max(this.toInt64(), 0))))),
i52 => @as(i52, @truncate(@as(i52, @intCast(this.toInt64())))),
u64 => toUInt64NoTruncate(this),
u8 => @as(u8, @truncate(toU32(this))),
i16 => @as(i16, @truncate(toInt32(this))),
i8 => @as(i8, @truncate(toInt32(this))),
i32 => @as(i32, @truncate(toInt32(this))),
i64 => this.toInt64(),
bool => this.toBoolean(),
else => @compileError("Not implemented yet"),
};
}
pub fn isInstanceOf(this: JSValue, global: *JSGlobalObject, constructor: JSValue) bool {
if (!this.isCell())
return false;
return cppFn("isInstanceOf", .{ this, global, constructor });
}
pub fn call(this: JSValue, globalThis: *JSGlobalObject, args: []const JSC.JSValue) JSC.JSValue {
return callWithThis(this, globalThis, JSC.JSValue.jsUndefined(), args);
}
pub fn callWithGlobalThis(this: JSValue, globalThis: *JSGlobalObject, args: []const JSC.JSValue) JSC.JSValue {
JSC.markBinding(@src());
return JSC.C.JSObjectCallAsFunctionReturnValue(
globalThis,
this,
globalThis.toJS(),
args.len,
@as(?[*]const JSC.C.JSValueRef, @ptrCast(args.ptr)),
);
}
pub fn callWithThis(this: JSValue, globalThis: *JSGlobalObject, thisValue: JSC.JSValue, args: []const JSC.JSValue) JSC.JSValue {
JSC.markBinding(@src());
return JSC.C.JSObjectCallAsFunctionReturnValue(
globalThis,
this,
thisValue,
args.len,
@as(?[*]const JSC.C.JSValueRef, @ptrCast(args.ptr)),
);
}
pub fn jsType(
this: JSValue,
) JSType {
return cppFn("jsType", .{this});
}
pub fn jsTypeLoose(
this: JSValue,
) JSType {
if (this.isNumber()) {
return JSType.NumberObject;
}
return this.jsType();
}
pub fn createEmptyObject(global: *JSGlobalObject, len: usize) JSValue {
std.debug.assert(len <= 64); // max inline capacity JSC allows is 64. If you run into this, just set it to 0.
return cppFn("createEmptyObject", .{ global, len });
}
pub fn createEmptyArray(global: *JSGlobalObject, len: usize) JSValue {
return cppFn("createEmptyArray", .{ global, len });
}
pub fn putRecord(value: JSValue, global: *JSGlobalObject, key: *ZigString, values: [*]ZigString, values_len: usize) void {
return cppFn("putRecord", .{ value, global, key, values, values_len });
}
pub fn put(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: JSC.JSValue) void {
return cppFn("put", .{ value, global, key, result });
}
pub fn putIndex(value: JSValue, globalObject: *JSGlobalObject, i: u32, out: JSValue) void {
cppFn("putIndex", .{ value, globalObject, i, out });
}
pub fn push(value: JSValue, globalObject: *JSGlobalObject, out: JSValue) void {
cppFn("push", .{ value, globalObject, out });
}
pub fn as(value: JSValue, comptime ZigType: type) ?*ZigType {
if (value.isEmptyOrUndefinedOrNull())
return null;
if (comptime ZigType == DOMURL) {
return DOMURL.cast(value);
}
if (comptime ZigType == FetchHeaders) {
return FetchHeaders.cast(value);
}
if (comptime @hasDecl(ZigType, "fromJS") and @TypeOf(ZigType.fromJS) == fn (JSC.JSValue) ?*ZigType) {
if (comptime ZigType == JSC.WebCore.Blob) {
if (ZigType.fromJS(value)) |blob| {
return blob;
}
if (JSC.API.BuildArtifact.fromJS(value)) |build| {
return &build.blob;
}
return null;
}
return ZigType.fromJS(value);
}
return JSC.GetJSPrivateData(ZigType, value.asObjectRef());
}
extern fn JSBuffer__isBuffer(*JSGlobalObject, JSValue) bool;
pub fn isBuffer(value: JSValue, global: *JSGlobalObject) bool {
JSC.markBinding(@src());
return JSBuffer__isBuffer(global, value);
}
pub fn isRegExp(this: JSValue) bool {
return this.jsType() == .RegExpObject;
}
pub fn isDate(this: JSValue) bool {
return this.jsType() == .JSDate;
}
pub fn asCheckLoaded(value: JSValue, comptime ZigType: type) ?*ZigType {
if (!ZigType.Class.isLoaded() or value.isUndefinedOrNull())
return null;
return JSC.GetJSPrivateData(ZigType, value.asObjectRef());
}
pub fn protect(this: JSValue) void {
if (this.isEmptyOrUndefinedOrNull() or this.isNumber()) return;
JSC.C.JSValueProtect(JSC.VirtualMachine.get().global, this.asObjectRef());
}
pub fn unprotect(this: JSValue) void {
if (this.isEmptyOrUndefinedOrNull() or this.isNumber()) return;
JSC.C.JSValueUnprotect(JSC.VirtualMachine.get().global, this.asObjectRef());
}
pub fn JSONValueFromString(
global: *JSGlobalObject,
str: [*]const u8,
len: usize,
ascii: bool,
) JSValue {
return cppFn("JSONValueFromString", .{ global, str, len, ascii });
}
/// Create an object with exactly two properties
pub fn createObject2(global: *JSGlobalObject, key1: *const ZigString, key2: *const ZigString, value1: JSValue, value2: JSValue) JSValue {
return cppFn("createObject2", .{ global, key1, key2, value1, value2 });
}
pub fn asPromisePtr(this: JSValue, comptime T: type) *T {
return asPtr(this, T);
}
pub fn createRopeString(this: JSValue, rhs: JSValue, globalThis: *JSC.JSGlobalObject) JSValue {
return cppFn("createRopeString", .{ this, rhs, globalThis });
}
pub fn getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue {
return cppFn("getErrorsProperty", .{ this, globalObject });
}
pub fn makeWithNameAndPrototype(globalObject: *JSGlobalObject, class: ?*anyopaque, instance: ?*anyopaque, name_: *const ZigString) JSValue {
return cppFn("makeWithNameAndPrototype", .{ globalObject, class, instance, name_ });
}
pub fn createBufferFromLength(globalObject: *JSGlobalObject, len: usize) JSValue {
JSC.markBinding(@src());
return JSBuffer__bufferFromLength(globalObject, @as(i64, @intCast(len)));
}
pub fn jestSnapshotPrettyFormat(this: JSValue, out: *MutableString, globalObject: *JSGlobalObject) !void {
var buffered_writer = MutableString.BufferedWriter{ .context = out };
var writer = buffered_writer.writer();
const Writer = @TypeOf(writer);
const fmt_options = JestPrettyFormat.FormatOptions{
.enable_colors = false,
.add_newline = false,
.flush = false,
.quote_strings = true,
};
JestPrettyFormat.format(
.Debug,
globalObject,
@as([*]const JSValue, @ptrCast(&this)),
1,
Writer,
Writer,
writer,
fmt_options,
);
try buffered_writer.flush();
const count: usize = brk: {
var total: usize = 0;
var remain = out.list.items;
while (strings.indexOfChar(remain, '`')) |i| {
total += 1;
remain = remain[i + 1 ..];
}
break :brk total;
};
if (count > 0) {
var result = try out.allocator.alloc(u8, count + out.list.items.len);
var input = out.list.items;
var input_i: usize = 0;
var result_i: usize = 0;
while (strings.indexOfChar(input[input_i..], '`')) |i| {
bun.copy(u8, result[result_i..], input[input_i .. input_i + i]);
result_i += i;
result[result_i] = '\\';
result[result_i + 1] = '`';
result_i += 2;
input_i += i + 1;
}
if (result_i != result.len) {
bun.copy(u8, result[result_i..], input[input_i..]);
}
out.deinit();
out.list.items = result;
out.list.capacity = result.len;
}
}
pub fn jestPrettyFormat(this: JSValue, out: *MutableString, globalObject: *JSGlobalObject) !void {
var buffered_writer = MutableString.BufferedWriter{ .context = out };
var writer = buffered_writer.writer();
const Writer = @TypeOf(writer);
const fmt_options = JSC.ZigConsoleClient.FormatOptions{
.enable_colors = false,
.add_newline = false,
.flush = false,
.ordered_properties = true,
.quote_strings = true,
};
JSC.ZigConsoleClient.format(
.Debug,
globalObject,
@as([*]const JSValue, @ptrCast(&this)),
1,
Writer,
Writer,
writer,
fmt_options,
);
try buffered_writer.flush();
}
extern fn JSBuffer__bufferFromLength(*JSGlobalObject, i64) JSValue;
/// Must come from globally-allocated memory if allocator is not null
pub fn createBuffer(globalObject: *JSGlobalObject, slice: []u8, allocator: ?std.mem.Allocator) JSValue {
JSC.markBinding(@src());
@setRuntimeSafety(false);
if (allocator) |alloc| {
return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, alloc.ptr, JSC.MarkedArrayBuffer_deallocator);
} else {
return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, null, null);
}
}
pub fn createUninitializedUint8Array(globalObject: *JSGlobalObject, len: usize) JSValue {
JSC.markBinding(@src());
return shim.cppFn("createUninitializedUint8Array", .{ globalObject, len });
}
pub fn createBufferWithCtx(globalObject: *JSGlobalObject, slice: []u8, ptr: ?*anyopaque, func: JSC.C.JSTypedArrayBytesDeallocator) JSValue {
JSC.markBinding(@src());
@setRuntimeSafety(false);
return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, ptr, func);
}
extern fn JSBuffer__bufferFromPointerAndLengthAndDeinit(*JSGlobalObject, [*]u8, usize, ?*anyopaque, JSC.C.JSTypedArrayBytesDeallocator) JSValue;
pub fn jsNumberWithType(comptime Number: type, number: Number) JSValue {
return switch (comptime Number) {
JSValue => number,
f32, f64 => jsNumberFromDouble(@as(f64, number)),
c_ushort, u8, i16, i32, c_int, i8, u16 => jsNumberFromInt32(@as(i32, @intCast(number))),
u32, u52, c_uint, i64 => jsNumberFromInt64(@as(i64, @intCast(number))),
usize, u64 => jsNumberFromUint64(@as(u64, @intCast(number))),
comptime_int => switch (number) {
0...std.math.maxInt(i32) => jsNumberFromInt32(@as(i32, @intCast(number))),
else => jsNumberFromInt64(@as(i64, @intCast(number))),
},
else => @compileError("Type transformation missing for number of type: " ++ @typeName(Number)),
};
}
pub fn createInternalPromise(globalObject: *JSGlobalObject) JSValue {
return cppFn("createInternalPromise", .{globalObject});
}
pub fn asInternalPromise(
value: JSValue,
) ?*JSInternalPromise {
return cppFn("asInternalPromise", .{
value,
});
}
pub fn asPromise(
value: JSValue,
) ?*JSPromise {
return cppFn("asPromise", .{
value,
});
}
pub fn asAnyPromise(
value: JSValue,
) ?AnyPromise {
if (value.isEmptyOrUndefinedOrNull()) return null;
if (value.asInternalPromise()) |promise| {
return AnyPromise{
.Internal = promise,
};
}
if (value.asPromise()) |promise| {
return AnyPromise{
.Normal = promise,
};
}
return null;
}
pub fn jsNumber(number: anytype) JSValue {
return jsNumberWithType(@TypeOf(number), number);
}
pub inline fn jsNull() JSValue {
return JSValue.null;
}
pub inline fn jsUndefined() JSValue {
return JSValue.undefined;
}
pub inline fn jsBoolean(i: bool) JSValue {
const out = cppFn("jsBoolean", .{i});
return out;
}
pub fn jsTDZValue() JSValue {
return cppFn("jsTDZValue", .{});
}
pub fn jsDoubleNumber(i: f64) JSValue {
return cppFn("jsDoubleNumber", .{i});
}
pub fn className(this: JSValue, globalThis: *JSGlobalObject) ZigString {
var str = ZigString.init("");
this.getClassName(globalThis, &str);
return str;
}
pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]const ZigString, strings_count: usize, clone: bool) JSValue {
return cppFn("createStringArray", .{
globalThis,
str,
strings_count,
clone,
});
}
pub fn fromEntries(globalThis: *JSGlobalObject, keys: [*c]ZigString, values: [*c]ZigString, strings_count: usize, clone: bool) JSValue {
return cppFn("fromEntries", .{
globalThis,
keys,
values,
strings_count,
clone,
});
}
pub inline fn arrayIterator(this: JSValue, global: *JSGlobalObject) JSArrayIterator {
return JSArrayIterator.init(this, global);
}
pub fn jsNumberFromDouble(i: f64) JSValue {
return FFI.DOUBLE_TO_JSVALUE(i).asJSValue;
}
pub fn jsNumberFromChar(i: u8) JSValue {
return cppFn("jsNumberFromChar", .{i});
}
pub fn jsNumberFromU16(i: u16) JSValue {
return cppFn("jsNumberFromU16", .{i});
}
pub fn jsNumberFromInt32(i: i32) JSValue {
return FFI.INT32_TO_JSVALUE(i).asJSValue;
}
pub fn jsNumberFromInt64(i: i64) JSValue {
if (i <= std.math.maxInt(i32)) {
return jsNumberFromInt32(@as(i32, @intCast(i)));
}
return jsNumberFromDouble(@as(f64, @floatFromInt(@as(i52, @truncate(i)))));
}
pub inline fn toJS(this: JSValue, _: *const JSGlobalObject) JSValue {
return this;
}
pub fn jsNumberFromUint64(i: u64) JSValue {
if (i <= std.math.maxInt(i32)) {
return jsNumberFromInt32(@as(i32, @intCast(i)));
}
return jsNumberFromDouble(@as(f64, @floatFromInt(@as(i52, @intCast(@as(u51, @truncate(i)))))));
}
pub fn coerceDoubleTruncatingIntoInt64(this: JSValue) i64 {
const double_value = this.asDouble();
if (std.math.isNan(double_value))
return std.math.minInt(i64);
// coerce NaN or Infinity to either -maxInt or maxInt
if (std.math.isInf(double_value)) {
return if (double_value < 0) @as(i64, std.math.minInt(i64)) else @as(i64, std.math.maxInt(i64));
}
return @as(
i64,
@intFromFloat(double_value),
);
}
/// Decimal values are truncated without rounding.
/// `-Infinity` and `NaN` coerce to -minInt(64)
/// `Infinity` coerces to maxInt(64)
pub fn toInt64(this: JSValue) i64 {
if (this.isInt32()) {
return this.asInt32();
}
if (this.isNumber()) {
return this.coerceDoubleTruncatingIntoInt64();
}
return cppFn("toInt64", .{this});
}
pub const ComparisonResult = enum(u8) {
equal,
undefined_result,
greater_than,
less_than,
invalid_comparison,
};
pub fn asBigIntCompare(this: JSValue, global: *JSGlobalObject, other: JSValue) ComparisonResult {
if (!this.isBigInt() or (!other.isBigInt() and !other.isNumber())) {
return .invalid_comparison;
}
return cppFn("asBigIntCompare", .{ this, global, other });
}
pub inline fn isUndefined(this: JSValue) bool {
return @intFromEnum(this) == 0xa;
}
pub inline fn isNull(this: JSValue) bool {
return @intFromEnum(this) == 0x2;
}
pub inline fn isEmptyOrUndefinedOrNull(this: JSValue) bool {
return switch (@intFromEnum(this)) {
0, 0xa, 0x2 => true,
else => false,
};
}
pub fn isUndefinedOrNull(this: JSValue) bool {
return switch (@intFromEnum(this)) {
0xa, 0x2 => true,
else => false,
};
}
/// Empty as in "JSValue {}" rather than an empty string
pub inline fn isEmpty(this: JSValue) bool {
return switch (@intFromEnum(this)) {
0 => true,
else => false,
};
}
pub fn isBoolean(this: JSValue) bool {
return cppFn("isBoolean", .{this});
}
pub fn isAnyInt(this: JSValue) bool {
return cppFn("isAnyInt", .{this});
}
pub fn isUInt32AsAnyInt(this: JSValue) bool {
return cppFn("isUInt32AsAnyInt", .{this});
}
pub fn asEncoded(this: JSValue) FFI.EncodedJSValue {
return FFI.EncodedJSValue{ .asJSValue = this };
}
pub fn fromCell(ptr: *anyopaque) JSValue {
return (FFI.EncodedJSValue{ .asPtr = ptr }).asJSValue;
}
pub fn isInt32(this: JSValue) bool {
return FFI.JSVALUE_IS_INT32(.{ .asJSValue = this });
}
pub fn isInt32AsAnyInt(this: JSValue) bool {
return cppFn("isInt32AsAnyInt", .{this});
}
pub fn isNumber(this: JSValue) bool {
return FFI.JSVALUE_IS_NUMBER(.{ .asJSValue = this });
}
pub fn isError(this: JSValue) bool {
if (!this.isCell())
return false;
return this.jsType() == JSType.ErrorInstance;
}
pub fn isAnyError(this: JSValue) bool {
if (!this.isCell())
return false;
return cppFn("isAnyError", .{this});
}
pub fn toError_(this: JSValue) JSValue {
return cppFn("toError_", .{this});
}
pub fn toError(this: JSValue) ?JSValue {
const res = this.toError_();
if (res == .zero)
return null;
return res;
}
/// Returns true if
/// - `" string literal"`
/// - `new String("123")`
/// - `class DerivedString extends String; new DerivedString("123")`
pub inline fn isString(this: JSValue) bool {
if (!this.isCell())
return false;
return jsType(this).isStringLike();
}
pub fn isBigInt(this: JSValue) bool {
return cppFn("isBigInt", .{this});
}
pub fn isHeapBigInt(this: JSValue) bool {
return cppFn("isHeapBigInt", .{this});
}
pub fn isBigInt32(this: JSValue) bool {
return cppFn("isBigInt32", .{this});
}
pub fn isSymbol(this: JSValue) bool {
return cppFn("isSymbol", .{this});
}
pub fn isPrimitive(this: JSValue) bool {
return cppFn("isPrimitive", .{this});
}
pub fn isGetterSetter(this: JSValue) bool {
return cppFn("isGetterSetter", .{this});
}
pub fn isCustomGetterSetter(this: JSValue) bool {
return cppFn("isCustomGetterSetter", .{this});
}
pub inline fn isObject(this: JSValue) bool {
return this.isCell() and this.jsType().isObject();
}
pub fn isClass(this: JSValue, global: *JSGlobalObject) bool {
return cppFn("isClass", .{ this, global });
}
pub fn isConstructor(this: JSValue) bool {
if (!this.isCell()) return false;
return cppFn("isConstructor", .{this});
}
pub fn getNameProperty(this: JSValue, global: *JSGlobalObject, ret: *ZigString) void {
if (this.isEmptyOrUndefinedOrNull()) {
return;
}
cppFn("getNameProperty", .{ this, global, ret });
}
pub fn getName(this: JSValue, global: *JSGlobalObject) ZigString {
var ret = ZigString.init("");
getNameProperty(this, global, &ret);
return ret;
}
pub fn getClassName(this: JSValue, global: *JSGlobalObject, ret: *ZigString) void {
cppFn("getClassName", .{ this, global, ret });
}
pub inline fn isCell(this: JSValue) bool {
return switch (this) {
.zero, .undefined, .null, .true, .false => false,
else => (@as(u64, @bitCast(@intFromEnum(this))) & FFI.NotCellMask) == 0,
};
}
pub fn asCell(this: JSValue) *JSCell {
return cppFn("asCell", .{this});
}
pub fn isCallable(this: JSValue, vm: *VM) bool {
return cppFn("isCallable", .{ this, vm });
}
pub fn isException(this: JSValue, vm: *VM) bool {
return cppFn("isException", .{ this, vm });
}
pub fn isTerminationException(this: JSValue, vm: *VM) bool {
return cppFn("isTerminationException", .{ this, vm });
}
pub fn toZigException(this: JSValue, global: *JSGlobalObject, exception: *ZigException) void {
return cppFn("toZigException", .{ this, global, exception });
}
pub fn toZigString(this: JSValue, out: *ZigString, global: *JSGlobalObject) void {
return cppFn("toZigString", .{ this, out, global });
}
pub fn toBunString(this: JSValue, globalObject: *JSC.JSGlobalObject) bun.String {
return bun.String.fromJS(this, globalObject);
}
/// this: RegExp value
/// other: string value
pub fn toMatch(this: JSValue, global: *JSGlobalObject, other: JSValue) bool {
return cppFn("toMatch", .{ this, global, other });
}
pub fn asArrayBuffer_(this: JSValue, global: *JSGlobalObject, out: *ArrayBuffer) bool {
return cppFn("asArrayBuffer_", .{ this, global, out });
}
pub fn asArrayBuffer(this: JSValue, global: *JSGlobalObject) ?ArrayBuffer {
var out: ArrayBuffer = .{
.offset = 0,
.len = 0,
.byte_len = 0,
.shared = false,
.typed_array_type = .Uint8Array,
};
if (this.asArrayBuffer_(global, &out)) {
out.value = this;
return out;
}
return null;
}
pub fn fromInt64NoTruncate(globalObject: *JSGlobalObject, i: i64) JSValue {
return cppFn("fromInt64NoTruncate", .{ globalObject, i });
}
pub fn fromUInt64NoTruncate(globalObject: *JSGlobalObject, i: u64) JSValue {
return cppFn("fromUInt64NoTruncate", .{ globalObject, i });
}
pub fn toUInt64NoTruncate(this: JSValue) u64 {
return cppFn("toUInt64NoTruncate", .{
this,
});
}
pub inline fn getZigString(this: JSValue, global: *JSGlobalObject) ZigString {
var str = ZigString.init("");
this.toZigString(&str, global);
return str;
}
/// Convert a JSValue to a string, potentially calling `toString` on the
/// JSValue in JavaScript.
///
/// This function can throw an exception in the `JSC::VM`. **If
/// the exception is not handled correctly, Bun will segfault**
///
/// To handle exceptions, use `JSValue.toSliceOrNull`.
pub inline fn toSlice(this: JSValue, global: *JSGlobalObject, allocator: std.mem.Allocator) ZigString.Slice {
return getZigString(this, global).toSlice(allocator);
}
pub inline fn toSliceZ(this: JSValue, global: *JSGlobalObject, allocator: std.mem.Allocator) ZigString.Slice {
return getZigString(this, global).toSliceZ(allocator);
}
// On exception, this returns the empty string.
pub fn toString(this: JSValue, globalThis: *JSGlobalObject) *JSString {
return cppFn("toString", .{ this, globalThis });
}
pub fn jsonStringify(this: JSValue, globalThis: *JSGlobalObject, indent: u32, out: *bun.String) void {
return cppFn("jsonStringify", .{ this, globalThis, indent, out });
}
/// On exception, this returns null, to make exception checks clearer.
pub fn toStringOrNull(this: JSValue, globalThis: *JSGlobalObject) ?*JSString {
return cppFn("toStringOrNull", .{ this, globalThis });
}
/// Call `toString()` on the JSValue and clone the result.
/// On exception, this returns null.
pub fn toSliceOrNull(this: JSValue, globalThis: *JSGlobalObject) ?ZigString.Slice {
var str = this.toStringOrNull(globalThis) orelse return null;
return str.toSlice(globalThis, globalThis.allocator());
}
/// Call `toString()` on the JSValue and clone the result.
/// On exception or out of memory, this returns null.
///
/// Remember that `Symbol` throws an exception when you call `toString()`.
pub fn toSliceClone(this: JSValue, globalThis: *JSGlobalObject) ?ZigString.Slice {
return this.toSliceCloneWithAllocator(globalThis, globalThis.allocator());
}
/// On exception or out of memory, this returns null, to make exception checks clearer.
pub fn toSliceCloneWithAllocator(
this: JSValue,
globalThis: *JSGlobalObject,
allocator: std.mem.Allocator,
) ?ZigString.Slice {
var str = this.toStringOrNull(globalThis) orelse return null;
return str.toSlice(globalThis, allocator).cloneIfNeeded(allocator) catch {
globalThis.throwOutOfMemory();
return null;
};
}
pub fn toObject(this: JSValue, globalThis: *JSGlobalObject) *JSObject {
return cppFn("toObject", .{ this, globalThis });
}
pub fn getPrototype(this: JSValue, globalObject: *JSGlobalObject) JSValue {
return cppFn("getPrototype", .{ this, globalObject });
}
pub fn eqlValue(this: JSValue, other: JSValue) bool {
return cppFn("eqlValue", .{ this, other });
}
pub fn eqlCell(this: JSValue, other: *JSCell) bool {
return cppFn("eqlCell", .{ this, other });
}
pub const BuiltinName = enum(u8) {
method,
headers,
status,
url,
body,
data,
toString,
redirect,
};
// intended to be more lightweight than ZigString
pub fn fastGet(this: JSValue, global: *JSGlobalObject, builtin_name: BuiltinName) ?JSValue {
const result = fastGet_(this, global, @intFromEnum(builtin_name));
if (result == .zero) {
return null;
}
return result;
}
pub fn fastGetDirect(this: JSValue, global: *JSGlobalObject, builtin_name: BuiltinName) ?JSValue {
const result = fastGetDirect_(this, global, @intFromEnum(builtin_name));
if (result == .zero) {
return null;
}
return result;
}
pub fn fastGet_(this: JSValue, global: *JSGlobalObject, builtin_name: u8) JSValue {
return cppFn("fastGet_", .{ this, global, builtin_name });
}
pub fn fastGetDirect_(this: JSValue, global: *JSGlobalObject, builtin_name: u8) JSValue {
return cppFn("fastGetDirect_", .{ this, global, builtin_name });
}
/// Do not use this directly! Use `get` instead.
pub fn getIfPropertyExistsImpl(this: JSValue, global: *JSGlobalObject, ptr: [*]const u8, len: u32) JSValue {
return cppFn("getIfPropertyExistsImpl", .{ this, global, ptr, len });
}
pub fn getIfPropertyExistsFromPath(this: JSValue, global: *JSGlobalObject, path: JSValue) JSValue {
return cppFn("getIfPropertyExistsFromPath", .{ this, global, path });
}
pub fn getSymbolDescription(this: JSValue, global: *JSGlobalObject, str: *ZigString) void {
cppFn("getSymbolDescription", .{ this, global, str });
}
pub fn symbolFor(global: *JSGlobalObject, str: *ZigString) JSValue {
return cppFn("symbolFor", .{ global, str });
}
pub fn symbolKeyFor(this: JSValue, global: *JSGlobalObject, str: *ZigString) bool {
return cppFn("symbolKeyFor", .{ this, global, str });
}
pub fn _then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: JSNativeFn, reject: JSNativeFn) void {
return cppFn("_then", .{ this, global, ctx, resolve, reject });
}
pub fn then(this: JSValue, global: *JSGlobalObject, ctx: ?*anyopaque, resolve: JSNativeFn, reject: JSNativeFn) void {
if (comptime bun.Environment.allow_assert)
std.debug.assert(JSValue.fromPtr(ctx).asPtr(anyopaque) == ctx.?);
return this._then(global, JSValue.fromPtr(ctx), resolve, reject);
}
pub fn getDescription(this: JSValue, global: *JSGlobalObject) ZigString {
var zig_str = ZigString.init("");
getSymbolDescription(this, global, &zig_str);
return zig_str;
}
pub fn get(this: JSValue, global: *JSGlobalObject, property: []const u8) ?JSValue {
const value = getIfPropertyExistsImpl(this, global, property.ptr, @as(u32, @intCast(property.len)));
return if (@intFromEnum(value) != 0) value else return null;
}
pub fn implementsToString(this: JSValue, global: *JSGlobalObject) bool {
std.debug.assert(this.isCell());
const function = this.fastGet(global, BuiltinName.toString) orelse return false;
return function.isCell() and function.isCallable(global.vm());
}
pub fn getTruthy(this: JSValue, global: *JSGlobalObject, property: []const u8) ?JSValue {
if (get(this, global, property)) |prop| {
if (prop.isEmptyOrUndefinedOrNull()) return null;
return prop;
}
return null;
}
pub fn toEnumFromMap(
this: JSValue,
globalThis: *JSGlobalObject,
comptime property_name: []const u8,
comptime Enum: type,
comptime StringMap: anytype,
) !Enum {
if (!this.isString()) {
globalThis.throwInvalidArguments(property_name ++ " must be a string", .{});
return error.JSError;
}
const target_str = this.getZigString(globalThis);
return StringMap.getWithEql(target_str, ZigString.eqlComptime) orelse {
const one_of = struct {
pub const list = brk: {
var str: []const u8 = "'";
const field_names = bun.meta.enumFieldNames(Enum);
for (field_names, 0..) |entry, i| {
str = str ++ entry ++ "'";
if (i < field_names.len - 2) {
str = str ++ ", '";
} else if (i == field_names.len - 2) {
str = str ++ " or '";
}
}
break :brk str;
};
pub const label = property_name ++ " must be one of " ++ list;
}.label;
globalThis.throwInvalidArguments(one_of, .{});
return error.JSError;
};
}
pub fn toEnum(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8, comptime Enum: type) !Enum {
return toEnumFromMap(this, globalThis, property_name, Enum, Enum.Map);
}
pub fn toOptionalEnum(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8, comptime Enum: type) !?Enum {
if (this.isEmptyOrUndefinedOrNull())
return null;
return toEnum(this, globalThis, property_name, Enum);
}
pub fn getOptionalEnum(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8, comptime Enum: type) !?Enum {
if (get(this, globalThis, property_name)) |prop| {
if (prop.isEmptyOrUndefinedOrNull())
return null;
return try toEnum(prop, globalThis, property_name, Enum);
}
return null;
}
pub fn getArray(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) !?JSValue {
if (getTruthy(this, globalThis, property_name)) |prop| {
if (!prop.jsTypeLoose().isArray()) {
globalThis.throwInvalidArguments(property_name ++ " must be an array", .{});
return error.JSError;
}
if (prop.getLength(globalThis) == 0) {
return null;
}
return prop;
}
return null;
}
pub fn getObject(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) !?JSValue {
if (getTruthy(this, globalThis, property_name)) |prop| {
if (!prop.jsTypeLoose().isObject()) {
globalThis.throwInvalidArguments(property_name ++ " must be an object", .{});
return error.JSError;
}
return prop;
}
return null;
}
pub fn getFunction(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) !?JSValue {
if (getTruthy(this, globalThis, property_name)) |prop| {
if (!prop.isCell() or !prop.isCallable(globalThis.vm())) {
globalThis.throwInvalidArguments(property_name ++ " must be a function", .{});
return error.JSError;
}
return prop;
}
return null;
}
pub fn getOptional(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8, comptime T: type) !?T {
if (getTruthy(this, globalThis, property_name)) |prop| {
switch (comptime T) {
bool => {
if (prop.isBoolean()) {
return prop.toBoolean();
}
if (prop.isNumber()) {
return prop.asDouble() != 0;
}
globalThis.throwInvalidArguments(property_name ++ " must be a boolean", .{});
return error.JSError;
},
ZigString.Slice => {
if (prop.isString()) {
if (return prop.toSliceOrNull(globalThis)) |str| {
return str;
}
}
globalThis.throwInvalidArguments(property_name ++ " must be a string", .{});
return error.JSError;
},
else => @compileError("TODO:" ++ @typeName(T)),
}
}
return null;
}
/// Alias for getIfPropertyExists
pub const getIfPropertyExists = get;
pub fn createTypeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue {
return cppFn("createTypeError", .{ message, code, global });
}
pub fn createRangeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue {
return cppFn("createRangeError", .{ message, code, global });
}
/// Object.is()
/// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽.
/// https://tc39.es/ecma262/#sec-samevalue
pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return @intFromEnum(this) == @intFromEnum(other) or cppFn("isSameValue", .{ this, other, global });
}
pub fn deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("deepEquals", .{ this, other, global });
}
/// same as `JSValue.deepEquals`, but with jest asymmetric matchers enabled
pub fn jestDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("jestDeepEquals", .{ this, other, global });
}
pub fn strictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("strictDeepEquals", .{ this, other, global });
}
/// same as `JSValue.strictDeepEquals`, but with jest asymmetric matchers enabled
pub fn jestStrictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("jestStrictDeepEquals", .{ this, other, global });
}
pub fn deepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool {
return cppFn("deepMatch", .{ this, subset, global, replace_props_with_asymmetric_matchers });
}
/// same as `JSValue.deepMatch`, but with jest asymmetric matchers enabled
pub fn jestDeepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool {
return cppFn("jestDeepMatch", .{ this, subset, global, replace_props_with_asymmetric_matchers });
}
pub const DiffMethod = enum(u8) {
none,
character,
word,
line,
};
pub fn determineDiffMethod(this: JSValue, other: JSValue, global: *JSGlobalObject) DiffMethod {
if ((this.isString() and other.isString()) or (this.isBuffer(global) and other.isBuffer(global))) return .character;
if ((this.isRegExp() and other.isObject()) or (this.isObject() and other.isRegExp())) return .character;
if (this.isObject() and other.isObject()) return .line;
return .none;
}
pub fn asString(this: JSValue) *JSString {
return cppFn("asString", .{
this,
});
}
/// Get the internal number of the `JSC::DateInstance` object
/// Returns NaN if the value is not a `JSC::DateInstance` (`Date` in JS)
pub fn getUnixTimestamp(this: JSValue) f64 {
return cppFn("getUnixTimestamp", .{
this,
});
}
pub fn toFmt(
this: JSValue,
global: *JSGlobalObject,
formatter: *Exports.ZigConsoleClient.Formatter,
) Exports.ZigConsoleClient.Formatter.ZigFormatter {
formatter.remaining_values = &[_]JSValue{};
if (formatter.map_node) |node| {
node.release();
formatter.map_node = null;
}
return Exports.ZigConsoleClient.Formatter.ZigFormatter{
.formatter = formatter,
.value = this,
.global = global,
};
}
pub fn asObject(this: JSValue) JSObject {
return cppFn("asObject", .{
this,
});
}
pub fn asNumber(this: JSValue) f64 {
if (this.isInt32()) {
return @as(f64, @floatFromInt(this.asInt32()));
}
if (isNumber(this)) {
return asDouble(this);
}
if (this.isUndefinedOrNull()) {
return 0.0;
} else if (this.isBoolean()) {
return if (asBoolean(this)) 1.0 else 0.0;
}
return cppFn("asNumber", .{
this,
});
}
pub fn asDouble(this: JSValue) f64 {
return FFI.JSVALUE_TO_DOUBLE(.{ .asJSValue = this });
}
pub fn asPtr(this: JSValue, comptime Pointer: type) *Pointer {
return @as(*Pointer, @ptrFromInt(this.asPtrAddress()));
}
pub fn fromPtrAddress(addr: anytype) JSValue {
return jsNumber(@as(f64, @floatFromInt(@as(usize, @bitCast(@as(usize, addr))))));
}
pub fn asPtrAddress(this: JSValue) usize {
return @as(usize, @bitCast(@as(usize, @intFromFloat(this.asDouble()))));
}
pub fn fromPtr(addr: anytype) JSValue {
return fromPtrAddress(@intFromPtr(addr));
}
pub fn toBooleanSlow(this: JSValue, global: *JSGlobalObject) bool {
return cppFn("toBooleanSlow", .{ this, global });
}
pub fn toBoolean(this: JSValue) bool {
if (isUndefinedOrNull(this)) {
return false;
}
return asBoolean(this);
}
pub fn asBoolean(this: JSValue) bool {
return FFI.JSVALUE_TO_BOOL(.{ .asJSValue = this });
}
pub inline fn asInt52(this: JSValue) i64 {
if (comptime bun.Environment.allow_assert) {
std.debug.assert(this.isNumber());
}
return @as(i64, @intFromFloat(@max(@min(this.asDouble(), std.math.maxInt(i52)), std.math.minInt(i52))));
}
pub fn toInt32(this: JSValue) i32 {
if (this.isInt32()) {
return asInt32(this);
}
if (this.isNumber()) {
return @as(i32, @truncate(this.asInt52()));
}
if (comptime bun.Environment.allow_assert) {
std.debug.assert(!this.isString()); // use coerce() instead
std.debug.assert(!this.isCell()); // use coerce() instead
}
return cppFn("toInt32", .{
this,
});
}
pub fn asInt32(this: JSValue) i32 {
return FFI.JSVALUE_TO_INT32(.{ .asJSValue = this });
}
pub inline fn toU16(this: JSValue) u16 {
return @as(u16, @truncate(@max(this.toInt32(), 0)));
}
pub inline fn toU32(this: JSValue) u32 {
return @as(u32, @intCast(@min(@max(this.toInt64(), 0), std.math.maxInt(u32))));
}
/// This function supports:
/// - Array, DerivedArray & friends
/// - String, DerivedString & friends
/// - TypedArray
/// - Map (size)
/// - WeakMap (size)
/// - Set (size)
/// - WeakSet (size)
/// - ArrayBuffer (byteLength)
/// - anything with a .length property returning a number
///
/// If the "length" property does not exist, this function will return 0.
pub fn getLength(this: JSValue, globalThis: *JSGlobalObject) u64 {
const len = this.getLengthIfPropertyExistsInternal(globalThis);
if (len == std.math.floatMax(f64)) {
return 0;
}
return @as(u64, @intFromFloat(@max(@min(len, std.math.maxInt(i52)), 0)));
}
/// This function supports:
/// - Array, DerivedArray & friends
/// - String, DerivedString & friends
/// - TypedArray
/// - Map (size)
/// - WeakMap (size)
/// - Set (size)
/// - WeakSet (size)
/// - ArrayBuffer (byteLength)
/// - anything with a .length property returning a number
///
/// If the "length" property does not exist, this function will return null.
pub fn tryGetLength(this: JSValue, globalThis: *JSGlobalObject) ?f64 {
const len = this.getLengthIfPropertyExistsInternal(globalThis);
if (len == std.math.floatMax(f64)) {
return null;
}
return @as(u64, @intFromFloat(@max(@min(len, std.math.maxInt(i52)), 0)));
}
/// Do not use this directly!
///
/// If the property does not exist, this function will return max(f64) instead of 0.
pub fn getLengthIfPropertyExistsInternal(this: JSValue, globalThis: *JSGlobalObject) f64 {
return cppFn("getLengthIfPropertyExistsInternal", .{
this,
globalThis,
});
}
pub fn isAggregateError(this: JSValue, globalObject: *JSGlobalObject) bool {
return cppFn("isAggregateError", .{ this, globalObject });
}
pub fn forEach(
this: JSValue,
globalObject: *JSGlobalObject,
ctx: ?*anyopaque,
callback: *const fn (vm: *VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void,
) void {
return cppFn("forEach", .{ this, globalObject, ctx, callback });
}
pub fn isIterable(this: JSValue, globalObject: *JSGlobalObject) bool {
return cppFn("isIterable", .{
this,
globalObject,
});
}
pub fn parseJSON(this: JSValue, globalObject: *JSGlobalObject) JSValue {
return cppFn("parseJSON", .{
this,
globalObject,
});
}
pub fn stringIncludes(this: JSValue, globalObject: *JSGlobalObject, other: JSValue) bool {
return cppFn("stringIncludes", .{ this, globalObject, other });
}
pub inline fn asRef(this: JSValue) C_API.JSValueRef {
return @as(C_API.JSValueRef, @ptrFromInt(@as(usize, @bitCast(@intFromEnum(this)))));
}
pub inline fn c(this: C_API.JSValueRef) JSValue {
return @as(JSValue, @enumFromInt(@as(JSValue.Type, @bitCast(@intFromPtr(this)))));
}
pub inline fn fromRef(this: C_API.JSValueRef) JSValue {
return @as(JSValue, @enumFromInt(@as(JSValue.Type, @bitCast(@intFromPtr(this)))));
}
pub inline fn asObjectRef(this: JSValue) C_API.JSObjectRef {
return @as(C_API.JSObjectRef, @ptrCast(this.asVoid()));
}
/// When the GC sees a JSValue referenced in the stack
/// It knows not to free it
/// This mimicks the implementation in JavaScriptCore's C++
pub inline fn ensureStillAlive(this: JSValue) void {
if (this.isEmpty() or this.isNumber() or this.isBoolean() or this.isUndefinedOrNull()) return;
std.mem.doNotOptimizeAway(@as(C_API.JSObjectRef, @ptrCast(this.asVoid())));
}
pub inline fn asNullableVoid(this: JSValue) ?*anyopaque {
return @as(?*anyopaque, @ptrFromInt(@as(usize, @bitCast(@intFromEnum(this)))));
}
pub inline fn asVoid(this: JSValue) *anyopaque {
if (comptime bun.Environment.allow_assert) {
if (@intFromEnum(this) == 0) {
@panic("JSValue is null");
}
}
return this.asNullableVoid().?;
}
pub const Extern = [_][]const u8{
"_then",
"asArrayBuffer_",
"asBigIntCompare",
"asCell",
"asInternalPromise",
"asNumber",
"asObject",
"asPromise",
"asString",
"coerceToDouble",
"coerceToInt32",
"coerceToInt64",
"createEmptyArray",
"createEmptyObject",
"createInternalPromise",
"createObject2",
"createRangeError",
"createRopeString",
"createStringArray",
"createTypeError",
"createUninitializedUint8Array",
"deepEquals",
"eqlCell",
"eqlValue",
"fastGetDirect_",
"fastGet_",
"forEach",
"forEachProperty",
"forEachPropertyOrdered",
"fromEntries",
"fromInt64NoTruncate",
"fromUInt64NoTruncate",
"getClassName",
"getDirect",
"getErrorsProperty",
"getIfExists",
"getIfPropertyExistsFromPath",
"getIfPropertyExistsImpl",
"getLengthIfPropertyExistsInternal",
"getNameProperty",
"getPropertyByPropertyName",
"getPropertyNames",
"getPrototype",
"getStaticProperty",
"getSymbolDescription",
"getUnixTimestamp",
"hasProperty",
"isAggregateError",
"isAnyError",
"isAnyInt",
"isBigInt",
"isBigInt32",
"isBoolean",
"isCallable",
"isClass",
"isCustomGetterSetter",
"isError",
"isException",
"isGetterSetter",
"isHeapBigInt",
"isInt32",
"isInt32AsAnyInt",
"isIterable",
"isNumber",
"isObject",
"isPrimitive",
"isSameValue",
"isSymbol",
"isTerminationException",
"isUInt32AsAnyInt",
"jsBoolean",
"jsDoubleNumber",
"jsNull",
"jsNumberFromChar",
"jsNumberFromDouble",
"jsNumberFromInt64",
"jsNumberFromU16",
"jsTDZValue",
"jsType",
"jsUndefined",
"jsonStringify",
"kind_",
"makeWithNameAndPrototype",
"parseJSON",
"put",
"putDirect",
"putIndex",
"push",
"putRecord",
"strictDeepEquals",
"symbolFor",
"symbolKeyFor",
"toBoolean",
"toBooleanSlow",
"toError_",
"toInt32",
"toInt64",
"toObject",
"toPropertyKeyValue",
"toString",
"toStringOrNull",
"toUInt64NoTruncate",
"toWTFString",
"toZigException",
"toZigString",
"toMatch",
"isConstructor",
"isInstanceOf",
"stringIncludes",
"deepMatch",
"jestDeepEquals",
"jestStrictDeepEquals",
"jestDeepMatch",
};
// For any callback JSValue created in JS that you will not call *immediatly*, you must wrap it
// in an AsyncContextFrame with this function. This allows AsyncLocalStorage to work by
// snapshotting it's state and restoring it when called.
// - If there is no current context, this returns the callback as-is.
// - It is safe to run .call() on the resulting JSValue. This includes automatic unwrapping.
// - Do not pass the callback as-is to JS; The wrapped object is NOT a function.
// - If passed to C++, call it with AsyncContextFrame::call() instead of JSC::call()
pub inline fn withAsyncContextIfNeeded(this: JSValue, global: *JSGlobalObject) JSValue {
JSC.markBinding(@src());
return AsyncContextFrame__withAsyncContextIfNeeded(global, this);
}
};
extern "c" fn AsyncContextFrame__withAsyncContextIfNeeded(global: *JSGlobalObject, callback: JSValue) JSValue;
extern "c" fn Microtask__run(*Microtask, *JSGlobalObject) void;
extern "c" fn Microtask__run_default(*MicrotaskForDefaultGlobalObject, *JSGlobalObject) void;
pub const Microtask = opaque {
pub const name = "Zig::JSMicrotaskCallback";
pub const namespace = "Zig";
pub fn run(this: *Microtask, global_object: *JSGlobalObject) void {
if (comptime is_bindgen) {
return;
}
return Microtask__run(this, global_object);
}
};
pub const MicrotaskForDefaultGlobalObject = opaque {
pub fn run(this: *MicrotaskForDefaultGlobalObject, global_object: *JSGlobalObject) void {
if (comptime is_bindgen) {
return;
}
return Microtask__run_default(this, global_object);
}
};
pub const Exception = extern struct {
pub const shim = Shimmer("JSC", "Exception", @This());
bytes: shim.Bytes,
pub const Type = JSObject;
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/Exception.h";
pub const name = "JSC::Exception";
pub const namespace = "JSC";
pub const StackCaptureAction = enum(u8) {
CaptureStack = 0,
DoNotCaptureStack = 1,
};
pub fn create(globalObject: *JSGlobalObject, object: *JSObject, stack_capture: StackCaptureAction) *Exception {
return cppFn(
"create",
.{ globalObject, object, @intFromEnum(stack_capture) },
);
}
pub fn value(this: *Exception) JSValue {
return cppFn(
"value",
.{this},
);
}
pub fn getStackTrace(this: *Exception, trace: *ZigStackTrace) void {
return cppFn(
"getStackTrace",
.{ this, trace },
);
}
pub const Extern = [_][]const u8{ "create", "value", "getStackTrace" };
};
pub const VM = extern struct {
pub const shim = Shimmer("JSC", "VM", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/VM.h";
pub const name = "JSC::VM";
pub const namespace = "JSC";
pub const HeapType = enum(u8) {
SmallHeap = 0,
LargeHeap = 1,
};
pub fn create(heap_type: HeapType) *VM {
return cppFn("create", .{@intFromEnum(heap_type)});
}
pub fn deinit(vm: *VM, global_object: *JSGlobalObject) void {
return cppFn("deinit", .{ vm, global_object });
}
pub fn isJITEnabled() bool {
return cppFn("isJITEnabled", .{});
}
pub fn holdAPILock(this: *VM, ctx: ?*anyopaque, callback: *const fn (ctx: ?*anyopaque) callconv(.C) void) void {
cppFn("holdAPILock", .{ this, ctx, callback });
}
pub fn deferGC(this: *VM, ctx: ?*anyopaque, callback: *const fn (ctx: ?*anyopaque) callconv(.C) void) void {
cppFn("deferGC", .{ this, ctx, callback });
}
pub fn deleteAllCode(
vm: *VM,
global_object: *JSGlobalObject,
) void {
return cppFn("deleteAllCode", .{ vm, global_object });
}
pub fn whenIdle(
vm: *VM,
callback: *const fn (...) callconv(.C) void,
) void {
return cppFn("whenIdle", .{ vm, callback });
}
pub fn shrinkFootprint(
vm: *VM,
) void {
return cppFn("shrinkFootprint", .{
vm,
});
}
pub fn runGC(vm: *VM, sync: bool) JSValue {
return cppFn("runGC", .{
vm,
sync,
});
}
pub fn heapSize(vm: *VM) usize {
return cppFn("heapSize", .{
vm,
});
}
pub fn collectAsync(vm: *VM) void {
return cppFn("collectAsync", .{
vm,
});
}
pub fn setExecutionForbidden(vm: *VM, forbidden: bool) void {
cppFn("setExecutionForbidden", .{ vm, forbidden });
}
pub fn setExecutionTimeLimit(vm: *VM, timeout: f64) void {
return cppFn("setExecutionTimeLimit", .{ vm, timeout });
}
pub fn clearExecutionTimeLimit(vm: *VM) void {
return cppFn("clearExecutionTimeLimit", .{vm});
}
pub fn executionForbidden(vm: *VM) bool {
return cppFn("executionForbidden", .{
vm,
});
}
pub fn isEntered(vm: *VM) bool {
return cppFn("isEntered", .{
vm,
});
}
pub fn throwError(vm: *VM, global_object: *JSGlobalObject, value: JSValue) void {
return cppFn("throwError", .{
vm,
global_object,
value,
});
}
pub fn releaseWeakRefs(vm: *VM) void {
return cppFn("releaseWeakRefs", .{vm});
}
pub fn drainMicrotasks(
vm: *VM,
) void {
return cppFn("drainMicrotasks", .{
vm,
});
}
pub fn doWork(
vm: *VM,
) void {
return cppFn("doWork", .{
vm,
});
}
pub fn externalMemorySize(vm: *VM) usize {
return cppFn("externalMemorySize", .{vm});
}
/// `RESOURCE_USAGE` build option in JavaScriptCore is required for this function
/// This is faster than checking the heap size
pub fn blockBytesAllocated(vm: *VM) usize {
return cppFn("blockBytesAllocated", .{vm});
}
pub const Extern = [_][]const u8{ "collectAsync", "externalMemorySize", "blockBytesAllocated", "heapSize", "releaseWeakRefs", "throwError", "doWork", "deferGC", "holdAPILock", "runGC", "generateHeapSnapshot", "isJITEnabled", "deleteAllCode", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint", "setExecutionTimeLimit", "clearExecutionTimeLimit" };
};
pub const ThrowScope = extern struct {
pub const shim = Shimmer("JSC", "ThrowScope", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/ThrowScope.h";
pub const name = "JSC::ThrowScope";
pub const namespace = "JSC";
pub fn declare(
vm: *VM,
_: [*]u8,
file: [*]u8,
line: usize,
) ThrowScope {
return cppFn("declare", .{ vm, file, line });
}
pub fn release(this: *ThrowScope) void {
return cppFn("release", .{this});
}
pub fn exception(this: *ThrowScope) ?*Exception {
return cppFn("exception", .{this});
}
pub fn clearException(this: *ThrowScope) void {
return cppFn("clearException", .{this});
}
pub const Extern = [_][]const u8{
"declare",
"release",
"exception",
"clearException",
};
};
pub const CatchScope = extern struct {
pub const shim = Shimmer("JSC", "CatchScope", @This());
bytes: shim.Bytes,
const cppFn = shim.cppFn;
pub const include = "JavaScriptCore/CatchScope.h";
pub const name = "JSC::CatchScope";
pub const namespace = "JSC";
pub fn declare(
vm: *VM,
function_name: [*]u8,
file: [*]u8,
line: usize,
) CatchScope {
return cppFn("declare", .{ vm, function_name, file, line });
}
pub fn exception(this: *CatchScope) ?*Exception {
return cppFn("exception", .{this});
}
pub fn clearException(this: *CatchScope) void {
return cppFn("clearException", .{this});
}
pub const Extern = [_][]const u8{
"declare",
"exception",
"clearException",
};
};
pub const CallFrame = opaque {
/// The value is generated in `make sizegen`
/// The value is 6.
/// On ARM64_32, the value is something else but it really doesn't matter for our case
/// However, I don't want this to subtly break amidst future upgrades to JavaScriptCore
const alignment = Sizes.Bun_CallFrame__align;
pub const name = "JSC::CallFrame";
pub fn argumentsPtr(self: *const CallFrame) [*]const JSC.JSValue {
return @as([*]align(alignment) const JSC.JSValue, @ptrCast(@alignCast(self))) + Sizes.Bun_CallFrame__firstArgument;
}
pub fn callee(self: *const CallFrame) JSC.JSValue {
return (@as([*]align(alignment) const JSC.JSValue, @ptrCast(@alignCast(self))) + Sizes.Bun_CallFrame__callee)[0];
}
fn Arguments(comptime max: usize) type {
return struct {
ptr: [max]JSC.JSValue,
len: usize,
pub inline fn init(comptime i: usize, ptr: [*]const JSC.JSValue) @This() {
var args: [max]JSC.JSValue = std.mem.zeroes([max]JSC.JSValue);
args[0..comptime i].* = ptr[0..i].*;
return @This(){
.ptr = args,
.len = i,
};
}
pub inline fn slice(self: @This()) []const JSValue {
return self.ptr[0..self.len];
}
};
}
pub fn arguments(self: *const CallFrame, comptime max: usize) Arguments(max) {
const len = self.argumentsCount();
var ptr = self.argumentsPtr();
return switch (@as(u4, @min(len, max))) {
0 => .{ .ptr = undefined, .len = 0 },
4 => Arguments(max).init(comptime @min(4, max), ptr),
2 => Arguments(max).init(comptime @min(2, max), ptr),
6 => Arguments(max).init(comptime @min(6, max), ptr),
3 => Arguments(max).init(comptime @min(3, max), ptr),
8 => Arguments(max).init(comptime @min(8, max), ptr),
5 => Arguments(max).init(comptime @min(5, max), ptr),
1 => Arguments(max).init(comptime @min(1, max), ptr),
7 => Arguments(max).init(comptime @min(7, max), ptr),
else => unreachable,
};
}
pub fn argument(self: *const CallFrame, comptime i: comptime_int) JSC.JSValue {
return self.argumentsPtr()[i];
}
pub fn this(self: *const CallFrame) JSC.JSValue {
return (@as([*]align(alignment) const JSC.JSValue, @ptrCast(@alignCast(self))) + Sizes.Bun_CallFrame__thisArgument)[0];
}
pub fn argumentsCount(self: *const CallFrame) usize {
return @as(usize, @intCast((@as([*]align(alignment) const JSC.JSValue, @ptrCast(@alignCast(self))) + Sizes.Bun_CallFrame__argumentCountIncludingThis)[0].asInt32() - 1));
}
};
// pub const WellKnownSymbols = extern struct {
// pub const shim = Shimmer("JSC", "CommonIdentifiers", @This());
//
//
// pub const include = "JavaScriptCore/CommonIdentifiers.h";
// pub const name = "JSC::CommonIdentifiers";
// pub const namespace = "JSC";
// pub var hasthis: *const Identifier = shim.cppConst(Identifier, "hasInstance");
// pub var isConcatSpreadable: Identifier = shim.cppConst(Identifier, "isConcatSpreadable");
// pub var asyncIterator: Identifier = shim.cppConst(Identifier, "asyncIterator");
// pub var iterator: Identifier = shim.cppConst(Identifier, "iterator");
// pub var match: Identifier = shim.cppConst(Identifier, "match");
// pub var matchAll: Identifier = shim.cppConst(Identifier, "matchAll");
// pub var replace: Identifier = shim.cppConst(Identifier, "replace");
// pub var search: Identifier = shim.cppConst(Identifier, "search");
// pub var species: Identifier = shim.cppConst(Identifier, "species");
// pub var split: Identifier = shim.cppConst(Identifier, "split");
// pub var toPrimitive: Identifier = shim.cppConst(Identifier, "toPrimitive");
// pub var toStringTag: Identifier = shim.cppConst(Identifier, "toStringTag");
// pub var unscopable: Identifier = shim.cppConst(Identifier, "unscopabl");
// };
pub const EncodedJSValue = extern union {
asInt64: i64,
ptr: ?*JSCell,
asBits: [8]u8,
asPtr: ?*anyopaque,
asDouble: f64,
};
pub const JSHostFunctionType = fn (*JSGlobalObject, *CallFrame) callconv(.C) JSValue;
pub const JSHostFunctionPtr = *const JSHostFunctionType;
const DeinitFunction = *const fn (ctx: *anyopaque, buffer: [*]u8, len: usize) callconv(.C) void;
pub const JSArray = struct {
pub fn from(globalThis: *JSGlobalObject, arguments: []const JSC.JSValue) JSValue {
return JSC.JSValue.c(JSC.C.JSObjectMakeArray(globalThis, arguments.len, @as(?[*]const JSC.C.JSObjectRef, @ptrCast(arguments.ptr)), null));
}
};
const private = struct {
pub extern fn Bun__CreateFFIFunctionWithDataValue(
*JSGlobalObject,
?*const ZigString,
argCount: u32,
function: *const anyopaque,
strong: bool,
data: *anyopaque,
) JSValue;
pub extern fn Bun__CreateFFIFunction(
globalObject: *JSGlobalObject,
symbolName: ?*const ZigString,
argCount: u32,
functionPointer: *const anyopaque,
strong: bool,
) *anyopaque;
pub extern fn Bun__CreateFFIFunctionValue(
globalObject: *JSGlobalObject,
symbolName: ?*const ZigString,
argCount: u32,
functionPointer: JSHostFunctionPtr,
strong: bool,
) JSValue;
pub extern fn Bun__untrackFFIFunction(
globalObject: *JSGlobalObject,
function: JSValue,
) bool;
pub extern fn Bun__FFIFunction_getDataPtr(JSValue) ?*anyopaque;
pub extern fn Bun__FFIFunction_setDataPtr(JSValue, ?*anyopaque) void;
};
pub fn NewFunctionPtr(globalObject: *JSGlobalObject, symbolName: ?*const ZigString, argCount: u32, comptime functionPointer: anytype, strong: bool) *anyopaque {
JSC.markBinding(@src());
return private.Bun__CreateFFIFunction(globalObject, symbolName, argCount, @as(*const anyopaque, @ptrCast(&functionPointer)), strong);
}
pub fn NewFunction(
globalObject: *JSGlobalObject,
symbolName: ?*const ZigString,
argCount: u32,
comptime functionPointer: JSHostFunctionType,
strong: bool,
) JSValue {
return NewRuntimeFunction(globalObject, symbolName, argCount, &functionPointer, strong);
}
pub fn NewRuntimeFunction(
globalObject: *JSGlobalObject,
symbolName: ?*const ZigString,
argCount: u32,
functionPointer: JSHostFunctionPtr,
strong: bool,
) JSValue {
JSC.markBinding(@src());
return private.Bun__CreateFFIFunctionValue(globalObject, symbolName, argCount, functionPointer, strong);
}
pub fn getFunctionData(function: JSValue) ?*anyopaque {
JSC.markBinding(@src());
return private.Bun__FFIFunction_getDataPtr(function);
}
pub fn setFunctionData(function: JSValue, value: ?*anyopaque) void {
JSC.markBinding(@src());
return private.Bun__FFIFunction_setDataPtr(function, value);
}
pub fn NewFunctionWithData(
globalObject: *JSGlobalObject,
symbolName: ?*const ZigString,
argCount: u32,
comptime functionPointer: anytype,
strong: bool,
data: *anyopaque,
) JSValue {
JSC.markBinding(@src());
return private.Bun__CreateFFIFunctionWithDataValue(
globalObject,
symbolName,
argCount,
@as(*const anyopaque, @ptrCast(&functionPointer)),
strong,
data,
);
}
pub fn untrackFunction(
globalObject: *JSGlobalObject,
value: JSValue,
) bool {
JSC.markBinding(@src());
return private.Bun__untrackFFIFunction(globalObject, value);
}
pub const URLSearchParams = opaque {
extern fn URLSearchParams__create(globalObject: *JSGlobalObject, *const ZigString) JSValue;
pub fn create(globalObject: *JSGlobalObject, init: ZigString) JSValue {
JSC.markBinding(@src());
return URLSearchParams__create(globalObject, &init);
}
extern fn URLSearchParams__fromJS(JSValue) ?*URLSearchParams;
pub fn fromJS(value: JSValue) ?*URLSearchParams {
JSC.markBinding(@src());
return URLSearchParams__fromJS(value);
}
extern fn URLSearchParams__toString(
self: *URLSearchParams,
ctx: *anyopaque,
callback: *const fn (ctx: *anyopaque, str: *const ZigString) void,
) void;
pub fn toString(
self: *URLSearchParams,
comptime Ctx: type,
ctx: *Ctx,
comptime callback: *const fn (ctx: *Ctx, str: ZigString) void,
) void {
JSC.markBinding(@src());
const Wrap = struct {
const cb_ = callback;
pub fn cb(c: *anyopaque, str: *const ZigString) void {
cb_(
bun.cast(*Ctx, c),
str.*,
);
}
};
URLSearchParams__toString(self, ctx, Wrap.cb);
}
};
pub const WTF = struct {
extern fn WTF__copyLCharsFromUCharSource(dest: [*]u8, source: *const anyopaque, len: usize) void;
extern fn WTF__toBase64URLStringValue(bytes: [*]const u8, length: usize, globalObject: *JSGlobalObject) JSValue;
extern fn WTF__parseDouble(bytes: [*]const u8, length: usize, counted: *usize) f64;
pub fn parseDouble(buf: []const u8) !f64 {
JSC.markBinding(@src());
if (buf.len == 0)
return error.InvalidCharacter;
var count: usize = 0;
const res = WTF__parseDouble(buf.ptr, buf.len, &count);
if (count == 0)
return error.InvalidCharacter;
return res;
}
/// This uses SSE2 instructions and/or ARM NEON to copy 16-bit characters efficiently
/// See wtf/Text/ASCIIFastPath.h for details
pub fn copyLCharsFromUCharSource(destination: [*]u8, comptime Source: type, source: Source) void {
JSC.markBinding(@src());
// This is any alignment
WTF__copyLCharsFromUCharSource(destination, source.ptr, source.len);
}
/// Encode a byte array to a URL-safe base64 string for use with JS
/// Memory is managed by JavaScriptCore instead of us
pub fn toBase64URLStringValue(bytes: []const u8, globalObject: *JSGlobalObject) JSValue {
JSC.markBinding(@src());
return WTF__toBase64URLStringValue(bytes.ptr, bytes.len, globalObject);
}
};
pub const Callback = struct {
// zig: Value,
};
pub fn Thenable(comptime name: []const u8, comptime Then: type, comptime onResolve: fn (*Then, globalThis: *JSGlobalObject, result: JSValue) void, comptime onReject: fn (*Then, globalThis: *JSGlobalObject, result: JSValue) void) type {
return struct {
pub fn resolve(
globalThis: [*c]JSGlobalObject,
callframe: ?*JSC.CallFrame,
) callconv(.C) void {
@setRuntimeSafety(false);
const args_list = callframe.?.arguments(8);
onResolve(@as(*Then, @ptrCast(@alignCast(args_list.ptr[args_list.len - 1].asEncoded().asPtr))), globalThis, args_list.ptr[0]);
}
pub fn reject(
globalThis: [*c]JSGlobalObject,
callframe: ?*JSC.CallFrame,
) callconv(.C) void {
@setRuntimeSafety(false);
const args_list = callframe.?.arguments(8);
onReject(@as(*Then, @ptrCast(@alignCast(args_list.ptr[args_list.len - 1].asEncoded().asPtr))), globalThis, args_list.ptr[0]);
}
pub fn then(ctx: *Then, this: JSValue, globalThis: *JSGlobalObject) void {
this._then(globalThis, ctx, resolve, reject);
}
comptime {
if (!JSC.is_bindgen) {
@export(resolve, name ++ "__resolve");
@export(reject, name ++ "__reject");
}
}
};
}
pub const JSPropertyIteratorOptions = struct {
skip_empty_name: bool,
include_value: bool,
};
pub fn JSPropertyIterator(comptime options: JSPropertyIteratorOptions) type {
return struct {
/// Position in the property list array
/// Update is deferred until the next iteration
i: u32 = 0,
iter_i: u32 = 0,
len: u32,
array_ref: JSC.C.JSPropertyNameArrayRef,
/// The `JSValue` of the current property.
///
/// Invokes undefined behavior if an iteration has not yet occurred and
/// zero-sized when `options.include_value` is not enabled.
value: if (options.include_value) JSC.JSValue else void,
/// Zero-sized when `options.include_value` is not enabled.
object: if (options.include_value) JSC.C.JSObjectRef else void,
/// Zero-sized when `options.include_value` is not enabled.
global: if (options.include_value) JSC.C.JSContextRef else void,
const Self = @This();
inline fn initInternal(global: JSC.C.JSContextRef, object: JSC.C.JSObjectRef) Self {
const array_ref = JSC.C.JSObjectCopyPropertyNames(global, object);
return .{
.array_ref = array_ref,
.len = @as(u32, @truncate(JSC.C.JSPropertyNameArrayGetCount(array_ref))),
.object = if (comptime options.include_value) object else .{},
.global = if (comptime options.include_value) global else .{},
.value = undefined,
};
}
/// Initializes the iterator. Make sure you `deinit()` it!
///
/// Not recommended for use when using the CString buffer mode as the
/// buffer must be manually initialized. Instead, see
/// `JSPropertyIterator.initCStringBuffer()`.
pub inline fn init(global: JSC.C.JSContextRef, object: JSC.C.JSObjectRef) Self {
return Self.initInternal(global, object);
}
/// Deinitializes the property name array and all of the string
/// references constructed by the copy.
pub inline fn deinit(self: *Self) void {
JSC.C.JSPropertyNameArrayRelease(self.array_ref);
}
pub fn hasLongNames(self: *Self) bool {
var i = self.i;
const len = self.len;
var estimated_length: usize = 0;
while (i < len) : (i += 1) {
estimated_length += JSC.C.JSStringGetLength(JSC.C.JSPropertyNameArrayGetNameAtIndex(self.array_ref, i));
if (estimated_length > 14) return true;
}
return false;
}
/// Finds the next property string and, if `options.include_value` is
/// enabled, updates the `iter.value` to respect the latest property's
/// value. Also note the behavior of the other options.
pub fn next(self: *Self) ?ZigString {
return nextMaybeFirstValue(self, .zero);
}
pub fn nextMaybeFirstValue(self: *Self, first_value: JSValue) ?ZigString {
if (self.iter_i >= self.len) {
self.i = self.iter_i;
return null;
}
self.i = self.iter_i;
var property_name_ref = JSC.C.JSPropertyNameArrayGetNameAtIndex(self.array_ref, self.iter_i);
self.iter_i += 1;
const len = JSC.C.JSStringGetLength(property_name_ref);
if (comptime options.skip_empty_name) {
if (len == 0) return self.next();
}
const prop = property_name_ref.toZigString();
if (comptime options.include_value) {
if (self.i == 0 and first_value != .zero) {
self.value = first_value;
} else {
self.value = JSC.JSValue.fromRef(JSC.C.JSObjectGetProperty(self.global, self.object, property_name_ref, null));
}
}
return prop;
}
};
}
// DOMCall Fields
pub const __DOMCall_ptr = @import("../api/bun.zig").FFI.Class.functionDefinitions.ptr;
pub const __DOMCall__reader_u8 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.u8;
pub const __DOMCall__reader_u16 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.u16;
pub const __DOMCall__reader_u32 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.u32;
pub const __DOMCall__reader_ptr = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.ptr;
pub const __DOMCall__reader_i8 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.i8;
pub const __DOMCall__reader_i16 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.i16;
pub const __DOMCall__reader_i32 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.i32;
pub const __DOMCall__reader_f32 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.f32;
pub const __DOMCall__reader_f64 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.f64;
pub const __DOMCall__reader_i64 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.i64;
pub const __DOMCall__reader_u64 = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.u64;
pub const __DOMCall__reader_intptr = @import("../api/bun.zig").FFI.Reader.Class.functionDefinitions.intptr;
pub const __Crypto_getRandomValues = @import("../webcore.zig").Crypto.Class.functionDefinitions.getRandomValues;
pub const __Crypto_randomUUID = @import("../webcore.zig").Crypto.Class.functionDefinitions.randomUUID;
pub const __Crypto_randomInt = @import("../webcore.zig").Crypto.Class.functionDefinitions.randomInt;
pub const __Crypto_timingSafeEqual = @import("../webcore.zig").Crypto.Class.functionDefinitions.timingSafeEqual;
pub const DOMCalls = .{
@import("../api/bun.zig").FFI,
@import("../api/bun.zig").FFI.Reader,
@import("../webcore.zig").Crypto,
};
extern "c" fn JSCInitialize(env: [*]const [*:0]u8, count: usize, cb: *const fn ([*]const u8, len: usize) callconv(.C) void) void;
pub fn initialize() void {
JSC.markBinding(@src());
JSCInitialize(
std.os.environ.ptr,
std.os.environ.len,
struct {
pub fn callback(name: [*]const u8, len: usize) callconv(.C) void {
Output.prettyErrorln(
\\<r><red>error<r><d>:<r> invalid JSC environment variable
\\
\\ <b>{s}<r>
\\
\\For a list of options, see this file:
\\
\\ https://github.com/oven-sh/webkit/blob/main/Source/JavaScriptCore/runtime/OptionsList.h
\\
\\Environment variables must be prefixed with "BUN_JSC_". This code runs before .env files are loaded, so those won't work here.
\\
\\Warning: options change between releases of Bun and WebKit without notice. This is not a stable API, you should not rely on it beyond debugging something, and it may be removed entirely in a future version of Bun.
,
.{name[0..len]},
);
bun.Global.exit(1);
}
}.callback,
);
}
|