aboutsummaryrefslogtreecommitdiff
path: root/public/js/cljcc-lib-wasm.js
blob: cf475fb3bbf3c6459e8acfc2a279c7510663f57a (plain)
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
'use strict';


/**
 * @suppress {checkVars,checkTypes,duplicate}
 * @nocollapse
*/
var GraalVM = {};
window.GraalVM = GraalVM;
(function() {(function() {(function() {

/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Represents a potential feature of the JS runtime.
 *
 * During construction, the detection callback is called to detect whether the runtime supports the feature.
 * The callback returns whether the feature was detected and may store some data
 * into the 'data' member for future use.
 */
class Feature {
    constructor(descr, detection_callback) {
        this.description = descr;
        this.data = {};
        this.detected = detection_callback(this.data);
    }
}

/**
 * Specialized feature to detect global variables.
 */
class GlobalVariableFeature extends Feature {
    constructor(descr, var_name) {
        super(descr, GlobalVariableFeature.detection_callback.bind(null, var_name));
    }

    /**
     * Function to detect a global variable.
     *
     * Uses the 'globalThis' object which should represent the global scope in
     * modern runtimes.
     */
    static detection_callback(var_name, data) {
        if (var_name in globalThis) {
            data.global = globalThis[var_name];
            return true;
        }

        return false;
    }

    /**
     * Returns the global detected by this feature.
     */
    get() {
        return this.data.global;
    }
}

/**
 * Specialized feature to detect the presence of Node.js modules.
 */
class RequireFeature extends Feature {
    constructor(descr, module_name) {
        super(descr, RequireFeature.detection_callback.bind(null, module_name));
    }

    /**
     * Function to detect a Node.js module.
     */
    static detection_callback(module_name, data) {
        if (typeof require != "function") {
            return false;
        }

        try {
            data.module = require(module_name);
            return true;
        } catch (e) {
            return false;
        }
    }

    /**
     * Returns the module detected by this feature.
     */
    get() {
        return this.data.module;
    }
}

/**
 * Collection of features needed for runtime functions.
 */
let features = {
    // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
    fetch: new GlobalVariableFeature("Presence of the Fetch API", "fetch"),

    // https://nodejs.org/api/fs.html#promises-api
    node_fs: new RequireFeature("Presence of Node.js fs promises module", "fs/promises"),

    // https://nodejs.org/api/https.html
    node_https: new RequireFeature("Presence of Node.js https module", "https"),

    // https://nodejs.org/api/process.html
    node_process: new RequireFeature("Presence of Node.js process module", "process"),

    /**
     * Technically, '__filename' is not a global variable, it is a variable in the module scope.
     * https://nodejs.org/api/globals.html#__filename
     */
    filename: new Feature("Presence of __filename global", (d) => {
        if (typeof __filename != "undefined") {
            d.filename = __filename;
            return true;
        }

        return false;
    }),

    // https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript
    currentScript: new Feature("Presence of document.currentScript global", (d) => {
        if (
            typeof document != "undefined" &&
            "currentScript" in document &&
            document.currentScript != null &&
            "src" in document.currentScript
        ) {
            d.currentScript = document.currentScript;
            return true;
        }

        return false;
    }),

    // https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/location
    location: new Feature("Presence of Web worker location", (d) => {
        if (typeof self != "undefined") {
            d.location = self.location;
            return true;
        }
        return false;
    }),
};


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
function charArrayToString(arr) {
    let res = [];

    const len = 512;

    for (let i = 0; i < arr.length; i += len) {
        res.push(String.fromCharCode(...arr.slice(i, i + len)));
    }
    return res.join("");
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
function llog(p) {
    if (p instanceof Error) {
        console.log(p);
    } else if (p instanceof Object) {
        console.log(p.toString());
    } else {
        console.log(p);
    }
}

/**
 * A writer emulating stdout and stderr using console.log and console.error
 *
 * Since those functions cannot print without newline, lines are buffered but
 * without a max buffer size.
 */
class ConsoleWriter {
    constructor(logger) {
        this.line = "";
        this.newline = "\n".charCodeAt(0);
        this.closed = false;
        this.logger = logger;
    }

    printChars(chars) {
        let index = chars.lastIndexOf(this.newline);

        if (index >= 0) {
            this.line += charArrayToString(chars.slice(0, index));
            this.writeLine();
            chars = chars.slice(index + 1);
        }

        this.line += charArrayToString(chars);
    }

    writeLine() {
        this.logger(this.line);
        this.line = "";
    }

    flush() {
        if (this.line.length > 0) {
            // In JS we cannot print without newline, so flushing will always produce one
            this.writeLine();
        }
    }

    close() {
        if (this.closed) {
            return;
        }
        this.closed = true;

        this.flush();
    }
}

var stdoutWriter = new ConsoleWriter(console.log);
var stderrWriter = new ConsoleWriter(console.error);


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Class that holds the configuration of the VM.
 */
class Config {
    constructor() {
        this.libraries = {};
        this.currentWorkingDirectory = "/root";
    }
}

/**
 * Class that holds the data required to start the VM.
 */
class Data {
    constructor(config) {
        /**
         * User-specified configuration object.
         *
         * @type Config
         */
        this.config = config;

        /**
         * Optionally holds a binary support file.
         */
        this.binaryImageHeap = null;

        /**
         * Maps the library names to prefetched content during VM bootup.
         * After the VM is initialized, the keys are retained, but values are set to null.
         */
        this.libraries = {};
    }
}

/**
 * Dummy object that exists only to avoid warnings in IDEs for the `$t[name]` expressions (used in JavaScript support files).
 */
const $t = {};

/**
 * For a given JavaScript class, returns an object that can lookup its properties.
 */
function cprops(cls) {
    return cls.prototype;
}

/**
 * Placeholder for lazy-value initializers.
 */
class LazyValueThunk {
    constructor(initializer) {
        this.initializer = initializer;
    }
}

/**
 * Creates a lazy property on the specified object.
 */
function lazy(obj, name, initializer) {
    let state = new LazyValueThunk(initializer);
    Object.defineProperty(obj, name, {
        configurable: false,
        enumerable: true,
        get: () => {
            if (state instanceof LazyValueThunk) {
                state = state.initializer();
            }
            return state;
        },
        set: () => {
            throw new Error("Property is not writable.");
        },
    });
}

/**
 * Placeholder for a method and its signature.
 */
class MethodMetadata {
    constructor(method, isStatic, returnHub, ...paramHubs) {
        this.method = method;
        this.isStatic = isStatic;
        this.returnHub = returnHub;
        this.paramHubs = paramHubs;
    }
}

/**
 * Create MethodMetadata object for an instance method.
 */
function mmeta(method, returnHub, ...paramHubs) {
    return new MethodMetadata(method, false, returnHub, ...paramHubs);
}

/**
 * Create MethodMetadata object for a static method.
 */
function smmeta(method, returnHub, ...paramHubs) {
    return new MethodMetadata(method, true, returnHub, ...paramHubs);
}

/**
 * Describes extra class metadata used by the runtime.
 */
class ClassMetadata {
    /**
     * Constructs the class metadata.
     *
     * @param ft Field table
     * @param singleAbstractMethod Method metadata for the single abstract method, when the class implements exactly one functional interface
     * @param methodTable Dictionary mapping each method name to the list of overloaded signatures
     */
    constructor(ft, singleAbstractMethod = undefined, methodTable = undefined) {
        this.ft = ft;
        this.singleAbstractMethod = singleAbstractMethod;
        this.methodTable = methodTable;
    }
}

/**
 * Class for the various runtime utilities.
 */
class Runtime {
    constructor() {
        this.isLittleEndian = false;
        /**
         * Dictionary of all initializer functions.
         */
        this.jsResourceInits = {};
        /**
         * The data object of the current VM, which contains the configuration settings,
         * optionally a binary-encoded image heap, and other resources.
         *
         * The initial data value is present in the enclosing scope.
         *
         * @type Data
         */
        this.data = null;
        /**
         * Map from full Java class names to corresponding Java hubs, for classes that are accessible outside of the image.
         */
        this.hubs = {};
        /**
         * The table of native functions that can be invoked via indirect calls.
         *
         * The index in this table represents the address of the function.
         * The zero-th entry is always set to null.
         */
        this.funtab = [null];
        /**
         * Map of internal symbols that are used during execution.
         */
        Object.defineProperty(this, "symbol", {
            writable: false,
            configurable: false,
            value: {
                /**
                 * Symbol used to symbolically get the to-JavaScript-native coercion object on the Java proxy.
                 *
                 * This symbol is available as a property on Java proxies, and will return a special object
                 * that can coerce the Java proxy to various native JavaScript values.
                 *
                 * See the ProxyHandler class for more details.
                 */
                javaScriptCoerceAs: Symbol("__javascript_coerce_as__"),

                /**
                 * Key used by Web Image to store the corresponding JS native value as a property of JSValue objects.
                 *
                 * Used by the JS annotation.
                 *
                 * Use conversion.setJavaScriptNative and conversion.extractJavaScriptNative to access that property
                 * instead of using this symbol directly.
                 */
                javaScriptNative: Symbol("__javascript_native__"),

                /**
                 * Key used to store a property value (inside a JavaScript object) that contains the Java-native object.
                 *
                 * Used by the JS annotation.
                 */
                javaNative: Symbol("__java_native__"),

                /**
                 * Key used to store the runtime-generated proxy handler inside the Java class.
                 *
                 * The handler is created lazily the first time that the corresponding class is added
                 *
                 * Use getOrCreateProxyHandler to retrieve the proxy handler instead of using this symbol directly.
                 */
                javaProxyHandler: Symbol("__java_proxy_handler__"),

                /**
                 * Key used to store the extra class metadata when emitting Java classes.
                 */
                classMeta: Symbol("__class_metadata__"),

                /**
                 * Key for the hub-object property that points to the corresponding generated JavaScript class.
                 */
                jsClass: Symbol("__js_class__"),

                /**
                 * Key for the property on primitive hubs, which points to the corresponding boxed hub.
                 */
                boxedHub: Symbol("__boxed_hub__"),

                /**
                 * Key for the property on primitive hubs, which holds the boxing function.
                 */
                box: Symbol("__box__"),

                /**
                 * Key for the property on primitive hubs, which holds the unboxing function.
                 */
                unbox: Symbol("__unbox__"),

                /**
                 * Key for the constructor-overload list that is stored in the class metadata.
                 */
                ctor: Symbol("__ctor__"),

                /**
                 * Internal value passed to JavaScript mirror-class constructors
                 * to denote that the mirrored class was instantiated from Java.
                 *
                 * This is used when a JSObject subclass gets constructed from Java.
                 */
                skipJavaCtor: Symbol("__skip_java_ctor__"),

                /**
                 * Symbol for the Java toString method.
                 */
                toString: Symbol("__toString__"),
            },
        });

        // Conversion-related functions and values.
        // The following values are set or used by the jsconversion module.

        /**
         * The holder of JavaScript mirror class for JSObject subclasses.
         */
        this.mirrors = {};
        /**
         * Reference to the hub of the java.lang.Class class.
         */
        this.classHub = null;
        /**
         * Function that retrieves the hub of the specified Java object.
         */
        this.hubOf = null;
        /**
         * Function that checks if the first argument hub is the supertype or the same as the second argument hub.
         */
        this.isSupertype = null;
        /**
         * Mapping from JavaScript classes that were imported to the list of internal Java classes
         * under which the corresponding JavaScript class was imported.
         * See JS.Import annotation.
         */
        this.importMap = new Map();
    }

    /**
     * Use the build-time endianness at run-time.
     *
     * Unsafe operations that write values to byte arrays at build-time assumes the
     * endianness of the build machine. Therefore, unsafe read and write operations
     * at run-time need to assume the same endianness.
     */
    setEndianness(isLittleEndian) {
        runtime.isLittleEndian = isLittleEndian;
    }

    /**
     * Ensures that there is a Set entry for the given JavaScript class, and returns it.
     */
    ensureFacadeSetFor(cls) {
        let facades = this.importMap.get(cls);
        if (facades === undefined) {
            facades = new Set();
            this.importMap.set(cls, facades);
        }
        return facades;
    }

    /**
     * Finds the set of Java facade classes for the given JavaScript class, or an empty set if there are none.
     */
    findFacadesFor(cls) {
        let facades = this.importMap.get(cls);
        if (facades === undefined) {
            facades = new Set();
        }
        return facades;
    }

    _ensurePackage(container, name) {
        const elements = name === "" ? [] : name.split(".");
        let current = container;
        for (let i = 0; i < elements.length; i++) {
            const element = elements[i];
            current = element in current ? current[element] : (current[element] = {});
        }
        return current;
    }

    /**
     * Get or create the specified exported JavaScript mirror-class export package on the VM object.
     *
     * @param name Full Java name of the package
     */
    ensureExportPackage(name) {
        return this._ensurePackage(vm.exports, name);
    }

    /**
     * Get or create the specified exported JavaScript mirror-class package on the Runtime object.
     *
     * @param name Full Java name of the package
     */
    ensureVmPackage(name) {
        return this._ensurePackage(runtime.mirrors, name);
    }

    /**
     * Get an existing exported JavaScript mirror class on the Runtime object.
     *
     * @param className Full Java name of the class
     */
    vmClass(className) {
        const elements = className.split(".");
        let current = runtime.mirrors;
        for (let i = 0; i < elements.length; i++) {
            const element = elements[i];
            if (element in current) {
                current = current[element];
            } else {
                return null;
            }
        }
        return current;
    }

    /**
     * Returns the array with all the prefetched library names.
     */
    prefetchedLibraryNames() {
        const names = [];
        for (const name in this.data.libraries) {
            names.push(name);
        }
        return names;
    }

    /**
     * Adds a function to the function table.
     *
     * @param f The function to add
     * @returns {number} The address of the newly added function
     */
    addToFuntab(f) {
        this.funtab.push(f);
        return runtime.funtab.length - 1;
    }

    /**
     * Fetches binary data from the given url.
     *
     * @param url
     * @returns {!Promise<!ArrayBuffer>}
     */
    fetchData(url) {
        return Promise.reject(new Error("fetchData is not supported"));
    }

    /**
     * Fetches UTF8 text from the given url.
     *
     * @param url
     * @returns {!Promise<!String>}
     */
    fetchText(url) {
        return Promise.reject(new Error("fetchText is not supported"));
    }

    /**
     * Sets the exit code for the VM.
     */
    setExitCode(c) {
        vm.exitCode = c;
    }

    /**
     * Returns the absolute path of the JS file WebImage is running in.
     *
     * Depending on the runtime, this may be a URL or an absolute filesystem path.
     * @returns {!String}
     */
    getCurrentFile() {
        throw new Error("getCurrentFile is not supported");
    }
}

/**
 * Instance of the internal runtime state of the VM.
 */
const runtime = new Runtime();

/**
 * VM state that is exposed, and which represents the VM API accessible to external users.
 */
class VM {
    constructor() {
        this.exitCode = 0;
        this.exports = {};
        this.symbol = {};
        /**
         * The to-JavaScript-native coercion symbol in the external API.
         */
        Object.defineProperty(this.symbol, "as", {
            configurable: false,
            enumerable: true,
            writable: false,
            value: runtime.symbol.javaScriptCoerceAs,
        });
        /**
         * The symbol for the Java toString method in the external API.
         */
        Object.defineProperty(this.symbol, "toString", {
            configurable: false,
            enumerable: true,
            writable: false,
            value: runtime.symbol.toString,
        });
    }

    /**
     * Coerce the specified JavaScript value to the specified Java type.
     *
     * For precise summary of the coercion rules, please see the JS annotation JavaDoc.
     *
     * The implementation for this function is injected later.
     *
     * @param javaScriptValue The JavaScript value to coerce
     * @param type The name of the Java class to coerce to, or a Java Proxy representing the target class.
     * @returns {*} The closest corresponding Java Proxy value
     */
    as(javaScriptValue, type) {
        throw new Error("VM.as is not supported in this backend or it was called too early");
    }
}

/**
 * Instance of the class that represents the public VM API.
 */
const vm = new VM();

if (features.node_fs.detected && features.node_https.detected) {
    runtime.fetchText = (url) => {
        if (url.startsWith("http://") || url.startsWith("https://")) {
            return new Promise((fulfill, reject) => {
                let content = [];
                features.node_https
                    .get()
                    .get(url, (r) => {
                        r.on("data", (data) => {
                            content.push(data);
                        });
                        r.on("end", () => {
                            fulfill(content.join(""));
                        });
                    })
                    .on("error", (e) => {
                        reject(e);
                    });
            });
        } else {
            return features.node_fs.get().readFile(url, "utf8");
        }
    };
    runtime.fetchData = (url) => {
        return features.node_fs
            .get()
            .readFile(url)
            .then((d) => d.buffer);
    };
} else if (features.fetch.detected) {
    runtime.fetchText = (url) =>
        features.fetch
            .get()(url)
            .then((r) => r.text());
    runtime.fetchData = (url) =>
        features.fetch
            .get()(url)
            .then((response) => {
                if (!response.ok) {
                    throw new Error(`Failed to load data at '${url}': ${response.status} ${response.statusText}`);
                }
                return response.arrayBuffer();
            });
}

if (features.node_process.detected) {
    // Extend the setExitCode function to also set the exit code of the runtime.
    let oldFun = runtime.setExitCode;
    runtime.setExitCode = (exitCode) => {
        oldFun(exitCode);
        features.node_process.get().exitCode = exitCode;
    };
}

if (features.filename.detected) {
    runtime.getCurrentFile = () => features.filename.data.filename;
} else if (features.currentScript.detected) {
    runtime.getCurrentFile = () => features.currentScript.data.currentScript.src;
} else if (features.location.detected) {
    runtime.getCurrentFile = () => features.location.data.location.href;
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Imports object passed to the WASM module during instantiation.
 *
 * @see WasmImports
 */
const wasmImports = {};

/**
 * Imports for operations that cannot be performed (or be easily emulated) in WASM.
 */
wasmImports.compat = {
    f64rem: (x, y) => x % y,
    f64log: Math.log,
    f64log10: Math.log10,
    f64sin: Math.sin,
    f64cos: Math.cos,
    f64tan: Math.tan,
    f64tanh: Math.tanh,
    f64exp: Math.exp,
    f64pow: Math.pow,
    f32rem: (x, y) => x % y,
};

/**
 * Imports relating to I/O.
 */
wasmImports.io = {};

/**
 * Loads and instantiates the appropriate WebAssembly module.
 *
 * The module path is given by config.wasm_path, if specified, otherwise it is loaded relative to the current script file.
 */
async function wasmInstantiate(config, args) {
    // const wasmPath = config.wasm_path || runtime.getCurrentFile() + ".wasm";
    const wasmPath = "js/cljcc-lib-wasm.js.wasm";
    const file = await runtime.fetchData(wasmPath);
    const result = await WebAssembly.instantiate(file, wasmImports);
    return {
        instance: result.instance,
        memory: result.instance.exports.memory,
    };
}

/**
 * Runs the main entry point of the given WebAssembly module.
 */
function wasmRun(args) {
    try {
        doRun(args);
    } catch (e) {
        console.log("Uncaught internal error:");
        console.log(e);
        runtime.setExitCode(1);
    }
}

function getExports() {
    return runtime.data.wasm.instance.exports;
}

function getExport(name) {
    return getExports()[name];
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Constructs Java string from JavaScript string.
 */
function toJavaString(jsStr) {
    const length = jsStr.length;
    const charArray = getExport("array.char.create")(length);

    for (let i = 0; i < length; i++) {
        getExport("array.char.write")(charArray, i, jsStr.charCodeAt(i));
    }

    return getExport("string.fromchars")(charArray);
}

/**
 * Constructs a Java string array (String[]) from a JavaScript array of
 * JavaScript strings.
 */
function toJavaStringArray(jsStrings) {
    const length = jsStrings.length;
    const stringArray = getExport("array.string.create")(length);

    for (let i = 0; i < length; i++) {
        getExport("array.object.write")(stringArray, i, toJavaString(jsStrings[i]));
    }

    return stringArray;
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Checks if the given string is an array index.
 *
 * Proxied accesses always get a string property (even for indexed accesses) so
 * we need to check if the property access is an indexed access.
 *
 * A property is an index if the numeric index it is refering to has the same
 * string representation as the original property.
 * E.g the string '010' is a property while '10' is an index.
 */
function isArrayIndex(property) {
    try {
        return Number(property).toString() === property;
    } catch (e) {
        // Catch clause because not all property keys (e.g. symbols) can be
        // converted to a number.
        return false;
    }
}

/**
 * Proxy handler that proxies all array element and length accesses to a Wasm
 * array and everything else to the underlying array.
 *
 * See `proxyArray` function for more information.
 */
class ArrayProxyHandler {
    /**
     * Reference to the Wasm-world object.
     *
     * In this case, this will be a Wasm struct containing a Wasm array.
     */
    #wasmObject;

    /**
     * Immutable length of the array, determined during construction.
     */
    #length;

    /**
     * A callable (usually an exported function) that accepts the Wasm object
     * and an index and returns the element at that location.
     */
    #reader;

    constructor(wasmObject, reader) {
        this.#wasmObject = wasmObject;
        this.#length = getExport("array.length")(wasmObject);
        this.#reader = reader;
    }

    #isInBounds(idx) {
        return idx >= 0 && idx < this.#length;
    }

    #getElement(idx) {
        /*
         * We need an additional bounds check here because Wasm will trap,
         * while JS expects an undefined value.
         */
        if (this.#isInBounds(idx)) {
            return this.#reader(this.#wasmObject, idx);
        } else {
            return undefined;
        }
    }

    defineProperty() {
        throw new TypeError("This array is immutable. Attempted to call defineProperty");
    }

    deleteProperty() {
        throw new TypeError("This array is immutable. Attempted to call deleteProperty");
    }

    /**
     * Indexed accesses and the `length` property are serviced from the Wasm
     * object, everything else goes to the underlying object.
     */
    get(target, property, receiver) {
        if (isArrayIndex(property)) {
            return this.#getElement(property);
        } else if (property == "length") {
            return this.#length;
        } else {
            return Reflect.get(target, property, receiver);
        }
    }

    getOwnPropertyDescriptor(target, property) {
        if (isArrayIndex(property)) {
            return {
                value: this.#getElement(property),
                writable: false,
                enumerable: true,
                configurable: false,
            };
        } else {
            return Reflect.getOwnPropertyDescriptor(target, property);
        }
    }

    has(target, property) {
        if (isArrayIndex(property)) {
            return this.#isInBounds(Number(property));
        } else {
            return Reflect.has(target, property);
        }
    }

    isExtensible() {
        return false;
    }

    /**
     * Returns the array's own enumerable string-keyed property names.
     *
     * For arrays this is simply an array of all indices in string form.
     */
    ownKeys() {
        return Object.keys(Array.from({ length: this.#length }, (x, i) => i));
    }

    preventExtensions() {
        // Do nothing this object is already not extensible
    }

    set() {
        throw new TypeError("This array is immutable. Attempted to call set");
    }

    setPrototypeOf() {
        throw new TypeError("This array is immutable. Attempted to call setPrototypeOf");
    }
}

/**
 * Creates a read-only view on a Wasm array that looks like a JavaScript Array.
 *
 * The proxy is backed by an Array instance (albeit an empty one) and any
 * accesses except for `length` and indexed accesses (see `isArrayIndex`) are
 * proxied to the original object.
 * Because the `Array.prototype` methods are all generic and only access
 * `length` and the indices, this works. For example if `indexOf` is called on
 * the proxy, `Array.prototype.indexOf` is called with the proxy bound to
 * `this`, thus the `indexOf` implementation goes through the proxy when
 * accessing elements or determining the array length.
 */
function proxyArray(a, reader) {
    return new Proxy(new Array(), new ArrayProxyHandler(a, reader));
}

function proxyCharArray(a) {
    return proxyArray(a, getExport("array.char.read"));
}

wasmImports.convert = {};
wasmImports.convert.proxyCharArray = proxyCharArray;


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

function doRun(args) {
    getExport("main")(toJavaStringArray(args));
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
const STACK_TRACE_MARKER = "NATIVE-IMAGE-MARKER";

/**
 * Create JavaScript Error object, which is used to fill in the Throwable.backtrace object.
 */
function genBacktrace() {
    return new Error(STACK_TRACE_MARKER);
}

/**
 * Extract a Java string from the given backtrace object, which is supposed to be a JavaScript Error object.
 */
function formatStackTrace(backtrace) {
    let trace;

    if (backtrace.stack) {
        let lines = backtrace.stack.split("\n");

        /*
         * Since Error.prototype.stack is non-standard, different runtimes set
         * it differently.
         * We try to remove the preamble that contains the error name and
         * message to just get the stack trace.
         */
        if (lines.length > 0 && lines[0].includes(STACK_TRACE_MARKER)) {
            lines = lines.splice(1);
        }

        trace = lines.join("\n");
    } else {
        trace = "This JavaScript runtime does not expose stack trace information.";
    }

    return toJavaString(trace);
}

function gen_call_stack() {
    return formatStackTrace(genBacktrace());
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Provides the current working directory from the Config instance to Java code.
 */
function getCurrentWorkingDirectory() {
    return toJavaString(runtime.data.config.currentWorkingDirectory);
}
runtime.setEndianness(1);
wasmImports.interop = {
	'Date.now' : (...args) => Date.now(...args),
	'formatStackTrace' : (...args) => formatStackTrace(...args),
	'genBacktrace' : (...args) => genBacktrace(...args),
	'getCurrentWorkingDirectory' : (...args) => getCurrentWorkingDirectory(...args),
	'llog' : (...args) => llog(...args),
	'performance.now' : (...args) => performance.now(...args),
	'runtime.setExitCode' : (...args) => runtime.setExitCode(...args),
	'stderrWriter.close' : (...args) => stderrWriter.close(...args),
	'stderrWriter.flush' : (...args) => stderrWriter.flush(...args),
	'stderrWriter.printChars' : (...args) => stderrWriter.printChars(...args),
	'stdoutWriter.close' : (...args) => stdoutWriter.close(...args),
	'stdoutWriter.flush' : (...args) => stdoutWriter.flush(...args),
	'stdoutWriter.printChars' : (...args) => stdoutWriter.printChars(...args),
}
;
wasmImports.jsbody = {
	'_JSBigInt.javaString___String' : (...args) => (function(){
		try{
			return conversion.toProxy(toJavaString(this.toString()));
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSBoolean.javaBoolean___Boolean' : (...args) => (function(){
		try{
			return conversion.toProxy(conversion.createJavaBoolean(this));
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSConversion.asJavaObjectOrString___Object_Object' : (...args) => (function(obj){
		try{
			return conversion.isInternalJavaObject(obj) ? obj : toJavaString(obj.toString());
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSConversion.extractJavaScriptProxy___Object_Object' : (...args) => (function(self){
		try{
			return conversion.toProxy(self);
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSConversion.extractJavaScriptString___String_Object' : (...args) => (function(s){
		try{
			return conversion.extractJavaScriptString(s);
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSConversion.javaScriptToJava___Object_Object' : (...args) => (function(x){
		try{
			return conversion.javaScriptToJava(x);
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSConversion.javaScriptUndefined___Object' : (...args) => (function(){
		try{
			return undefined;
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSConversion.unproxy___Object_Object' : (...args) => (function(proxy){
		try{
			const javaNative = proxy[runtime.symbol.javaNative]; return javaNative === undefined ? null : javaNative;
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSNumber.javaDouble___Double' : (...args) => (function(){
		try{
			return conversion.toProxy(conversion.createJavaDouble(this));
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSObject.get___Object_Object' : (...args) => (function(key){
		try{
			return this[key];
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSObject.stringValue___String' : (...args) => (function(){
		try{
			return conversion.toProxy(toJavaString(this.toString()));
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSObject.typeofString___JSString' : (...args) => (function(){
		try{
			return typeof this;
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSString.javaString___String' : (...args) => (function(){
		try{
			return conversion.toProxy(toJavaString(this));
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSSymbol.javaString___String' : (...args) => (function(){
		try{
			return conversion.toProxy(toJavaString(this.toString()));
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_JSSymbol.referenceEquals___JSSymbol_JSSymbol_JSBoolean' : (...args) => (function(sym0,sym1){
		try{
			return sym0 === sym1;
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
	'_WebImageUtil.random___D' : (...args) => (function(){
		try{
			return Math.random();
		}catch( e ) {
			conversion.handleJSError(e);}}).call(...args),
}
;


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Code dealing with moving values between the Java and JavaScript world.
 *
 * This code handles Java values:
 * - All Java values except for objects and longs are represented as JS Number values.
 * - Object and long representation depends on the backend used.
 * Variables and arguments representing Java values are usually marked explicitly
 * (e.g. by being named something like javaObject or jlstring, which stands for
 * java.lang.String).
 *
 * Java values can be used to call Java methods directly without additional
 * conversions, which is the basis of the functionality this class provides.
 * It facilitates calling Java methods from JavaScript by first performing the
 * necessary conversions or coercions before the Java call is executed. In the
 * reverse direction, it helps Java code execute JS code (e.g. through the @JS
 * annotation) by converting or coercing Java values into appropriate JS values.
 */
class Conversion {
    /**
     * Associates the given Java object with the given JS value.
     */
    setJavaScriptNative(javaObject, jsNative) {
        throw new Error("Unimplemented: Conversion.javaScriptNative");
    }

    /**
     * Returns the JS value associated with the given Java object or null if there is no associated value.
     */
    extractJavaScriptNative(javaObject) {
        throw new Error("Unimplemented: Conversion.extractJavaScriptNative");
    }

    // Java-to-JavaScript conversions

    /**
     * Given a Java boxed Double, creates the corresponding JavaScript number value.
     *
     * @param jldouble The java.lang.Double object
     * @return {*} A JavaScript Number value
     */
    extractJavaScriptNumber(jldouble) {
        throw new Error("Unimplemented: Conversion.extractJavaScriptNumber");
    }

    /**
     * Given a Java String, creates the corresponding JavaScript string value.
     *
     * Note: the Java method called in this implementation will return (in the generated code)
     * an actual primitive Java string.
     *
     * @param jlstring The java.lang.String object
     * @return {*} A JavaScript String value
     */
    extractJavaScriptString(jlstring) {
        throw new Error("Unimplemented: Conversion.extractJavaScriptString");
    }

    /**
     * Converts a Java array to a JavaScript array that contains JavaScript values
     * that correspond to the Java values of the input array.
     *
     * @param jarray A Java array
     * @returns {*} The resulting JavaScript array
     */
    extractJavaScriptArray(jarray) {
        throw new Error("Unimplemented: Conversion.extractJavaScriptArray");
    }

    // JavaScript-to-Java conversions (standard Java classes)

    /**
     * Creates a java.lang.Boolean object from a JavaScript boolean value.
     */
    createJavaBoolean(b) {
        throw new Error("Unimplemented: Conversion.createJavaBoolean");
    }

    /**
     * Creates a java.lang.Byte object from a JavaScript number value.
     */
    createJavaByte(x) {
        throw new Error("Unimplemented: Conversion.createJavaByte");
    }

    /**
     * Creates a java.lang.Short object from a JavaScript number value.
     */
    createJavaShort(x) {
        throw new Error("Unimplemented: Conversion.createJavaShort");
    }

    /**
     * Creates a java.lang.Character object from a JavaScript number value.
     */
    createJavaCharacter(x) {
        throw new Error("Unimplemented: Conversion.createJavaCharacter");
    }

    /**
     * Creates a java.lang.Integer object from a JavaScript number value.
     */
    createJavaInteger(x) {
        throw new Error("Unimplemented: Conversion.createJavaInteger");
    }

    /**
     * Creates a java.lang.Float object from a JavaScript number value.
     */
    createJavaFloat(x) {
        throw new Error("Unimplemented: Conversion.createJavaFloat");
    }

    /**
     * Creates a java.lang.Long object from a JavaScript number value.
     */
    createJavaLong(x) {
        throw new Error("Unimplemented: Conversion.createJavaLong");
    }

    /**
     * Creates a java.lang.Double object from a JavaScript number value.
     */
    createJavaDouble(x) {
        throw new Error("Unimplemented: Conversion.createJavaDouble");
    }

    /**
     * Gets the JavaKind ordinal for the given hub, as expected by `boxIfNeeded`.
     */
    getHubKindOrdinal(hub) {
        throw new Error("Unimplemented: Conversion.getHubKindOrdinal");
    }

    /**
     * Box the given value if the specified type is primitive.
     *
     * The parameter type is the enum index as defined in jdk.vm.ci.meta.JavaKind.
     * The following is a summary:
     *
     *      0 - Boolean
     *      1 - Byte
     *      2 - Short
     *      3 - Char
     *      4 - Int
     *      5 - Float
     *      6 - Long
     *      7 - Double
     *      8 - Object
     *
     * @param {number=} type
     */
    boxIfNeeded(javaValue, type) {
        switch (type) {
            case 0:
                return this.createJavaBoolean(javaValue);
            case 1:
                return this.createJavaByte(javaValue);
            case 2:
                return this.createJavaShort(javaValue);
            case 3:
                return this.createJavaCharacter(javaValue);
            case 4:
                return this.createJavaInteger(javaValue);
            case 5:
                return this.createJavaFloat(javaValue);
            case 6:
                return this.createJavaLong(javaValue);
            case 7:
                return this.createJavaDouble(javaValue);
            default:
                return javaValue;
        }
    }

    /**
     * Unbox the given value if the specified type is primitive.
     *
     * See documentation for `boxIfNeeded`.
     */
    unboxIfNeeded(javaObject, type) {
        switch (type) {
            case 0:
                return this.unboxBoolean(javaObject);
            case 1:
                return this.unboxByte(javaObject);
            case 2:
                return this.unboxShort(javaObject);
            case 3:
                return this.unboxChar(javaObject);
            case 4:
                return this.unboxInt(javaObject);
            case 5:
                return this.unboxFloat(javaObject);
            case 6:
                return this.unboxLong(javaObject);
            case 7:
                return this.unboxDouble(javaObject);
            default:
                return javaObject;
        }
    }

    unboxBoolean(jlBoolean) {
        throw new Error("Unimplemented: Conversion.unboxBoolean");
    }

    unboxByte(jlByte) {
        throw new Error("Unimplemented: Conversion.unboxByte");
    }

    unboxShort(jlShort) {
        throw new Error("Unimplemented: Conversion.unboxShort");
    }

    unboxChar(jlChar) {
        throw new Error("Unimplemented: Conversion.unboxChar");
    }

    unboxInt(jlInt) {
        throw new Error("Unimplemented: Conversion.unboxInt");
    }

    unboxFloat(jlFloat) {
        throw new Error("Unimplemented: Conversion.unboxFloat");
    }

    unboxLong(jlLong) {
        throw new Error("Unimplemented: Conversion.unboxLong");
    }

    unboxDouble(jlDouble) {
        throw new Error("Unimplemented: Conversion.unboxDouble");
    }

    /**
     * Gets the boxed counterpart of the given primitive hub.
     */
    getBoxedHub(jlClass) {
        throw new Error("Unimplemented: Conversion.getBoxedHub");
    }

    // JavaScript-to-Java conversions (JSValue classes)

    /**
     * Gets the Java singleton object that represents the JavaScript undefined value.
     */
    createJSUndefined() {
        throw new Error("Unimplemented: Conversion.createJSUndefined");
    }

    /**
     * Wraps a JavaScript Boolean into a Java JSBoolean object.
     *
     * @param boolean The JavaScript boolean to wrap
     * @return {*} The Java JSBoolean object
     */
    createJSBoolean(boolean) {
        throw new Error("Unimplemented: Conversion.createJSBoolean");
    }

    /**
     * Wraps a JavaScript Number into a Java JSNumber object.
     *
     * @param number The JavaScript number to wrap
     * @return {*} The Java JSNumber object
     */
    createJSNumber(number) {
        throw new Error("Unimplemented: Conversion.createJSNumber");
    }

    /**
     * Wraps a JavaScript BigInt into a Java JSBigInt object.
     *
     * @param bigint The JavaScript BigInt value to wrap
     * @return {*} The Java JSBigInt object
     */
    createJSBigInt(bigint) {
        throw new Error("Unimplemented: Conversion.createJSBigInt");
    }

    /**
     * Wraps a JavaScript String into a Java JSString object.
     *
     * @param string The JavaScript String value to wrap
     * @return {*} The Java JSString object
     */
    createJSString(string) {
        throw new Error("Unimplemented: Conversion.createJSString");
    }

    /**
     * Wraps a JavaScript Symbol into a Java JSSymbol object.
     *
     * @param symbol The JavaScript Symbol value to wrap
     * @return {*} The Java JSSymbol object
     */
    createJSSymbol(symbol) {
        throw new Error("Unimplemented: Conversion.createJSSymbol");
    }

    /**
     * Wraps a JavaScript object into a Java JSObject object.
     *
     * @param obj The JavaScript Object value to wrap
     * @returns {*} The Java JSObject object
     */
    createJSObject(obj) {
        throw new Error("Unimplemented: Conversion.createJSObject");
    }

    // Helper methods

    /**
     * Checks if the specified object (which may be a JavaScript value or a Java value) is an internal Java object.
     */
    isInternalJavaObject(obj) {
        throw new Error("Unimplemented: Conversion.isInternalJavaObject");
    }

    isPrimitiveHub(hub) {
        throw new Error("Unimplemented: Conversion.isPrimitiveHub");
    }

    isJavaLangString(obj) {
        throw new Error("Unimplemented: Conversion.isJavaLangString");
    }

    isJavaLangClass(obj) {
        throw new Error("Unimplemented: Conversion.isJavaLangClassHub");
    }

    isInstance(obj, hub) {
        throw new Error("Unimplemented: Conversion.isInstance");
    }

    /**
     * Copies own fields from source to destination.
     *
     * Existing fields in the destination are overwritten.
     */
    copyOwnFields(src, dst) {
        for (let name of Object.getOwnPropertyNames(src)) {
            dst[name] = src[name];
        }
    }

    /**
     * Creates an anonymous JavaScript object, and does the mirror handshake.
     */
    createAnonymousJavaScriptObject() {
        const x = {};
        const jsObject = this.createJSObject(x);
        x[runtime.symbol.javaNative] = jsObject;
        return x;
    }

    /**
     * Obtains or creates the proxy handler for the given Java class
     */
    getOrCreateProxyHandler(arg) {
        throw new Error("Unimplemented: Conversion.getOrCreateProxyHandler");
    }

    /**
     * For proxying the given object returns value that should be passed to
     * getOrCreateProxyHandler.
     */
    _getProxyHandlerArg(obj) {
        throw new Error("Unimplemented: Conversion._getProxyHandlerArg");
    }

    /**
     * Creates a proxy that intercepts messages that correspond to Java method calls and Java field accesses.
     *
     * @param obj The Java object to create a proxy for
     * @return {*} The proxy around the Java object
     */
    toProxy(obj) {
        let proxyHandler = this.getOrCreateProxyHandler(this._getProxyHandlerArg(obj));
        // The wrapper is a temporary object that allows having the non-identifier name of the target function.
        // We declare the property as a function, to ensure that it is constructable, so that the Proxy handler's construct method is callable.
        let targetWrapper = {
            ["Java Proxy"]: function (key) {
                if (key === runtime.symbol.javaNative) {
                    return obj;
                }
                return undefined;
            },
        };

        return new Proxy(targetWrapper["Java Proxy"], proxyHandler);
    }

    /**
     * Converts a JavaScript value to the corresponding Java representation.
     *
     * The exact rules of the mapping are documented in the Java JS annotation class.
     *
     * This method is only meant to be called from the conversion code generated for JS-annotated methods.
     *
     * @param x The JavaScript value to convert
     * @return {*} The Java representation of the JavaScript value
     */
    javaScriptToJava(x) {
        // Step 1: check null, which is mapped 1:1 to null in Java.
        if (x === null) {
            return null;
        }

        // Step 2: check undefined, which is a singleton in Java.
        if (x === undefined) {
            return this.createJSUndefined();
        }

        // Step 3: check if the javaNative property is set.
        // This covers objects that already have Java counterparts (for example, Java proxies).
        const javaValue = x[runtime.symbol.javaNative];
        if (javaValue !== undefined) {
            return javaValue;
        }

        // Step 4: use the JavaScript type to select the appropriate Java representation.
        const tpe = typeof x;
        switch (tpe) {
            case "boolean":
                return this.createJSBoolean(x);
            case "number":
                return this.createJSNumber(x);
            case "bigint":
                return this.createJSBigInt(x);
            case "string":
                return this.createJSString(x);
            case "symbol":
                return this.createJSSymbol(x);
            case "object":
            case "function":
                // We know this is a normal object created in JavaScript,
                // otherwise it would have a runtime.symbol.javaNative property,
                // and the conversion would have returned in Step 3.
                return this.createJSObject(x);
            default:
                throw new Error("unexpected type: " + tpe);
        }
    }

    /**
     * Maps each JavaScript value in the input array to a Java value.
     * See {@code javaScriptToJava}.
     */
    eachJavaScriptToJava(javaScriptValues) {
        const javaValues = new Array(javaScriptValues.length);
        for (let i = 0; i < javaScriptValues.length; i++) {
            javaValues[i] = this.javaScriptToJava(javaScriptValues[i]);
        }
        return javaValues;
    }

    /**
     * Converts a Java value to JavaScript.
     */
    javaToJavaScript(x) {
        throw new Error("Unimplemented: Conversion.javaToJavaScript");
    }

    throwClassCastExceptionImpl(javaObject, tpeNameJavaString) {
        throw new Error("Unimplemented: Conversion.throwClassCastExceptionImpl");
    }

    throwClassCastException(javaObject, tpe) {
        let tpeName;
        if (typeof tpe === "string") {
            tpeName = tpe;
        } else if (typeof tpe === "function") {
            tpeName = tpe.name;
        } else {
            tpeName = tpe.toString();
        }
        this.throwClassCastExceptionImpl(javaObject, toJavaString(tpeName));
    }

    /**
     * Converts the specified Java Proxy to the target JavaScript type, if possible.
     *
     * This method is meant to be called from Java Proxy object, either when implicit coercion is enabled,
     * or when the user explicitly invokes coercion on the Proxy object.
     *
     * @param proxyHandler handler for the proxy that must be converted
     * @param proxy the Java Proxy object that should be coerced
     * @param tpe target JavaScript type name (result of the typeof operator) or constructor function
     * @return {*} the resulting JavaScript value
     */
    coerceJavaProxyToJavaScriptType(proxyHandler, proxy, tpe) {
        throw new Error("Unimplemented: Conversion.coerceJavaProxyToJavaScriptType");
    }

    /**
     * Try to convert the JavaScript object to a Java facade class, or return null.
     *
     * @param obj JavaScript object whose Java facade class we search for
     * @param cls target Java class in the form of its JavaScript counterpart
     * @return {*} the mirror instance wrapped into a JavaScript Java Proxy, or null
     */
    tryExtractFacadeClass(obj, cls) {
        const facades = runtime.findFacadesFor(obj.constructor);
        const rawJavaHub = cls[runtime.symbol.javaNative];
        const internalJavaClass = rawJavaHub[runtime.symbol.jsClass];
        if (facades.has(internalJavaClass)) {
            const rawJavaMirror = new internalJavaClass();
            // Note: only one-way handshake, since the JavaScript object could be recast to a different Java facade class.
            this.setJavaScriptNative(rawJavaMirror, obj);
            return this.toProxy(rawJavaMirror);
        } else {
            return null;
        }
    }

    /**
     * Coerce the specified JavaScript value to the specified Java type.
     *
     * See VM.as for the specification of this function.
     */
    coerceJavaScriptToJavaType(javaScriptValue, type) {
        throw new Error("Unimplemented: Conversion.coerceJavaScriptToJavaType");
    }
}

/**
 * Handle for proxying Java objects.
 *
 * Client JS code never directly sees Java object, instead they see proxies
 * using this handler. The handler is generally specialized per type.
 * It provides access to the underlying Java methods.
 *
 * It also supports invoking the proxy, which calls the single abstract method
 * in the Java object if available, and for Class objects the new operator
 * works, creating a Java object and invoking a matching constructor.
 *
 * The backends provide method metadata describing the Java methods available
 * to the proxy. At runtime, when a method call is triggered (a method is
 * accessed and called, the proxy itself is invoked, or a constructor is called),
 * the proxy will find a matching implementation based on the types of the
 * passed arguments.
 * Arguments and return values are automatically converted to and from Java
 * objects respectively, but no coercion is done.
 */
class ProxyHandler {
    constructor() {
        this._initialized = false;
        this._methods = {};
        this._staticMethods = {};
        this._javaConstructorMethod = null;
    }

    ensureInitialized() {
        if (!this._initialized) {
            this._initialized = true;
            // Function properties derived from accessible Java methods.
            this._createProxyMethods();
            // Default function properties.
            this._createDefaultMethods();
        }
    }

    _getMethods() {
        this.ensureInitialized();
        return this._methods;
    }

    _getStaticMethods() {
        this.ensureInitialized();
        return this._staticMethods;
    }

    _getJavaConstructorMethod() {
        this.ensureInitialized();
        return this._javaConstructorMethod;
    }

    /**
     * Returns a ClassMetadata instance for the class this proxy handler represents.
     */
    _getClassMetadata() {
        throw new Error("Unimplemented: ProxyHandler._getClassMetadata");
    }

    _getMethodTable() {
        const classMeta = this._getClassMetadata();
        if (classMeta === undefined) {
            return undefined;
        }
        return classMeta.methodTable;
    }

    /**
     * String that can be printed as part of the toString and valueOf functions.
     */
    _getClassName() {
        throw new Error("Unimplemented: ProxyHandler._getClassName");
    }

    /**
     * Link the methods object to the prototype chain of the methods object of the superclass' proxy handler.
     */
    _linkMethodPrototype() {
        throw new Error("Unimplemented: ProxyHandler._linkMethodPrototype");
    }

    _createProxyMethods() {
        // Create proxy methods for the current class.
        const methodTable = this._getMethodTable();
        if (methodTable === undefined) {
            return;
        }

        const proxyHandlerThis = this;
        for (const name in methodTable) {
            const overloads = methodTable[name];
            const instanceOverloads = [];
            const staticOverloads = [];
            for (const m of overloads) {
                if (m.isStatic) {
                    staticOverloads.push(m);
                } else {
                    instanceOverloads.push(m);
                }
            }
            if (instanceOverloads.length > 0) {
                this._methods[name] = function (...javaScriptArgs) {
                    // Note: the 'this' value is bound to the Proxy object.
                    return proxyHandlerThis._invokeProxyMethod(name, instanceOverloads, this, ...javaScriptArgs);
                };
            }
            if (staticOverloads.length > 0) {
                this._staticMethods[name] = function (...javaScriptArgs) {
                    // Note: the 'this' value is bound to the Proxy object.
                    return proxyHandlerThis._invokeProxyMethod(name, staticOverloads, null, ...javaScriptArgs);
                };
            }
        }
        if (methodTable[runtime.symbol.ctor] !== undefined) {
            const overloads = methodTable[runtime.symbol.ctor];
            this._javaConstructorMethod = function (javaScriptJavaProxy, ...javaScriptArgs) {
                // Note: the 'this' value is bound to the Proxy object.
                return proxyHandlerThis._invokeProxyMethod("<init>", overloads, javaScriptJavaProxy, ...javaScriptArgs);
            };
        } else {
            this._javaConstructorMethod = function (javaScriptJavaProxy, ...javaScriptArgs) {
                throw new Error(
                    "Cannot invoke the constructor. Make sure that the constructors are explicitly added to the image."
                );
            };
        }

        this._linkMethodPrototype();
    }

    /**
     * Checks whether the given argument values can be used to call the method identified by the given metdata class.
     */
    _conforms(args, metadata) {
        if (metadata.paramHubs.length !== args.length) {
            return false;
        }
        for (let i = 0; i < args.length; i++) {
            const arg = args[i];
            let paramHub = metadata.paramHubs[i];
            if (paramHub === null) {
                // A null parameter hub means that the type-check always passes.
                continue;
            }
            if (conversion.isPrimitiveHub(paramHub)) {
                // A primitive hub must be replaced with the hub of the corresponding boxed type.
                paramHub = conversion.getBoxedHub(paramHub);
            }
            if (!conversion.isInstance(arg, paramHub)) {
                return false;
            }
        }
        return true;
    }

    _unboxJavaArguments(args, metadata) {
        // Precondition -- method metadata refers to a method with a correct arity.
        for (let i = 0; i < args.length; i++) {
            const paramHub = metadata.paramHubs[i];
            args[i] = conversion.unboxIfNeeded(args[i], conversion.getHubKindOrdinal(paramHub));
        }
    }

    _createDefaultMethods() {
        if (!this._methods.hasOwnProperty("toString")) {
            // The check must use hasOwnProperty, because toString always exists in the prototype.
            this._methods["toString"] = () => "[Java Proxy: " + this._getClassName() + "]";
        } else {
            const javaToString = this._methods["toString"];
            this._methods[runtime.symbol.toString] = javaToString;
            this._methods["toString"] = function () {
                // The `this` value must be bound to the proxy instance.
                //
                // The `toString` method is used often in JavaScript, and treated specially.
                // If its return type is a Java String, then that string is converted to a JavaScript string.
                // In other words, if the result of the call is a JavaScript proxy (see _invokeProxyMethod return value),
                // then proxies that represent java.lang.String are converted to JavaScript strings.
                const javaScriptResult = javaToString.call(this);
                if (typeof javaScriptResult === "function" || typeof javaScriptResult === "object") {
                    const javaResult = javaScriptResult[runtime.symbol.javaNative];
                    if (javaResult !== undefined && conversion.isJavaLangString(javaResult)) {
                        return conversion.extractJavaScriptString(javaResult);
                    } else {
                        return javaScriptResult;
                    }
                } else {
                    return javaScriptResult;
                }
            };
        }

        // Override Java methods that return valueOf.
        // JavaScript requires that valueOf returns a JavaScript primitive (in this case, string).
        this._methods["valueOf"] = () => "[Java Proxy: " + this._getClassName() + "]";

        const proxyHandlerThis = this;
        const asProperty = function (tpe) {
            // Note: this will be bound to the Proxy object.
            return conversion.coerceJavaProxyToJavaScriptType(proxyHandlerThis, this, tpe);
        };
        if (!("$as" in this._methods)) {
            this._methods["$as"] = asProperty;
        }
        this._methods[runtime.symbol.javaScriptCoerceAs] = asProperty;

        const vmProperty = vm;
        if (!("$vm" in this._methods)) {
            this._methods["$vm"] = vmProperty;
        }
    }

    _loadMethod(target, key) {
        const member = this._getMethods()[key];
        if (member !== undefined) {
            return member;
        }
    }

    _methodNames() {
        return Object.keys(this._getMethods());
    }

    _invokeProxyMethod(name, overloads, javaScriptJavaProxy, ...javaScriptArgs) {
        // For static methods, javaScriptThis is set to null.
        const isStatic = javaScriptJavaProxy === null;
        const javaThis = isStatic ? null : javaScriptJavaProxy[runtime.symbol.javaNative];
        const javaArgs = conversion.eachJavaScriptToJava(javaScriptArgs);
        for (let i = 0; i < overloads.length; i++) {
            const metadata = overloads[i];
            if (this._conforms(javaArgs, metadata)) {
                // Where necessary, perform unboxing of Java arguments.
                this._unboxJavaArguments(javaArgs, metadata);
                let javaResult;
                try {
                    if (isStatic) {
                        javaResult = metadata.method.call(null, ...javaArgs);
                    } else {
                        javaResult = metadata.method.call(null, javaThis, ...javaArgs);
                    }
                } catch (error) {
                    throw conversion.javaToJavaScript(error);
                }
                if (javaResult === undefined) {
                    // This only happens when the return type is void.
                    return undefined;
                }
                // If necessary, box the Java return value.
                const retHub = metadata.returnHub;
                javaResult = conversion.boxIfNeeded(javaResult, conversion.getHubKindOrdinal(retHub));
                const javaScriptResult = conversion.javaToJavaScript(javaResult);
                return javaScriptResult;
            }
        }
        const methodName = name !== null ? "method '" + name + "'" : "single abstract method";
        throw new Error("No matching signature for " + methodName + " and argument list '" + javaScriptArgs + "'");
    }

    /**
     * The Java type hierarchy is not modelled in the proxy and the proxied
     * object has no prototype.
     */
    getPrototypeOf(target) {
        return null;
    }

    /**
     * Modifying the prototype of the proxied object is not allowed.
     */
    setPrototypeOf(target, prototype) {
        return false;
    }

    /**
     * Proxied objects are not extensible in any way.
     */
    isExtensible(target) {
        return false;
    }

    /**
     * We allow calling Object.preventExtensions on the proxy.
     * However, it won't do anything, the proxy handler already prevents extensions.
     */
    preventExtensions(target) {
        return true;
    }

    getOwnPropertyDescriptor(target, key) {
        const value = this._loadMethod(target, key);
        if (value === undefined) {
            return undefined;
        }
        return {
            value: value,
            writable: false,
            enumerable: false,
            configurable: false,
        };
    }

    /**
     * Defining properties on the Java object is not allowed.
     */
    defineProperty(target, key, descriptor) {
        return false;
    }

    has(target, key) {
        return this._loadMethod(target, key) !== undefined;
    }

    get(target, key) {
        if (key === runtime.symbol.javaNative) {
            return target(runtime.symbol.javaNative);
        } else {
            const javaObject = target(runtime.symbol.javaNative);
            // TODO GR-60603 Deal with arrays in WasmGC backend
            if (Array.isArray(javaObject) && typeof key === "string") {
                const index = Number(key);
                if (0 <= index && index < javaObject.length) {
                    return conversion.javaToJavaScript(javaObject[key]);
                } else if (key === "length") {
                    return javaObject.length;
                }
            }
        }
        return this._loadMethod(target, key);
    }

    set(target, key, value, receiver) {
        const javaObject = target(runtime.symbol.javaNative);
        // TODO GR-60603 Deal with arrays in WasmGC backend
        if (Array.isArray(javaObject)) {
            const index = Number(key);
            if (0 <= index && index < javaObject.length) {
                javaObject[key] = conversion.javaScriptToJava(value);
                return true;
            }
        }
        return false;
    }

    /**
     * Deleting properties on the Java object is not allowed.
     */
    deleteProperty(target, key) {
        return false;
    }

    ownKeys(target) {
        return this._methodNames();
    }

    apply(target, javaScriptThisArg, javaScriptArgs) {
        // We need to convert the Proxy's target function to the Java Proxy.
        const javaScriptJavaProxy = conversion.toProxy(target(runtime.symbol.javaNative));
        // Note: the JavaScript this argument for the apply method is never exposed to Java, so we just ignore it.
        return this._applyWithObject(javaScriptJavaProxy, javaScriptArgs);
    }

    _getSingleAbstractMethod(javaScriptJavaProxy) {
        return this._getClassMetadata().singleAbstractMethod;
    }

    _applyWithObject(javaScriptJavaProxy, javaScriptArgs) {
        const sam = this._getSingleAbstractMethod(javaScriptJavaProxy);
        if (sam === undefined) {
            throw new Error("Java Proxy is not a functional interface, so 'apply' cannot be called from JavaScript.");
        }
        return this._invokeProxyMethod(null, [sam], javaScriptJavaProxy, ...javaScriptArgs);
    }

    /**
     * Create uninitialized instance of given Java type.
     */
    _createInstance(hub) {
        throw new Error("Unimplemented: ProxyHandler._createInstance");
    }

    construct(target, argumentsList) {
        const javaThis = target(runtime.symbol.javaNative);
        // This is supposed to be a proxy handler for java.lang.Class objects
        // and javaThis is supposed to be some Class instance.
        if (!conversion.isJavaLangClass(javaThis)) {
            throw new Error(
                "Cannot invoke the 'new' operator. The 'new' operator can only be used on Java Proxies that represent the 'java.lang.Class' type."
            );
        }
        // Allocate the Java object from Class instance
        const javaInstance = this._createInstance(javaThis);
        // Lookup constructor method of the target class.
        // This proxy handler is for java.lang.Class while javaThis is a
        // java.lang.Class instance for some object type for which we want to
        // lookup the constructor.
        const instanceProxyHandler = conversion.getOrCreateProxyHandler(conversion._getProxyHandlerArg(javaInstance));
        const javaConstructorMethod = instanceProxyHandler._getJavaConstructorMethod();
        // Convert the Java instance to JS (usually creates a proxy)
        const javaScriptInstance = conversion.javaToJavaScript(javaInstance);
        // Call the Java constructor method.
        javaConstructorMethod(javaScriptInstance, ...argumentsList);
        return javaScriptInstance;
    }
}


/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * WasmGC-backend specific implementation of conversion code.
 *
 * In the WasmGC backend, all Java values are originally Wasm values, with
 * objects being references to Wasm structs. How those values are represented
 * in Java is governed by the "WebAssembly JavaScript Interface".
 * Java Objects are represented as opaque JS objects, these objects do not have
 * any properties of their own nor are they extensible (though identity with
 * regards to the === operator is preserved), only when passing them back to
 * Wasm code can they be manipulated.
 * Java long values are represented as JS BigInt values.
 *
 * Unlike the JS backend, Java code compiled to WasmGC cannot directly be passed
 * JS objects as arguments due to Wasm's type safety. Instead, JS values are
 * first wrapped in WasmExtern, a custom Java class with some special handling
 * to have it store and externref value in one of its fields.
 *
 * To support JSValue instances, there are Java factory methods for each
 * subclass exported under convert.create.*, which create a new instance of the
 * type and associate it with the given JavaScript value.
 * Instead of having the JS code store the JS native value directly in the
 * WasmGC object (which won't work because they are immutable on the JS side),
 * the JS value is first wrapped in a WasmExtern, and then passed to Java, where
 * that WasmExtern value is stored in a hidden field of the JSValue instance.
 */
class WasmGCConversion extends Conversion {
    constructor() {
        super();
        this.proxyHandlers = new WeakMap();
    }

    #wrapExtern(jsObj) {
        return getExport("extern.wrap")(jsObj);
    }

    #unwrapExtern(javaObj) {
        return getExport("extern.unwrap")(javaObj);
    }

    handleJSError(jsError) {
        if (jsError instanceof WebAssembly.Exception) {
            // Wasm exceptions can be rethrown as-is. They will be caught in Wasm code
            throw jsError;
        } else {
            // Have Java code wrap the JS error in a Java JSError instance and throw it.
            getExport("convert.throwjserror")(this.javaScriptToJava(jsError));
        }
    }

    extractJavaScriptNumber(jldouble) {
        return getExport("unbox.double")(jldouble);
    }

    extractJavaScriptString(jlstring) {
        return charArrayToString(proxyCharArray(getExport("string.tochars")(jlstring)));
    }

    extractJavaScriptArray(jarray) {
        const length = getExport("array.length")(jarray);
        const jsarray = new Array(length);
        for (let i = 0; i < length; i++) {
            jsarray[i] = this.javaToJavaScript(getExport("array.object.read")(jarray, i));
        }
        return jsarray;
    }

    createJavaBoolean(x) {
        return getExport("box.boolean")(x);
    }

    createJavaByte(x) {
        return getExport("box.byte")(x);
    }

    createJavaShort(x) {
        return getExport("box.short")(x);
    }

    createJavaCharacter(x) {
        return getExport("box.char")(x);
    }

    createJavaInteger(x) {
        return getExport("box.int")(x);
    }

    createJavaFloat(x) {
        return getExport("box.float")(x);
    }

    createJavaLong(x) {
        return getExport("box.long")(x);
    }

    createJavaDouble(x) {
        return getExport("box.double")(x);
    }

    getHubKindOrdinal(hub) {
        return getExport("class.getkindordinal")(hub);
    }

    getBoxedHub(jlClass) {
        return getExport("class.getboxedhub")(jlClass);
    }

    unboxBoolean(jlBoolean) {
        return getExport("unbox.boolean")(jlBoolean);
    }

    unboxByte(jlByte) {
        return getExport("unbox.byte")(jlByte);
    }

    unboxShort(jlShort) {
        return getExport("unbox.short")(jlShort);
    }

    unboxChar(jlChar) {
        return getExport("unbox.char")(jlChar);
    }

    unboxInt(jlInt) {
        return getExport("unbox.int")(jlInt);
    }

    unboxFloat(jlFloat) {
        return getExport("unbox.float")(jlFloat);
    }

    unboxLong(jlLong) {
        return getExport("unbox.long")(jlLong);
    }

    unboxDouble(jlDouble) {
        return getExport("unbox.double")(jlDouble);
    }

    createJSUndefined() {
        return getExport("convert.create.jsundefined")();
    }

    createJSBoolean(boolean) {
        return getExport("convert.create.jsboolean")(this.#wrapExtern(boolean));
    }

    createJSNumber(number) {
        return getExport("convert.create.jsnumber")(this.#wrapExtern(number));
    }

    createJSBigInt(bigint) {
        return getExport("convert.create.jsbigint")(this.#wrapExtern(bigint));
    }

    createJSString(string) {
        return getExport("convert.create.jsstring")(this.#wrapExtern(string));
    }

    createJSSymbol(symbol) {
        return getExport("convert.create.jssymbol")(this.#wrapExtern(symbol));
    }

    createJSObject(obj) {
        return getExport("convert.create.jsobject")(this.#wrapExtern(obj));
    }

    isInternalJavaObject(obj) {
        return getExport("extern.isjavaobject")(obj);
    }

    isPrimitiveHub(hub) {
        return getExport("class.isprimitive")(hub);
    }

    isJavaLangString(obj) {
        return getExport("convert.isjavalangstring")(obj);
    }

    isJavaLangClass(obj) {
        return getExport("convert.isjavalangclass")(obj);
    }

    isInstance(obj, hub) {
        return getExport("object.isinstance")(obj, hub);
    }

    getOrCreateProxyHandler(clazz) {
        if (!this.proxyHandlers.has(clazz)) {
            this.proxyHandlers.set(clazz, new WasmGCProxyHandler(clazz));
        }
        return this.proxyHandlers.get(clazz);
    }

    _getProxyHandlerArg(obj) {
        return getExport("object.getclass")(obj);
    }

    javaToJavaScript(x) {
        let effectiveJavaObject = x;

        /*
         * When catching exceptions in JavaScript, exceptions thrown from Java
         * aren't caught as Java objects, but as WebAssembly.Exception objects.
         * Instead of having to do special handling whenever we catch an
         * exception in JS, converting to JavaScript first unwraps the original
         * Java Throwable before converting.
         */
        if (x instanceof WebAssembly.Exception && x.is(getExport("tag.throwable"))) {
            effectiveJavaObject = x.getArg(getExport("tag.throwable"), 0);
        }

        return this.#unwrapExtern(getExport("convert.javatojavascript")(effectiveJavaObject));
    }

    throwClassCastExceptionImpl(javaObject, tpeNameJavaString) {
        getExport("convert.throwClassCastException")(javaObject, tpeNameJavaString);
    }

    coerceJavaProxyToJavaScriptType(proxyHandler, proxy, tpe) {
        const o = proxy[runtime.symbol.javaNative];
        switch (tpe) {
            case "boolean":
                // Due to Java booleans being numbers, the double-negation is necessary.
                return !!this.#unwrapExtern(getExport("convert.coerce.boolean")(o));
            case "number":
                return this.#unwrapExtern(getExport("convert.coerce.number")(o));
            case "bigint":
                const bs = this.#unwrapExtern(getExport("convert.coerce.bigint")(o));
                return BigInt(bs);
            case "string":
                return this.#unwrapExtern(getExport("convert.coerce.string")(o));
            case "object":
                return this.#unwrapExtern(getExport("convert.coerce.object")(o));
            case "function":
                const sam = proxyHandler._getSingleAbstractMethod(proxy);
                if (sam !== undefined) {
                    return (...args) => proxyHandler._applyWithObject(proxy, args);
                }
                this.throwClassCastException(o, tpe);
            case Uint8Array:
            case Int8Array:
            case Uint16Array:
            case Int16Array:
            case Int32Array:
            case Float32Array:
            case BigInt64Array:
            case Float64Array:
                // TODO GR-60603 Support array coercion
                throw new Error("Coercion to arrays is not supported yet");
            default:
                this.throwClassCastException(o, tpe);
        }
    }
}

const METADATA_PREFIX = "META.";
const SAM_PREFIX = "SAM.";
const METADATA_SEPARATOR = " ";

class WasmGCProxyHandler extends ProxyHandler {
    #classMetadata = null;

    constructor(clazz) {
        super();
        this.clazz = clazz;
    }

    #lookupClass(name) {
        const clazz = getExport("conversion.classfromencoding")(toJavaString(name));
        if (!clazz) {
            throw new Error("Failed to lookup class " + name);
        }

        return clazz;
    }

    _getClassMetadata() {
        if (!this.#classMetadata) {
            this.#classMetadata = new ClassMetadata({}, this.#extractSingleAbstractMethod(), this.#createMethodTable());
        }
        return this.#classMetadata;
    }

    #decodeMetadata(exports, name, prefix) {
        if (name.startsWith(prefix)) {
            const parts = name.slice(prefix.length).split(METADATA_SEPARATOR);
            if (parts.length < 3) {
                throw new Error("Malformed metadata: " + name);
            }
            const classId = parts[0];

            if (this.#lookupClass(classId) == this.clazz) {
                const methodName = parts[1];
                const returnTypeId = parts[2];
                const argTypeIds = parts.slice(3);

                return [
                    methodName,
                    mmeta(
                        exports[name],
                        this.#lookupClass(returnTypeId),
                        ...argTypeIds.map((i) => this.#lookupClass(i))
                    ),
                ];
            }
        }

        return undefined;
    }

    #extractSingleAbstractMethod() {
        const exports = getExports();

        for (const name in exports) {
            const meta = this.#decodeMetadata(exports, name, SAM_PREFIX);
            if (meta !== undefined) {
                return meta[1];
            }
        }

        return undefined;
    }

    #createMethodTable() {
        const exports = getExports();
        const methodTable = {};

        for (const name in exports) {
            const meta = this.#decodeMetadata(exports, name, METADATA_PREFIX);
            if (meta !== undefined) {
                let methodName = meta[0];

                if (methodName === "<init>") {
                    methodName = runtime.symbol.ctor;
                }

                if (!methodTable.hasOwnProperty(methodName)) {
                    methodTable[methodName] = [];
                }

                methodTable[methodName].push(meta[1]);
            }
        }

        return methodTable;
    }

    _getClassName() {
        return conversion.extractJavaScriptString(getExport("class.getname")(this.clazz));
    }

    _linkMethodPrototype() {
        // Link the prototype chain of the superclass' proxy handler, to include super methods.
        if (!getExport("class.isjavalangobject")(this.clazz)) {
            const parentClass = getExport("class.superclass")(this.clazz);
            const parentProxyHandler = conversion.getOrCreateProxyHandler(parentClass);
            Object.setPrototypeOf(this._getMethods(), parentProxyHandler._getMethods());
        }
    }

    _createInstance(hub) {
        return getExport("unsafe.create")(hub);
    }
}

const conversion = new WasmGCConversion();
const createVM = function(vmArgs, data) {
runtime.data = data;
wasmRun(vmArgs);

return vm;

};
GraalVM.Config = Config;
/** @suppress {checkVars,duplicate} */ GraalVM.run = async function (vmArgs, config = new GraalVM.Config()) {
   let data = new Data(config);
   for (let libname in config.libraries) {
       const content = await runtime.fetchText(config.libraries[libname]);
       data.libraries[libname] = content;
   }
data.wasm = await wasmInstantiate(config, vmArgs);
   let vm = createVM(vmArgs, data);
   return vm;
}
})();

})();

})();

(function() {
/*
 * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * Try to load commandline arguments for various JS runtimes.
 */
function load_cmd_args() {
    if (typeof process === "object" && "argv" in process) {
        // nodejs
        return process.argv.slice(2);
    } else if (typeof scriptArgs == "object") {
        // spidermonkey
        return scriptArgs;
    }

    return window.compilerArgs;
    return [];
}

const config = new GraalVM.Config();
GraalVM.run(load_cmd_args(),config).catch(console.error);
});