1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
|
#include <climits> // INT_MAX
#include <cmath>
#include <algorithm>
#define NAPI_EXPERIMENTAL
#include "env-inl.h"
#include "js_native_api_v8.h"
#include "js_native_api.h"
#include "util-inl.h"
#define CHECK_MAYBE_NOTHING(env, maybe, status) \
RETURN_STATUS_IF_FALSE((env), !((maybe).IsNothing()), (status))
#define CHECK_TO_NUMBER(env, context, result, src) \
CHECK_TO_TYPE((env), Number, (context), (result), (src), napi_number_expected)
// n-api defines NAPI_AUTO_LENGHTH as the indicator that a string
// is null terminated. For V8 the equivalent is -1. The assert
// validates that our cast of NAPI_AUTO_LENGTH results in -1 as
// needed by V8.
#define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \
do { \
static_assert(static_cast<int>(NAPI_AUTO_LENGTH) == -1, \
"Casting NAPI_AUTO_LENGTH to int must result in -1"); \
RETURN_STATUS_IF_FALSE((env), \
(len == NAPI_AUTO_LENGTH) || len <= INT_MAX, \
napi_invalid_arg); \
RETURN_STATUS_IF_FALSE((env), \
(str) != nullptr, \
napi_invalid_arg); \
auto str_maybe = v8::String::NewFromUtf8( \
(env)->isolate, (str), v8::NewStringType::kInternalized, \
static_cast<int>(len)); \
CHECK_MAYBE_EMPTY((env), str_maybe, napi_generic_failure); \
(result) = str_maybe.ToLocalChecked(); \
} while (0)
#define CHECK_NEW_FROM_UTF8(env, result, str) \
CHECK_NEW_FROM_UTF8_LEN((env), (result), (str), NAPI_AUTO_LENGTH)
#define CREATE_TYPED_ARRAY( \
env, type, size_of_element, buffer, byte_offset, length, out) \
do { \
if ((size_of_element) > 1) { \
THROW_RANGE_ERROR_IF_FALSE( \
(env), (byte_offset) % (size_of_element) == 0, \
"ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", \
"start offset of "#type" should be a multiple of "#size_of_element); \
} \
THROW_RANGE_ERROR_IF_FALSE((env), (length) * (size_of_element) + \
(byte_offset) <= buffer->ByteLength(), \
"ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", \
"Invalid typed array length"); \
(out) = v8::type::New((buffer), (byte_offset), (length)); \
} while (0)
namespace v8impl {
namespace {
inline static napi_status
V8NameFromPropertyDescriptor(napi_env env,
const napi_property_descriptor* p,
v8::Local<v8::Name>* result) {
if (p->utf8name != nullptr) {
CHECK_NEW_FROM_UTF8(env, *result, p->utf8name);
} else {
v8::Local<v8::Value> property_value =
v8impl::V8LocalValueFromJsValue(p->name);
RETURN_STATUS_IF_FALSE(env, property_value->IsName(), napi_name_expected);
*result = property_value.As<v8::Name>();
}
return napi_ok;
}
// convert from n-api property attributes to v8::PropertyAttribute
inline static v8::PropertyAttribute V8PropertyAttributesFromDescriptor(
const napi_property_descriptor* descriptor) {
unsigned int attribute_flags = v8::PropertyAttribute::None;
// The napi_writable attribute is ignored for accessor descriptors, but
// V8 would throw `TypeError`s on assignment with nonexistence of a setter.
if ((descriptor->getter == nullptr && descriptor->setter == nullptr) &&
(descriptor->attributes & napi_writable) == 0) {
attribute_flags |= v8::PropertyAttribute::ReadOnly;
}
if ((descriptor->attributes & napi_enumerable) == 0) {
attribute_flags |= v8::PropertyAttribute::DontEnum;
}
if ((descriptor->attributes & napi_configurable) == 0) {
attribute_flags |= v8::PropertyAttribute::DontDelete;
}
return static_cast<v8::PropertyAttribute>(attribute_flags);
}
inline static napi_deferred
JsDeferredFromNodePersistent(v8impl::Persistent<v8::Value>* local) {
return reinterpret_cast<napi_deferred>(local);
}
inline static v8impl::Persistent<v8::Value>*
NodePersistentFromJsDeferred(napi_deferred local) {
return reinterpret_cast<v8impl::Persistent<v8::Value>*>(local);
}
class HandleScopeWrapper {
public:
explicit HandleScopeWrapper(v8::Isolate* isolate) : scope(isolate) {}
private:
v8::HandleScope scope;
};
// In node v0.10 version of v8, there is no EscapableHandleScope and the
// node v0.10 port use HandleScope::Close(Local<T> v) to mimic the behavior
// of a EscapableHandleScope::Escape(Local<T> v), but it is not the same
// semantics. This is an example of where the api abstraction fail to work
// across different versions.
class EscapableHandleScopeWrapper {
public:
explicit EscapableHandleScopeWrapper(v8::Isolate* isolate)
: scope(isolate), escape_called_(false) {}
bool escape_called() const {
return escape_called_;
}
template <typename T>
v8::Local<T> Escape(v8::Local<T> handle) {
escape_called_ = true;
return scope.Escape(handle);
}
private:
v8::EscapableHandleScope scope;
bool escape_called_;
};
inline static napi_handle_scope
JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) {
return reinterpret_cast<napi_handle_scope>(s);
}
inline static HandleScopeWrapper*
V8HandleScopeFromJsHandleScope(napi_handle_scope s) {
return reinterpret_cast<HandleScopeWrapper*>(s);
}
inline static napi_escapable_handle_scope
JsEscapableHandleScopeFromV8EscapableHandleScope(
EscapableHandleScopeWrapper* s) {
return reinterpret_cast<napi_escapable_handle_scope>(s);
}
inline static EscapableHandleScopeWrapper*
V8EscapableHandleScopeFromJsEscapableHandleScope(
napi_escapable_handle_scope s) {
return reinterpret_cast<EscapableHandleScopeWrapper*>(s);
}
inline static napi_status ConcludeDeferred(napi_env env,
napi_deferred deferred,
napi_value result,
bool is_resolved) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->isolate->GetCurrentContext();
v8impl::Persistent<v8::Value>* deferred_ref =
NodePersistentFromJsDeferred(deferred);
v8::Local<v8::Value> v8_deferred =
v8::Local<v8::Value>::New(env->isolate, *deferred_ref);
auto v8_resolver = v8::Local<v8::Promise::Resolver>::Cast(v8_deferred);
v8::Maybe<bool> success = is_resolved ?
v8_resolver->Resolve(context, v8impl::V8LocalValueFromJsValue(result)) :
v8_resolver->Reject(context, v8impl::V8LocalValueFromJsValue(result));
delete deferred_ref;
RETURN_STATUS_IF_FALSE(env, success.FromMaybe(false), napi_generic_failure);
return GET_RETURN_STATUS(env);
}
// Wrapper around v8impl::Persistent that implements reference counting.
class RefBase : protected Finalizer, RefTracker {
protected:
RefBase(napi_env env,
uint32_t initial_refcount,
bool delete_self,
napi_finalize finalize_callback,
void* finalize_data,
void* finalize_hint)
: Finalizer(env, finalize_callback, finalize_data, finalize_hint),
_refcount(initial_refcount),
_delete_self(delete_self) {
Link(finalize_callback == nullptr
? &env->reflist
: &env->finalizing_reflist);
}
public:
static RefBase* New(napi_env env,
uint32_t initial_refcount,
bool delete_self,
napi_finalize finalize_callback,
void* finalize_data,
void* finalize_hint) {
return new RefBase(env,
initial_refcount,
delete_self,
finalize_callback,
finalize_data,
finalize_hint);
}
inline void* Data() {
return _finalize_data;
}
// Delete is called in 2 ways. Either from the finalizer or
// from one of Unwrap or napi_delete_reference.
//
// When it is called from Unwrap or napi_delete_reference we only
// want to do the delete if the finalizer has already run or
// cannot have been queued to run (ie the reference count is > 0),
// otherwise we may crash when the finalizer does run.
// If the finalizer may have been queued and has not already run
// delay the delete until the finalizer runs by not doing the delete
// and setting _delete_self to true so that the finalizer will
// delete it when it runs.
//
// The second way this is called is from
// the finalizer and _delete_self is set. In this case we
// know we need to do the deletion so just do it.
static inline void Delete(RefBase* reference) {
reference->Unlink();
if ((reference->RefCount() != 0) ||
(reference->_delete_self) ||
(reference->_finalize_ran)) {
delete reference;
} else {
// defer until finalizer runs as
// it may alread be queued
reference->_delete_self = true;
}
}
inline uint32_t Ref() {
return ++_refcount;
}
inline uint32_t Unref() {
if (_refcount == 0) {
return 0;
}
return --_refcount;
}
inline uint32_t RefCount() {
return _refcount;
}
protected:
inline void Finalize(bool is_env_teardown = false) override {
if (_finalize_callback != nullptr) {
_env->CallFinalizer(_finalize_callback, _finalize_data, _finalize_hint);
}
// this is safe because if a request to delete the reference
// is made in the finalize_callback it will defer deletion
// to this block and set _delete_self to true
if (_delete_self || is_env_teardown) {
Delete(this);
} else {
_finalize_ran = true;
}
}
private:
uint32_t _refcount;
bool _delete_self;
};
class Reference : public RefBase {
protected:
template <typename... Args>
Reference(napi_env env,
v8::Local<v8::Value> value,
Args&&... args)
: RefBase(env, std::forward<Args>(args)...),
_persistent(env->isolate, value) {
if (RefCount() == 0) {
_persistent.SetWeak(
this, FinalizeCallback, v8::WeakCallbackType::kParameter);
}
}
public:
static inline Reference* New(napi_env env,
v8::Local<v8::Value> value,
uint32_t initial_refcount,
bool delete_self,
napi_finalize finalize_callback = nullptr,
void* finalize_data = nullptr,
void* finalize_hint = nullptr) {
return new Reference(env,
value,
initial_refcount,
delete_self,
finalize_callback,
finalize_data,
finalize_hint);
}
inline uint32_t Ref() {
uint32_t refcount = RefBase::Ref();
if (refcount == 1) {
_persistent.ClearWeak();
}
return refcount;
}
inline uint32_t Unref() {
uint32_t old_refcount = RefCount();
uint32_t refcount = RefBase::Unref();
if (old_refcount == 1 && refcount == 0) {
_persistent.SetWeak(
this, FinalizeCallback, v8::WeakCallbackType::kParameter);
}
return refcount;
}
inline v8::Local<v8::Value> Get() {
if (_persistent.IsEmpty()) {
return v8::Local<v8::Value>();
} else {
return v8::Local<v8::Value>::New(_env->isolate, _persistent);
}
}
private:
// The N-API finalizer callback may make calls into the engine. V8's heap is
// not in a consistent state during the weak callback, and therefore it does
// not support calls back into it. However, it provides a mechanism for adding
// a finalizer which may make calls back into the engine by allowing us to
// attach such a second-pass finalizer from the first pass finalizer. Thus,
// we do that here to ensure that the N-API finalizer callback is free to call
// into the engine.
static void FinalizeCallback(const v8::WeakCallbackInfo<Reference>& data) {
Reference* reference = data.GetParameter();
// The reference must be reset during the first pass.
reference->_persistent.Reset();
data.SetSecondPassCallback(SecondPassCallback);
}
static void SecondPassCallback(const v8::WeakCallbackInfo<Reference>& data) {
data.GetParameter()->Finalize();
}
v8impl::Persistent<v8::Value> _persistent;
};
enum UnwrapAction {
KeepWrap,
RemoveWrap
};
inline static napi_status Unwrap(napi_env env,
napi_value js_object,
void** result,
UnwrapAction action) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, js_object);
if (action == KeepWrap) {
CHECK_ARG(env, result);
}
v8::Isolate* isolate = env->isolate;
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object);
RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg);
v8::Local<v8::Object> obj = value.As<v8::Object>();
auto val = obj->GetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper))
.ToLocalChecked();
RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg);
Reference* reference =
static_cast<v8impl::Reference*>(val.As<v8::External>()->Value());
if (result) {
*result = reference->Data();
}
if (action == RemoveWrap) {
CHECK(obj->DeletePrivate(context, NAPI_PRIVATE_KEY(context, wrapper))
.FromJust());
Reference::Delete(reference);
}
return GET_RETURN_STATUS(env);
}
//=== Function napi_callback wrapper =================================
// Use this data structure to associate callback data with each N-API function
// exposed to JavaScript. The structure is stored in a v8::External which gets
// passed into our callback wrapper. This reduces the performance impact of
// calling through N-API.
// Ref: benchmark/misc/function_call
// Discussion (incl. perf. data): https://github.com/nodejs/node/pull/21072
struct CallbackBundle {
napi_env env; // Necessary to invoke C++ NAPI callback
void* cb_data; // The user provided callback data
napi_callback function_or_getter;
napi_callback setter;
};
// Base class extended by classes that wrap V8 function and property callback
// info.
class CallbackWrapper {
public:
CallbackWrapper(napi_value this_arg, size_t args_length, void* data)
: _this(this_arg), _args_length(args_length), _data(data) {}
virtual napi_value GetNewTarget() = 0;
virtual void Args(napi_value* buffer, size_t bufferlength) = 0;
virtual void SetReturnValue(napi_value value) = 0;
napi_value This() { return _this; }
size_t ArgsLength() { return _args_length; }
void* Data() { return _data; }
protected:
const napi_value _this;
const size_t _args_length;
void* _data;
};
template <typename Info, napi_callback CallbackBundle::*FunctionField>
class CallbackWrapperBase : public CallbackWrapper {
public:
CallbackWrapperBase(const Info& cbinfo, const size_t args_length)
: CallbackWrapper(JsValueFromV8LocalValue(cbinfo.This()),
args_length,
nullptr),
_cbinfo(cbinfo) {
_bundle = reinterpret_cast<CallbackBundle*>(
v8::Local<v8::External>::Cast(cbinfo.Data())->Value());
_data = _bundle->cb_data;
}
napi_value GetNewTarget() override { return nullptr; }
protected:
void InvokeCallback() {
napi_callback_info cbinfo_wrapper = reinterpret_cast<napi_callback_info>(
static_cast<CallbackWrapper*>(this));
// All other pointers we need are stored in `_bundle`
napi_env env = _bundle->env;
napi_callback cb = _bundle->*FunctionField;
napi_value result;
env->CallIntoModule([&](napi_env env) {
result = cb(env, cbinfo_wrapper);
});
if (result != nullptr) {
this->SetReturnValue(result);
}
}
const Info& _cbinfo;
CallbackBundle* _bundle;
};
class FunctionCallbackWrapper
: public CallbackWrapperBase<v8::FunctionCallbackInfo<v8::Value>,
&CallbackBundle::function_or_getter> {
public:
static void Invoke(const v8::FunctionCallbackInfo<v8::Value>& info) {
FunctionCallbackWrapper cbwrapper(info);
cbwrapper.InvokeCallback();
}
explicit FunctionCallbackWrapper(
const v8::FunctionCallbackInfo<v8::Value>& cbinfo)
: CallbackWrapperBase(cbinfo, cbinfo.Length()) {}
napi_value GetNewTarget() override {
if (_cbinfo.IsConstructCall()) {
return v8impl::JsValueFromV8LocalValue(_cbinfo.NewTarget());
} else {
return nullptr;
}
}
/*virtual*/
void Args(napi_value* buffer, size_t buffer_length) override {
size_t i = 0;
size_t min = std::min(buffer_length, _args_length);
for (; i < min; i += 1) {
buffer[i] = v8impl::JsValueFromV8LocalValue(_cbinfo[i]);
}
if (i < buffer_length) {
napi_value undefined =
v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate()));
for (; i < buffer_length; i += 1) {
buffer[i] = undefined;
}
}
}
/*virtual*/
void SetReturnValue(napi_value value) override {
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
_cbinfo.GetReturnValue().Set(val);
}
};
class GetterCallbackWrapper
: public CallbackWrapperBase<v8::PropertyCallbackInfo<v8::Value>,
&CallbackBundle::function_or_getter> {
public:
static void Invoke(v8::Local<v8::Name> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
GetterCallbackWrapper cbwrapper(info);
cbwrapper.InvokeCallback();
}
explicit GetterCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Value>& cbinfo)
: CallbackWrapperBase(cbinfo, 0) {}
/*virtual*/
void Args(napi_value* buffer, size_t buffer_length) override {
if (buffer_length > 0) {
napi_value undefined =
v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate()));
for (size_t i = 0; i < buffer_length; i += 1) {
buffer[i] = undefined;
}
}
}
/*virtual*/
void SetReturnValue(napi_value value) override {
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
_cbinfo.GetReturnValue().Set(val);
}
};
class SetterCallbackWrapper
: public CallbackWrapperBase<v8::PropertyCallbackInfo<void>,
&CallbackBundle::setter> {
public:
static void Invoke(v8::Local<v8::Name> property,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<void>& info) {
SetterCallbackWrapper cbwrapper(info, value);
cbwrapper.InvokeCallback();
}
SetterCallbackWrapper(const v8::PropertyCallbackInfo<void>& cbinfo,
const v8::Local<v8::Value>& value)
: CallbackWrapperBase(cbinfo, 1), _value(value) {}
/*virtual*/
void Args(napi_value* buffer, size_t buffer_length) override {
if (buffer_length > 0) {
buffer[0] = v8impl::JsValueFromV8LocalValue(_value);
if (buffer_length > 1) {
napi_value undefined = v8impl::JsValueFromV8LocalValue(
v8::Undefined(_cbinfo.GetIsolate()));
for (size_t i = 1; i < buffer_length; i += 1) {
buffer[i] = undefined;
}
}
}
}
/*virtual*/
void SetReturnValue(napi_value value) override {
// Ignore any value returned from a setter callback.
}
private:
const v8::Local<v8::Value>& _value;
};
static void DeleteCallbackBundle(napi_env env, void* data, void* hint) {
CallbackBundle* bundle = static_cast<CallbackBundle*>(data);
delete bundle;
}
// Creates an object to be made available to the static function callback
// wrapper, used to retrieve the native callback function and data pointer.
static
v8::Local<v8::Value> CreateFunctionCallbackData(napi_env env,
napi_callback cb,
void* data) {
CallbackBundle* bundle = new CallbackBundle();
bundle->function_or_getter = cb;
bundle->cb_data = data;
bundle->env = env;
v8::Local<v8::Value> cbdata = v8::External::New(env->isolate, bundle);
Reference::New(env, cbdata, 0, true, DeleteCallbackBundle, bundle, nullptr);
return cbdata;
}
enum WrapType {
retrievable,
anonymous
};
template <WrapType wrap_type>
inline napi_status Wrap(napi_env env,
napi_value js_object,
void* native_object,
napi_finalize finalize_cb,
void* finalize_hint,
napi_ref* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, js_object);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object);
RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg);
v8::Local<v8::Object> obj = value.As<v8::Object>();
if (wrap_type == retrievable) {
// If we've already wrapped this object, we error out.
RETURN_STATUS_IF_FALSE(env,
!obj->HasPrivate(context, NAPI_PRIVATE_KEY(context, wrapper))
.FromJust(),
napi_invalid_arg);
} else if (wrap_type == anonymous) {
// If no finalize callback is provided, we error out.
CHECK_ARG(env, finalize_cb);
}
v8impl::Reference* reference = nullptr;
if (result != nullptr) {
// The returned reference should be deleted via napi_delete_reference()
// ONLY in response to the finalize callback invocation. (If it is deleted
// before then, then the finalize callback will never be invoked.)
// Therefore a finalize callback is required when returning a reference.
CHECK_ARG(env, finalize_cb);
reference = v8impl::Reference::New(
env, obj, 0, false, finalize_cb, native_object, finalize_hint);
*result = reinterpret_cast<napi_ref>(reference);
} else {
// Create a self-deleting reference.
reference = v8impl::Reference::New(env, obj, 0, true, finalize_cb,
native_object, finalize_cb == nullptr ? nullptr : finalize_hint);
}
if (wrap_type == retrievable) {
CHECK(obj->SetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper),
v8::External::New(env->isolate, reference)).FromJust());
}
return GET_RETURN_STATUS(env);
}
} // end of anonymous namespace
} // end of namespace v8impl
// Warning: Keep in-sync with napi_status enum
static
const char* error_messages[] = {nullptr,
"Invalid argument",
"An object was expected",
"A string was expected",
"A string or symbol was expected",
"A function was expected",
"A number was expected",
"A boolean was expected",
"An array was expected",
"Unknown failure",
"An exception is pending",
"The async work item was cancelled",
"napi_escape_handle already called on scope",
"Invalid handle scope usage",
"Invalid callback scope usage",
"Thread-safe function queue is full",
"Thread-safe function handle is closing",
"A bigint was expected",
"A date was expected",
"An arraybuffer was expected",
"A detachable arraybuffer was expected",
"Main thread would deadlock",
};
napi_status napi_get_last_error_info(napi_env env,
const napi_extended_error_info** result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
// The value of the constant below must be updated to reference the last
// message in the `napi_status` enum each time a new error message is added.
// We don't have a napi_status_last as this would result in an ABI
// change each time a message was added.
const int last_status = napi_would_deadlock;
static_assert(
NAPI_ARRAYSIZE(error_messages) == last_status + 1,
"Count of error messages must match count of error values");
CHECK_LE(env->last_error.error_code, last_status);
// Wait until someone requests the last error information to fetch the error
// message string
env->last_error.error_message =
error_messages[env->last_error.error_code];
*result = &(env->last_error);
return napi_ok;
}
napi_status napi_create_function(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* callback_data,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
CHECK_ARG(env, cb);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::Function> return_value;
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Value> cbdata =
v8impl::CreateFunctionCallbackData(env, cb, callback_data);
RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure);
v8::Local<v8::Context> context = env->context();
v8::MaybeLocal<v8::Function> maybe_function =
v8::Function::New(context,
v8impl::FunctionCallbackWrapper::Invoke,
cbdata);
CHECK_MAYBE_EMPTY(env, maybe_function, napi_generic_failure);
return_value = scope.Escape(maybe_function.ToLocalChecked());
if (utf8name != nullptr) {
v8::Local<v8::String> name_string;
CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length);
return_value->SetName(name_string);
}
*result = v8impl::JsValueFromV8LocalValue(return_value);
return GET_RETURN_STATUS(env);
}
napi_status napi_define_class(napi_env env,
const char* utf8name,
size_t length,
napi_callback constructor,
void* callback_data,
size_t property_count,
const napi_property_descriptor* properties,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
CHECK_ARG(env, constructor);
if (property_count > 0) {
CHECK_ARG(env, properties);
}
v8::Isolate* isolate = env->isolate;
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Value> cbdata =
v8impl::CreateFunctionCallbackData(env, constructor, callback_data);
RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure);
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(
isolate, v8impl::FunctionCallbackWrapper::Invoke, cbdata);
v8::Local<v8::String> name_string;
CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length);
tpl->SetClassName(name_string);
size_t static_property_count = 0;
for (size_t i = 0; i < property_count; i++) {
const napi_property_descriptor* p = properties + i;
if ((p->attributes & napi_static) != 0) {
// Static properties are handled separately below.
static_property_count++;
continue;
}
v8::Local<v8::Name> property_name;
napi_status status =
v8impl::V8NameFromPropertyDescriptor(env, p, &property_name);
if (status != napi_ok) {
return napi_set_last_error(env, status);
}
v8::PropertyAttribute attributes =
v8impl::V8PropertyAttributesFromDescriptor(p);
// This code is similar to that in napi_define_properties(); the
// difference is it applies to a template instead of an object,
// and preferred PropertyAttribute for lack of PropertyDescriptor
// support on ObjectTemplate.
if (p->getter != nullptr || p->setter != nullptr) {
v8::Local<v8::FunctionTemplate> getter_tpl;
v8::Local<v8::FunctionTemplate> setter_tpl;
if (p->getter != nullptr) {
v8::Local<v8::Value> getter_data =
v8impl::CreateFunctionCallbackData(env, p->getter, p->data);
getter_tpl = v8::FunctionTemplate::New(
isolate, v8impl::FunctionCallbackWrapper::Invoke, getter_data);
}
if (p->setter != nullptr) {
v8::Local<v8::Value> setter_data =
v8impl::CreateFunctionCallbackData(env, p->setter, p->data);
setter_tpl = v8::FunctionTemplate::New(
isolate, v8impl::FunctionCallbackWrapper::Invoke, setter_data);
}
tpl->PrototypeTemplate()->SetAccessorProperty(
property_name,
getter_tpl,
setter_tpl,
attributes,
v8::AccessControl::DEFAULT);
} else if (p->method != nullptr) {
v8::Local<v8::Value> cbdata =
v8impl::CreateFunctionCallbackData(env, p->method, p->data);
RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure);
v8::Local<v8::FunctionTemplate> t =
v8::FunctionTemplate::New(isolate,
v8impl::FunctionCallbackWrapper::Invoke,
cbdata,
v8::Signature::New(isolate, tpl));
tpl->PrototypeTemplate()->Set(property_name, t, attributes);
} else {
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(p->value);
tpl->PrototypeTemplate()->Set(property_name, value, attributes);
}
}
v8::Local<v8::Context> context = env->context();
*result = v8impl::JsValueFromV8LocalValue(
scope.Escape(tpl->GetFunction(context).ToLocalChecked()));
if (static_property_count > 0) {
std::vector<napi_property_descriptor> static_descriptors;
static_descriptors.reserve(static_property_count);
for (size_t i = 0; i < property_count; i++) {
const napi_property_descriptor* p = properties + i;
if ((p->attributes & napi_static) != 0) {
static_descriptors.push_back(*p);
}
}
napi_status status =
napi_define_properties(env,
*result,
static_descriptors.size(),
static_descriptors.data());
if (status != napi_ok) return status;
}
return GET_RETURN_STATUS(env);
}
napi_status napi_get_property_names(napi_env env,
napi_value object,
napi_value* result) {
return napi_get_all_property_names(
env,
object,
napi_key_include_prototypes,
static_cast<napi_key_filter>(napi_key_enumerable |
napi_key_skip_symbols),
napi_key_numbers_to_strings,
result);
}
napi_status napi_get_all_property_names(napi_env env,
napi_value object,
napi_key_collection_mode key_mode,
napi_key_filter key_filter,
napi_key_conversion key_conversion,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::PropertyFilter filter = v8::PropertyFilter::ALL_PROPERTIES;
if (key_filter & napi_key_writable) {
filter =
static_cast<v8::PropertyFilter>(filter |
v8::PropertyFilter::ONLY_WRITABLE);
}
if (key_filter & napi_key_enumerable) {
filter =
static_cast<v8::PropertyFilter>(filter |
v8::PropertyFilter::ONLY_ENUMERABLE);
}
if (key_filter & napi_key_configurable) {
filter =
static_cast<v8::PropertyFilter>(filter |
v8::PropertyFilter::ONLY_WRITABLE);
}
if (key_filter & napi_key_skip_strings) {
filter =
static_cast<v8::PropertyFilter>(filter |
v8::PropertyFilter::SKIP_STRINGS);
}
if (key_filter & napi_key_skip_symbols) {
filter =
static_cast<v8::PropertyFilter>(filter |
v8::PropertyFilter::SKIP_SYMBOLS);
}
v8::KeyCollectionMode collection_mode;
v8::KeyConversionMode conversion_mode;
switch (key_mode) {
case napi_key_include_prototypes:
collection_mode = v8::KeyCollectionMode::kIncludePrototypes;
break;
case napi_key_own_only:
collection_mode = v8::KeyCollectionMode::kOwnOnly;
break;
default:
return napi_set_last_error(env, napi_invalid_arg);
}
switch (key_conversion) {
case napi_key_keep_numbers:
conversion_mode = v8::KeyConversionMode::kKeepNumbers;
break;
case napi_key_numbers_to_strings:
conversion_mode = v8::KeyConversionMode::kConvertToString;
break;
default:
return napi_set_last_error(env, napi_invalid_arg);
}
v8::MaybeLocal<v8::Array> maybe_all_propertynames =
obj->GetPropertyNames(context,
collection_mode,
filter,
v8::IndexFilter::kIncludeIndices,
conversion_mode);
CHECK_MAYBE_EMPTY_WITH_PREAMBLE(
env, maybe_all_propertynames, napi_generic_failure);
*result =
v8impl::JsValueFromV8LocalValue(maybe_all_propertynames.ToLocalChecked());
return GET_RETURN_STATUS(env);
}
napi_status napi_set_property(napi_env env,
napi_value object,
napi_value key,
napi_value value) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, key);
CHECK_ARG(env, value);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
v8::Maybe<bool> set_maybe = obj->Set(context, k, val);
RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure);
return GET_RETURN_STATUS(env);
}
napi_status napi_has_property(napi_env env,
napi_value object,
napi_value key,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
CHECK_ARG(env, key);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key);
v8::Maybe<bool> has_maybe = obj->Has(context, k);
CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure);
*result = has_maybe.FromMaybe(false);
return GET_RETURN_STATUS(env);
}
napi_status napi_get_property(napi_env env,
napi_value object,
napi_value key,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, key);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key);
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
auto get_maybe = obj->Get(context, k);
CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure);
v8::Local<v8::Value> val = get_maybe.ToLocalChecked();
*result = v8impl::JsValueFromV8LocalValue(val);
return GET_RETURN_STATUS(env);
}
napi_status napi_delete_property(napi_env env,
napi_value object,
napi_value key,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, key);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key);
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Maybe<bool> delete_maybe = obj->Delete(context, k);
CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure);
if (result != nullptr)
*result = delete_maybe.FromMaybe(false);
return GET_RETURN_STATUS(env);
}
napi_status napi_has_own_property(napi_env env,
napi_value object,
napi_value key,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, key);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key);
RETURN_STATUS_IF_FALSE(env, k->IsName(), napi_name_expected);
v8::Maybe<bool> has_maybe = obj->HasOwnProperty(context, k.As<v8::Name>());
CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure);
*result = has_maybe.FromMaybe(false);
return GET_RETURN_STATUS(env);
}
napi_status napi_set_named_property(napi_env env,
napi_value object,
const char* utf8name,
napi_value value) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, value);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Name> key;
CHECK_NEW_FROM_UTF8(env, key, utf8name);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
v8::Maybe<bool> set_maybe = obj->Set(context, key, val);
RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure);
return GET_RETURN_STATUS(env);
}
napi_status napi_has_named_property(napi_env env,
napi_value object,
const char* utf8name,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Name> key;
CHECK_NEW_FROM_UTF8(env, key, utf8name);
v8::Maybe<bool> has_maybe = obj->Has(context, key);
CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure);
*result = has_maybe.FromMaybe(false);
return GET_RETURN_STATUS(env);
}
napi_status napi_get_named_property(napi_env env,
napi_value object,
const char* utf8name,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Name> key;
CHECK_NEW_FROM_UTF8(env, key, utf8name);
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
auto get_maybe = obj->Get(context, key);
CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure);
v8::Local<v8::Value> val = get_maybe.ToLocalChecked();
*result = v8impl::JsValueFromV8LocalValue(val);
return GET_RETURN_STATUS(env);
}
napi_status napi_set_element(napi_env env,
napi_value object,
uint32_t index,
napi_value value) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, value);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
auto set_maybe = obj->Set(context, index, val);
RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure);
return GET_RETURN_STATUS(env);
}
napi_status napi_has_element(napi_env env,
napi_value object,
uint32_t index,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Maybe<bool> has_maybe = obj->Has(context, index);
CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure);
*result = has_maybe.FromMaybe(false);
return GET_RETURN_STATUS(env);
}
napi_status napi_get_element(napi_env env,
napi_value object,
uint32_t index,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
auto get_maybe = obj->Get(context, index);
CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(get_maybe.ToLocalChecked());
return GET_RETURN_STATUS(env);
}
napi_status napi_delete_element(napi_env env,
napi_value object,
uint32_t index,
bool* result) {
NAPI_PREAMBLE(env);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Maybe<bool> delete_maybe = obj->Delete(context, index);
CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure);
if (result != nullptr)
*result = delete_maybe.FromMaybe(false);
return GET_RETURN_STATUS(env);
}
napi_status napi_define_properties(napi_env env,
napi_value object,
size_t property_count,
const napi_property_descriptor* properties) {
NAPI_PREAMBLE(env);
if (property_count > 0) {
CHECK_ARG(env, properties);
}
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
for (size_t i = 0; i < property_count; i++) {
const napi_property_descriptor* p = &properties[i];
v8::Local<v8::Name> property_name;
napi_status status =
v8impl::V8NameFromPropertyDescriptor(env, p, &property_name);
if (status != napi_ok) {
return napi_set_last_error(env, status);
}
if (p->getter != nullptr || p->setter != nullptr) {
v8::Local<v8::Value> local_getter;
v8::Local<v8::Value> local_setter;
if (p->getter != nullptr) {
v8::Local<v8::Value> getter_data =
v8impl::CreateFunctionCallbackData(env, p->getter, p->data);
CHECK_MAYBE_EMPTY(env, getter_data, napi_generic_failure);
v8::MaybeLocal<v8::Function> maybe_getter =
v8::Function::New(context,
v8impl::FunctionCallbackWrapper::Invoke,
getter_data);
CHECK_MAYBE_EMPTY(env, maybe_getter, napi_generic_failure);
local_getter = maybe_getter.ToLocalChecked();
}
if (p->setter != nullptr) {
v8::Local<v8::Value> setter_data =
v8impl::CreateFunctionCallbackData(env, p->setter, p->data);
CHECK_MAYBE_EMPTY(env, setter_data, napi_generic_failure);
v8::MaybeLocal<v8::Function> maybe_setter =
v8::Function::New(context,
v8impl::FunctionCallbackWrapper::Invoke,
setter_data);
CHECK_MAYBE_EMPTY(env, maybe_setter, napi_generic_failure);
local_setter = maybe_setter.ToLocalChecked();
}
v8::PropertyDescriptor descriptor(local_getter, local_setter);
descriptor.set_enumerable((p->attributes & napi_enumerable) != 0);
descriptor.set_configurable((p->attributes & napi_configurable) != 0);
auto define_maybe = obj->DefineProperty(context,
property_name,
descriptor);
if (!define_maybe.FromMaybe(false)) {
return napi_set_last_error(env, napi_invalid_arg);
}
} else if (p->method != nullptr) {
v8::Local<v8::Value> cbdata =
v8impl::CreateFunctionCallbackData(env, p->method, p->data);
CHECK_MAYBE_EMPTY(env, cbdata, napi_generic_failure);
v8::MaybeLocal<v8::Function> maybe_fn =
v8::Function::New(context,
v8impl::FunctionCallbackWrapper::Invoke,
cbdata);
CHECK_MAYBE_EMPTY(env, maybe_fn, napi_generic_failure);
v8::PropertyDescriptor descriptor(maybe_fn.ToLocalChecked(),
(p->attributes & napi_writable) != 0);
descriptor.set_enumerable((p->attributes & napi_enumerable) != 0);
descriptor.set_configurable((p->attributes & napi_configurable) != 0);
auto define_maybe = obj->DefineProperty(context,
property_name,
descriptor);
if (!define_maybe.FromMaybe(false)) {
return napi_set_last_error(env, napi_generic_failure);
}
} else {
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(p->value);
v8::PropertyDescriptor descriptor(value,
(p->attributes & napi_writable) != 0);
descriptor.set_enumerable((p->attributes & napi_enumerable) != 0);
descriptor.set_configurable((p->attributes & napi_configurable) != 0);
auto define_maybe =
obj->DefineProperty(context, property_name, descriptor);
if (!define_maybe.FromMaybe(false)) {
return napi_set_last_error(env, napi_invalid_arg);
}
}
}
return GET_RETURN_STATUS(env);
}
napi_status napi_is_array(napi_env env, napi_value value, bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
*result = val->IsArray();
return napi_clear_last_error(env);
}
napi_status napi_get_array_length(napi_env env,
napi_value value,
uint32_t* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsArray(), napi_array_expected);
v8::Local<v8::Array> arr = val.As<v8::Array>();
*result = arr->Length();
return GET_RETURN_STATUS(env);
}
napi_status napi_strict_equals(napi_env env,
napi_value lhs,
napi_value rhs,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, lhs);
CHECK_ARG(env, rhs);
CHECK_ARG(env, result);
v8::Local<v8::Value> a = v8impl::V8LocalValueFromJsValue(lhs);
v8::Local<v8::Value> b = v8impl::V8LocalValueFromJsValue(rhs);
*result = a->StrictEquals(b);
return GET_RETURN_STATUS(env);
}
napi_status napi_get_prototype(napi_env env,
napi_value object,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> obj;
CHECK_TO_OBJECT(env, context, obj, object);
v8::Local<v8::Value> val = obj->GetPrototype();
*result = v8impl::JsValueFromV8LocalValue(val);
return GET_RETURN_STATUS(env);
}
napi_status napi_create_object(napi_env env, napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Object::New(env->isolate));
return napi_clear_last_error(env);
}
napi_status napi_create_array(napi_env env, napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Array::New(env->isolate));
return napi_clear_last_error(env);
}
napi_status napi_create_array_with_length(napi_env env,
size_t length,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Array::New(env->isolate, length));
return napi_clear_last_error(env);
}
napi_status napi_create_string_latin1(napi_env env,
const char* str,
size_t length,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
RETURN_STATUS_IF_FALSE(env,
(length == NAPI_AUTO_LENGTH) || length <= INT_MAX,
napi_invalid_arg);
auto isolate = env->isolate;
auto str_maybe =
v8::String::NewFromOneByte(isolate,
reinterpret_cast<const uint8_t*>(str),
v8::NewStringType::kNormal,
length);
CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked());
return napi_clear_last_error(env);
}
napi_status napi_create_string_utf8(napi_env env,
const char* str,
size_t length,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
RETURN_STATUS_IF_FALSE(env,
(length == NAPI_AUTO_LENGTH) || length <= INT_MAX,
napi_invalid_arg);
auto isolate = env->isolate;
auto str_maybe =
v8::String::NewFromUtf8(isolate,
str,
v8::NewStringType::kNormal,
static_cast<int>(length));
CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked());
return napi_clear_last_error(env);
}
napi_status napi_create_string_utf16(napi_env env,
const char16_t* str,
size_t length,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
RETURN_STATUS_IF_FALSE(env,
(length == NAPI_AUTO_LENGTH) || length <= INT_MAX,
napi_invalid_arg);
auto isolate = env->isolate;
auto str_maybe =
v8::String::NewFromTwoByte(isolate,
reinterpret_cast<const uint16_t*>(str),
v8::NewStringType::kNormal,
length);
CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked());
return napi_clear_last_error(env);
}
napi_status napi_create_double(napi_env env,
double value,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Number::New(env->isolate, value));
return napi_clear_last_error(env);
}
napi_status napi_create_int32(napi_env env,
int32_t value,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Integer::New(env->isolate, value));
return napi_clear_last_error(env);
}
napi_status napi_create_uint32(napi_env env,
uint32_t value,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Integer::NewFromUnsigned(env->isolate, value));
return napi_clear_last_error(env);
}
napi_status napi_create_int64(napi_env env,
int64_t value,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Number::New(env->isolate, static_cast<double>(value)));
return napi_clear_last_error(env);
}
napi_status napi_create_bigint_int64(napi_env env,
int64_t value,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::BigInt::New(env->isolate, value));
return napi_clear_last_error(env);
}
napi_status napi_create_bigint_uint64(napi_env env,
uint64_t value,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::BigInt::NewFromUnsigned(env->isolate, value));
return napi_clear_last_error(env);
}
napi_status napi_create_bigint_words(napi_env env,
int sign_bit,
size_t word_count,
const uint64_t* words,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, words);
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
RETURN_STATUS_IF_FALSE(
env, word_count <= INT_MAX, napi_invalid_arg);
v8::MaybeLocal<v8::BigInt> b = v8::BigInt::NewFromWords(
context, sign_bit, word_count, words);
CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, b, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(b.ToLocalChecked());
return GET_RETURN_STATUS(env);
}
napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
v8::Isolate* isolate = env->isolate;
if (value) {
*result = v8impl::JsValueFromV8LocalValue(v8::True(isolate));
} else {
*result = v8impl::JsValueFromV8LocalValue(v8::False(isolate));
}
return napi_clear_last_error(env);
}
napi_status napi_create_symbol(napi_env env,
napi_value description,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
v8::Isolate* isolate = env->isolate;
if (description == nullptr) {
*result = v8impl::JsValueFromV8LocalValue(v8::Symbol::New(isolate));
} else {
v8::Local<v8::Value> desc = v8impl::V8LocalValueFromJsValue(description);
RETURN_STATUS_IF_FALSE(env, desc->IsString(), napi_string_expected);
*result = v8impl::JsValueFromV8LocalValue(
v8::Symbol::New(isolate, desc.As<v8::String>()));
}
return napi_clear_last_error(env);
}
static inline napi_status set_error_code(napi_env env,
v8::Local<v8::Value> error,
napi_value code,
const char* code_cstring) {
if ((code != nullptr) || (code_cstring != nullptr)) {
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Object> err_object = error.As<v8::Object>();
v8::Local<v8::Value> code_value = v8impl::V8LocalValueFromJsValue(code);
if (code != nullptr) {
code_value = v8impl::V8LocalValueFromJsValue(code);
RETURN_STATUS_IF_FALSE(env, code_value->IsString(), napi_string_expected);
} else {
CHECK_NEW_FROM_UTF8(env, code_value, code_cstring);
}
v8::Local<v8::Name> code_key;
CHECK_NEW_FROM_UTF8(env, code_key, "code");
v8::Maybe<bool> set_maybe = err_object->Set(context, code_key, code_value);
RETURN_STATUS_IF_FALSE(env,
set_maybe.FromMaybe(false),
napi_generic_failure);
}
return napi_ok;
}
napi_status napi_create_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, msg);
CHECK_ARG(env, result);
v8::Local<v8::Value> message_value = v8impl::V8LocalValueFromJsValue(msg);
RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected);
v8::Local<v8::Value> error_obj =
v8::Exception::Error(message_value.As<v8::String>());
napi_status status = set_error_code(env, error_obj, code, nullptr);
if (status != napi_ok) return status;
*result = v8impl::JsValueFromV8LocalValue(error_obj);
return napi_clear_last_error(env);
}
napi_status napi_create_type_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, msg);
CHECK_ARG(env, result);
v8::Local<v8::Value> message_value = v8impl::V8LocalValueFromJsValue(msg);
RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected);
v8::Local<v8::Value> error_obj =
v8::Exception::TypeError(message_value.As<v8::String>());
napi_status status = set_error_code(env, error_obj, code, nullptr);
if (status != napi_ok) return status;
*result = v8impl::JsValueFromV8LocalValue(error_obj);
return napi_clear_last_error(env);
}
napi_status napi_create_range_error(napi_env env,
napi_value code,
napi_value msg,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, msg);
CHECK_ARG(env, result);
v8::Local<v8::Value> message_value = v8impl::V8LocalValueFromJsValue(msg);
RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected);
v8::Local<v8::Value> error_obj =
v8::Exception::RangeError(message_value.As<v8::String>());
napi_status status = set_error_code(env, error_obj, code, nullptr);
if (status != napi_ok) return status;
*result = v8impl::JsValueFromV8LocalValue(error_obj);
return napi_clear_last_error(env);
}
napi_status napi_typeof(napi_env env,
napi_value value,
napi_valuetype* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> v = v8impl::V8LocalValueFromJsValue(value);
if (v->IsNumber()) {
*result = napi_number;
} else if (v->IsBigInt()) {
*result = napi_bigint;
} else if (v->IsString()) {
*result = napi_string;
} else if (v->IsFunction()) {
// This test has to come before IsObject because IsFunction
// implies IsObject
*result = napi_function;
} else if (v->IsExternal()) {
// This test has to come before IsObject because IsExternal
// implies IsObject
*result = napi_external;
} else if (v->IsObject()) {
*result = napi_object;
} else if (v->IsBoolean()) {
*result = napi_boolean;
} else if (v->IsUndefined()) {
*result = napi_undefined;
} else if (v->IsSymbol()) {
*result = napi_symbol;
} else if (v->IsNull()) {
*result = napi_null;
} else {
// Should not get here unless V8 has added some new kind of value.
return napi_set_last_error(env, napi_invalid_arg);
}
return napi_clear_last_error(env);
}
napi_status napi_get_undefined(napi_env env, napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Undefined(env->isolate));
return napi_clear_last_error(env);
}
napi_status napi_get_null(napi_env env, napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(
v8::Null(env->isolate));
return napi_clear_last_error(env);
}
// Gets all callback info in a single call. (Ugly, but faster.)
napi_status napi_get_cb_info(
napi_env env, // [in] NAPI environment handle
napi_callback_info cbinfo, // [in] Opaque callback-info handle
size_t* argc, // [in-out] Specifies the size of the provided argv array
// and receives the actual count of args.
napi_value* argv, // [out] Array of values
napi_value* this_arg, // [out] Receives the JS 'this' arg for the call
void** data) { // [out] Receives the data pointer for the callback.
CHECK_ENV(env);
CHECK_ARG(env, cbinfo);
v8impl::CallbackWrapper* info =
reinterpret_cast<v8impl::CallbackWrapper*>(cbinfo);
if (argv != nullptr) {
CHECK_ARG(env, argc);
info->Args(argv, *argc);
}
if (argc != nullptr) {
*argc = info->ArgsLength();
}
if (this_arg != nullptr) {
*this_arg = info->This();
}
if (data != nullptr) {
*data = info->Data();
}
return napi_clear_last_error(env);
}
napi_status napi_get_new_target(napi_env env,
napi_callback_info cbinfo,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, cbinfo);
CHECK_ARG(env, result);
v8impl::CallbackWrapper* info =
reinterpret_cast<v8impl::CallbackWrapper*>(cbinfo);
*result = info->GetNewTarget();
return napi_clear_last_error(env);
}
napi_status napi_call_function(napi_env env,
napi_value recv,
napi_value func,
size_t argc,
const napi_value* argv,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, recv);
if (argc > 0) {
CHECK_ARG(env, argv);
}
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Value> v8recv = v8impl::V8LocalValueFromJsValue(recv);
v8::Local<v8::Function> v8func;
CHECK_TO_FUNCTION(env, v8func, func);
auto maybe = v8func->Call(context, v8recv, argc,
reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)));
if (try_catch.HasCaught()) {
return napi_set_last_error(env, napi_pending_exception);
} else {
if (result != nullptr) {
CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked());
}
return napi_clear_last_error(env);
}
}
napi_status napi_get_global(napi_env env, napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsValueFromV8LocalValue(env->context()->Global());
return napi_clear_last_error(env);
}
napi_status napi_throw(napi_env env, napi_value error) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, error);
v8::Isolate* isolate = env->isolate;
isolate->ThrowException(v8impl::V8LocalValueFromJsValue(error));
// any VM calls after this point and before returning
// to the javascript invoker will fail
return napi_clear_last_error(env);
}
napi_status napi_throw_error(napi_env env,
const char* code,
const char* msg) {
NAPI_PREAMBLE(env);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::String> str;
CHECK_NEW_FROM_UTF8(env, str, msg);
v8::Local<v8::Value> error_obj = v8::Exception::Error(str);
napi_status status = set_error_code(env, error_obj, nullptr, code);
if (status != napi_ok) return status;
isolate->ThrowException(error_obj);
// any VM calls after this point and before returning
// to the javascript invoker will fail
return napi_clear_last_error(env);
}
napi_status napi_throw_type_error(napi_env env,
const char* code,
const char* msg) {
NAPI_PREAMBLE(env);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::String> str;
CHECK_NEW_FROM_UTF8(env, str, msg);
v8::Local<v8::Value> error_obj = v8::Exception::TypeError(str);
napi_status status = set_error_code(env, error_obj, nullptr, code);
if (status != napi_ok) return status;
isolate->ThrowException(error_obj);
// any VM calls after this point and before returning
// to the javascript invoker will fail
return napi_clear_last_error(env);
}
napi_status napi_throw_range_error(napi_env env,
const char* code,
const char* msg) {
NAPI_PREAMBLE(env);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::String> str;
CHECK_NEW_FROM_UTF8(env, str, msg);
v8::Local<v8::Value> error_obj = v8::Exception::RangeError(str);
napi_status status = set_error_code(env, error_obj, nullptr, code);
if (status != napi_ok) return status;
isolate->ThrowException(error_obj);
// any VM calls after this point and before returning
// to the javascript invoker will fail
return napi_clear_last_error(env);
}
napi_status napi_is_error(napi_env env, napi_value value, bool* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot
// throw JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
*result = val->IsNativeError();
return napi_clear_last_error(env);
}
napi_status napi_get_value_double(napi_env env,
napi_value value,
double* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected);
*result = val.As<v8::Number>()->Value();
return napi_clear_last_error(env);
}
napi_status napi_get_value_int32(napi_env env,
napi_value value,
int32_t* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
if (val->IsInt32()) {
*result = val.As<v8::Int32>()->Value();
} else {
RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected);
// Empty context: https://github.com/nodejs/node/issues/14379
v8::Local<v8::Context> context;
*result = val->Int32Value(context).FromJust();
}
return napi_clear_last_error(env);
}
napi_status napi_get_value_uint32(napi_env env,
napi_value value,
uint32_t* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
if (val->IsUint32()) {
*result = val.As<v8::Uint32>()->Value();
} else {
RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected);
// Empty context: https://github.com/nodejs/node/issues/14379
v8::Local<v8::Context> context;
*result = val->Uint32Value(context).FromJust();
}
return napi_clear_last_error(env);
}
napi_status napi_get_value_int64(napi_env env,
napi_value value,
int64_t* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
// This is still a fast path very likely to be taken.
if (val->IsInt32()) {
*result = val.As<v8::Int32>()->Value();
return napi_clear_last_error(env);
}
RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected);
// v8::Value::IntegerValue() converts NaN, +Inf, and -Inf to INT64_MIN,
// inconsistent with v8::Value::Int32Value() which converts those values to 0.
// Special-case all non-finite values to match that behavior.
double doubleValue = val.As<v8::Number>()->Value();
if (std::isfinite(doubleValue)) {
// Empty context: https://github.com/nodejs/node/issues/14379
v8::Local<v8::Context> context;
*result = val->IntegerValue(context).FromJust();
} else {
*result = 0;
}
return napi_clear_last_error(env);
}
napi_status napi_get_value_bigint_int64(napi_env env,
napi_value value,
int64_t* result,
bool* lossless) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
CHECK_ARG(env, lossless);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), napi_bigint_expected);
*result = val.As<v8::BigInt>()->Int64Value(lossless);
return napi_clear_last_error(env);
}
napi_status napi_get_value_bigint_uint64(napi_env env,
napi_value value,
uint64_t* result,
bool* lossless) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
CHECK_ARG(env, lossless);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), napi_bigint_expected);
*result = val.As<v8::BigInt>()->Uint64Value(lossless);
return napi_clear_last_error(env);
}
napi_status napi_get_value_bigint_words(napi_env env,
napi_value value,
int* sign_bit,
size_t* word_count,
uint64_t* words) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, word_count);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), napi_bigint_expected);
v8::Local<v8::BigInt> big = val.As<v8::BigInt>();
int word_count_int = *word_count;
if (sign_bit == nullptr && words == nullptr) {
word_count_int = big->WordCount();
} else {
CHECK_ARG(env, sign_bit);
CHECK_ARG(env, words);
big->ToWordsArray(sign_bit, &word_count_int, words);
}
*word_count = word_count_int;
return napi_clear_last_error(env);
}
napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsBoolean(), napi_boolean_expected);
*result = val.As<v8::Boolean>()->Value();
return napi_clear_last_error(env);
}
// Copies a JavaScript string into a LATIN-1 string buffer. The result is the
// number of bytes (excluding the null terminator) copied into buf.
// A sufficient buffer size should be greater than the length of string,
// reserving space for null terminator.
// If bufsize is insufficient, the string will be truncated and null terminated.
// If buf is NULL, this method returns the length of the string (in bytes)
// via the result parameter.
// The result argument is optional unless buf is NULL.
napi_status napi_get_value_string_latin1(napi_env env,
napi_value value,
char* buf,
size_t bufsize,
size_t* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected);
if (!buf) {
CHECK_ARG(env, result);
*result = val.As<v8::String>()->Length();
} else if (bufsize != 0) {
int copied =
val.As<v8::String>()->WriteOneByte(env->isolate,
reinterpret_cast<uint8_t*>(buf),
0,
bufsize - 1,
v8::String::NO_NULL_TERMINATION);
buf[copied] = '\0';
if (result != nullptr) {
*result = copied;
}
} else if (result != nullptr) {
*result = 0;
}
return napi_clear_last_error(env);
}
// Copies a JavaScript string into a UTF-8 string buffer. The result is the
// number of bytes (excluding the null terminator) copied into buf.
// A sufficient buffer size should be greater than the length of string,
// reserving space for null terminator.
// If bufsize is insufficient, the string will be truncated and null terminated.
// If buf is NULL, this method returns the length of the string (in bytes)
// via the result parameter.
// The result argument is optional unless buf is NULL.
napi_status napi_get_value_string_utf8(napi_env env,
napi_value value,
char* buf,
size_t bufsize,
size_t* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected);
if (!buf) {
CHECK_ARG(env, result);
*result = val.As<v8::String>()->Utf8Length(env->isolate);
} else if (bufsize != 0) {
int copied = val.As<v8::String>()->WriteUtf8(
env->isolate,
buf,
bufsize - 1,
nullptr,
v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION);
buf[copied] = '\0';
if (result != nullptr) {
*result = copied;
}
} else if (result != nullptr) {
*result = 0;
}
return napi_clear_last_error(env);
}
// Copies a JavaScript string into a UTF-16 string buffer. The result is the
// number of 2-byte code units (excluding the null terminator) copied into buf.
// A sufficient buffer size should be greater than the length of string,
// reserving space for null terminator.
// If bufsize is insufficient, the string will be truncated and null terminated.
// If buf is NULL, this method returns the length of the string (in 2-byte
// code units) via the result parameter.
// The result argument is optional unless buf is NULL.
napi_status napi_get_value_string_utf16(napi_env env,
napi_value value,
char16_t* buf,
size_t bufsize,
size_t* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected);
if (!buf) {
CHECK_ARG(env, result);
// V8 assumes UTF-16 length is the same as the number of characters.
*result = val.As<v8::String>()->Length();
} else if (bufsize != 0) {
int copied = val.As<v8::String>()->Write(env->isolate,
reinterpret_cast<uint16_t*>(buf),
0,
bufsize - 1,
v8::String::NO_NULL_TERMINATION);
buf[copied] = '\0';
if (result != nullptr) {
*result = copied;
}
} else if (result != nullptr) {
*result = 0;
}
return napi_clear_last_error(env);
}
napi_status napi_coerce_to_bool(napi_env env,
napi_value value,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::Boolean> b =
v8impl::V8LocalValueFromJsValue(value)->ToBoolean(isolate);
*result = v8impl::JsValueFromV8LocalValue(b);
return GET_RETURN_STATUS(env);
}
#define GEN_COERCE_FUNCTION(UpperCaseName, MixedCaseName, LowerCaseName) \
napi_status napi_coerce_to_##LowerCaseName(napi_env env, \
napi_value value, \
napi_value* result) { \
NAPI_PREAMBLE(env); \
CHECK_ARG(env, value); \
CHECK_ARG(env, result); \
\
v8::Local<v8::Context> context = env->context(); \
v8::Local<v8::MixedCaseName> str; \
\
CHECK_TO_##UpperCaseName(env, context, str, value); \
\
*result = v8impl::JsValueFromV8LocalValue(str); \
return GET_RETURN_STATUS(env); \
}
GEN_COERCE_FUNCTION(NUMBER, Number, number)
GEN_COERCE_FUNCTION(OBJECT, Object, object)
GEN_COERCE_FUNCTION(STRING, String, string)
#undef GEN_COERCE_FUNCTION
napi_status napi_wrap(napi_env env,
napi_value js_object,
void* native_object,
napi_finalize finalize_cb,
void* finalize_hint,
napi_ref* result) {
return v8impl::Wrap<v8impl::retrievable>(env,
js_object,
native_object,
finalize_cb,
finalize_hint,
result);
}
napi_status napi_unwrap(napi_env env, napi_value obj, void** result) {
return v8impl::Unwrap(env, obj, result, v8impl::KeepWrap);
}
napi_status napi_remove_wrap(napi_env env, napi_value obj, void** result) {
return v8impl::Unwrap(env, obj, result, v8impl::RemoveWrap);
}
napi_status napi_create_external(napi_env env,
void* data,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::Value> external_value = v8::External::New(isolate, data);
// The Reference object will delete itself after invoking the finalizer
// callback.
v8impl::Reference::New(env,
external_value,
0,
true,
finalize_cb,
data,
finalize_hint);
*result = v8impl::JsValueFromV8LocalValue(external_value);
return napi_clear_last_error(env);
}
napi_status napi_get_value_external(napi_env env,
napi_value value,
void** result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg);
v8::Local<v8::External> external_value = val.As<v8::External>();
*result = external_value->Value();
return napi_clear_last_error(env);
}
// Set initial_refcount to 0 for a weak reference, >0 for a strong reference.
napi_status napi_create_reference(napi_env env,
napi_value value,
uint32_t initial_refcount,
napi_ref* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> v8_value = v8impl::V8LocalValueFromJsValue(value);
if (!(v8_value->IsObject() || v8_value->IsFunction())) {
return napi_set_last_error(env, napi_object_expected);
}
v8impl::Reference* reference =
v8impl::Reference::New(env, v8_value, initial_refcount, false);
*result = reinterpret_cast<napi_ref>(reference);
return napi_clear_last_error(env);
}
// Deletes a reference. The referenced value is released, and may be GC'd unless
// there are other references to it.
napi_status napi_delete_reference(napi_env env, napi_ref ref) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, ref);
v8impl::Reference::Delete(reinterpret_cast<v8impl::Reference*>(ref));
return napi_clear_last_error(env);
}
// Increments the reference count, optionally returning the resulting count.
// After this call the reference will be a strong reference because its
// refcount is >0, and the referenced object is effectively "pinned".
// Calling this when the refcount is 0 and the object is unavailable
// results in an error.
napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, ref);
v8impl::Reference* reference = reinterpret_cast<v8impl::Reference*>(ref);
uint32_t count = reference->Ref();
if (result != nullptr) {
*result = count;
}
return napi_clear_last_error(env);
}
// Decrements the reference count, optionally returning the resulting count. If
// the result is 0 the reference is now weak and the object may be GC'd at any
// time if there are no other references. Calling this when the refcount is
// already 0 results in an error.
napi_status napi_reference_unref(napi_env env, napi_ref ref, uint32_t* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, ref);
v8impl::Reference* reference = reinterpret_cast<v8impl::Reference*>(ref);
if (reference->RefCount() == 0) {
return napi_set_last_error(env, napi_generic_failure);
}
uint32_t count = reference->Unref();
if (result != nullptr) {
*result = count;
}
return napi_clear_last_error(env);
}
// Attempts to get a referenced value. If the reference is weak, the value might
// no longer be available, in that case the call is still successful but the
// result is NULL.
napi_status napi_get_reference_value(napi_env env,
napi_ref ref,
napi_value* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, ref);
CHECK_ARG(env, result);
v8impl::Reference* reference = reinterpret_cast<v8impl::Reference*>(ref);
*result = v8impl::JsValueFromV8LocalValue(reference->Get());
return napi_clear_last_error(env);
}
napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsHandleScopeFromV8HandleScope(
new v8impl::HandleScopeWrapper(env->isolate));
env->open_handle_scopes++;
return napi_clear_last_error(env);
}
napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, scope);
if (env->open_handle_scopes == 0) {
return napi_handle_scope_mismatch;
}
env->open_handle_scopes--;
delete v8impl::V8HandleScopeFromJsHandleScope(scope);
return napi_clear_last_error(env);
}
napi_status napi_open_escapable_handle_scope(
napi_env env,
napi_escapable_handle_scope* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = v8impl::JsEscapableHandleScopeFromV8EscapableHandleScope(
new v8impl::EscapableHandleScopeWrapper(env->isolate));
env->open_handle_scopes++;
return napi_clear_last_error(env);
}
napi_status napi_close_escapable_handle_scope(
napi_env env,
napi_escapable_handle_scope scope) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, scope);
if (env->open_handle_scopes == 0) {
return napi_handle_scope_mismatch;
}
delete v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope);
env->open_handle_scopes--;
return napi_clear_last_error(env);
}
napi_status napi_escape_handle(napi_env env,
napi_escapable_handle_scope scope,
napi_value escapee,
napi_value* result) {
// Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
// JS exceptions.
CHECK_ENV(env);
CHECK_ARG(env, scope);
CHECK_ARG(env, escapee);
CHECK_ARG(env, result);
v8impl::EscapableHandleScopeWrapper* s =
v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope);
if (!s->escape_called()) {
*result = v8impl::JsValueFromV8LocalValue(
s->Escape(v8impl::V8LocalValueFromJsValue(escapee)));
return napi_clear_last_error(env);
}
return napi_set_last_error(env, napi_escape_called_twice);
}
napi_status napi_new_instance(napi_env env,
napi_value constructor,
size_t argc,
const napi_value* argv,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, constructor);
if (argc > 0) {
CHECK_ARG(env, argv);
}
CHECK_ARG(env, result);
v8::Local<v8::Context> context = env->context();
v8::Local<v8::Function> ctor;
CHECK_TO_FUNCTION(env, ctor, constructor);
auto maybe = ctor->NewInstance(context, argc,
reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)));
CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked());
return GET_RETURN_STATUS(env);
}
napi_status napi_instanceof(napi_env env,
napi_value object,
napi_value constructor,
bool* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, object);
CHECK_ARG(env, result);
*result = false;
v8::Local<v8::Object> ctor;
v8::Local<v8::Context> context = env->context();
CHECK_TO_OBJECT(env, context, ctor, constructor);
if (!ctor->IsFunction()) {
napi_throw_type_error(env,
"ERR_NAPI_CONS_FUNCTION",
"Constructor must be a function");
return napi_set_last_error(env, napi_function_expected);
}
napi_status status = napi_generic_failure;
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(object);
auto maybe_result = val->InstanceOf(context, ctor);
CHECK_MAYBE_NOTHING(env, maybe_result, status);
*result = maybe_result.FromJust();
return GET_RETURN_STATUS(env);
}
// Methods to support catching exceptions
napi_status napi_is_exception_pending(napi_env env, bool* result) {
// NAPI_PREAMBLE is not used here: this function must execute when there is a
// pending exception.
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = !env->last_exception.IsEmpty();
return napi_clear_last_error(env);
}
napi_status napi_get_and_clear_last_exception(napi_env env,
napi_value* result) {
// NAPI_PREAMBLE is not used here: this function must execute when there is a
// pending exception.
CHECK_ENV(env);
CHECK_ARG(env, result);
if (env->last_exception.IsEmpty()) {
return napi_get_undefined(env, result);
} else {
*result = v8impl::JsValueFromV8LocalValue(
v8::Local<v8::Value>::New(env->isolate, env->last_exception));
env->last_exception.Reset();
}
return napi_clear_last_error(env);
}
napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
*result = val->IsArrayBuffer();
return napi_clear_last_error(env);
}
napi_status napi_create_arraybuffer(napi_env env,
size_t byte_length,
void** data,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::Isolate* isolate = env->isolate;
v8::Local<v8::ArrayBuffer> buffer =
v8::ArrayBuffer::New(isolate, byte_length);
// Optionally return a pointer to the buffer's data, to avoid another call to
// retrieve it.
if (data != nullptr) {
*data = buffer->GetBackingStore()->Data();
}
*result = v8impl::JsValueFromV8LocalValue(buffer);
return GET_RETURN_STATUS(env);
}
napi_status napi_create_external_arraybuffer(napi_env env,
void* external_data,
size_t byte_length,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result) {
// The API contract here is that the cleanup function runs on the JS thread,
// and is able to use napi_env. Implementing that properly is hard, so use the
// `Buffer` variant for easier implementation.
napi_value buffer;
napi_status status;
status = napi_create_external_buffer(
env,
byte_length,
external_data,
finalize_cb,
finalize_hint,
&buffer);
if (status != napi_ok) return status;
return napi_get_typedarray_info(
env,
buffer,
nullptr,
nullptr,
nullptr,
result,
nullptr);
}
napi_status napi_get_arraybuffer_info(napi_env env,
napi_value arraybuffer,
void** data,
size_t* byte_length) {
CHECK_ENV(env);
CHECK_ARG(env, arraybuffer);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer);
RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg);
std::shared_ptr<v8::BackingStore> backing_store =
value.As<v8::ArrayBuffer>()->GetBackingStore();
if (data != nullptr) {
*data = backing_store->Data();
}
if (byte_length != nullptr) {
*byte_length = backing_store->ByteLength();
}
return napi_clear_last_error(env);
}
napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
*result = val->IsTypedArray();
return napi_clear_last_error(env);
}
napi_status napi_create_typedarray(napi_env env,
napi_typedarray_type type,
size_t length,
napi_value arraybuffer,
size_t byte_offset,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, arraybuffer);
CHECK_ARG(env, result);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer);
RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg);
v8::Local<v8::ArrayBuffer> buffer = value.As<v8::ArrayBuffer>();
v8::Local<v8::TypedArray> typedArray;
switch (type) {
case napi_int8_array:
CREATE_TYPED_ARRAY(
env, Int8Array, 1, buffer, byte_offset, length, typedArray);
break;
case napi_uint8_array:
CREATE_TYPED_ARRAY(
env, Uint8Array, 1, buffer, byte_offset, length, typedArray);
break;
case napi_uint8_clamped_array:
CREATE_TYPED_ARRAY(
env, Uint8ClampedArray, 1, buffer, byte_offset, length, typedArray);
break;
case napi_int16_array:
CREATE_TYPED_ARRAY(
env, Int16Array, 2, buffer, byte_offset, length, typedArray);
break;
case napi_uint16_array:
CREATE_TYPED_ARRAY(
env, Uint16Array, 2, buffer, byte_offset, length, typedArray);
break;
case napi_int32_array:
CREATE_TYPED_ARRAY(
env, Int32Array, 4, buffer, byte_offset, length, typedArray);
break;
case napi_uint32_array:
CREATE_TYPED_ARRAY(
env, Uint32Array, 4, buffer, byte_offset, length, typedArray);
break;
case napi_float32_array:
CREATE_TYPED_ARRAY(
env, Float32Array, 4, buffer, byte_offset, length, typedArray);
break;
case napi_float64_array:
CREATE_TYPED_ARRAY(
env, Float64Array, 8, buffer, byte_offset, length, typedArray);
break;
case napi_bigint64_array:
CREATE_TYPED_ARRAY(
env, BigInt64Array, 8, buffer, byte_offset, length, typedArray);
break;
case napi_biguint64_array:
CREATE_TYPED_ARRAY(
env, BigUint64Array, 8, buffer, byte_offset, length, typedArray);
break;
default:
return napi_set_last_error(env, napi_invalid_arg);
}
*result = v8impl::JsValueFromV8LocalValue(typedArray);
return GET_RETURN_STATUS(env);
}
napi_status napi_get_typedarray_info(napi_env env,
napi_value typedarray,
napi_typedarray_type* type,
size_t* length,
void** data,
napi_value* arraybuffer,
size_t* byte_offset) {
CHECK_ENV(env);
CHECK_ARG(env, typedarray);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(typedarray);
RETURN_STATUS_IF_FALSE(env, value->IsTypedArray(), napi_invalid_arg);
v8::Local<v8::TypedArray> array = value.As<v8::TypedArray>();
if (type != nullptr) {
if (value->IsInt8Array()) {
*type = napi_int8_array;
} else if (value->IsUint8Array()) {
*type = napi_uint8_array;
} else if (value->IsUint8ClampedArray()) {
*type = napi_uint8_clamped_array;
} else if (value->IsInt16Array()) {
*type = napi_int16_array;
} else if (value->IsUint16Array()) {
*type = napi_uint16_array;
} else if (value->IsInt32Array()) {
*type = napi_int32_array;
} else if (value->IsUint32Array()) {
*type = napi_uint32_array;
} else if (value->IsFloat32Array()) {
*type = napi_float32_array;
} else if (value->IsFloat64Array()) {
*type = napi_float64_array;
} else if (value->IsBigInt64Array()) {
*type = napi_bigint64_array;
} else if (value->IsBigUint64Array()) {
*type = napi_biguint64_array;
}
}
if (length != nullptr) {
*length = array->Length();
}
v8::Local<v8::ArrayBuffer> buffer;
if (data != nullptr || arraybuffer != nullptr) {
// Calling Buffer() may have the side effect of allocating the buffer,
// so only do this when it’s needed.
buffer = array->Buffer();
}
if (data != nullptr) {
*data = static_cast<uint8_t*>(buffer->GetBackingStore()->Data()) +
array->ByteOffset();
}
if (arraybuffer != nullptr) {
*arraybuffer = v8impl::JsValueFromV8LocalValue(buffer);
}
if (byte_offset != nullptr) {
*byte_offset = array->ByteOffset();
}
return napi_clear_last_error(env);
}
napi_status napi_create_dataview(napi_env env,
size_t byte_length,
napi_value arraybuffer,
size_t byte_offset,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, arraybuffer);
CHECK_ARG(env, result);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer);
RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg);
v8::Local<v8::ArrayBuffer> buffer = value.As<v8::ArrayBuffer>();
if (byte_length + byte_offset > buffer->ByteLength()) {
napi_throw_range_error(
env,
"ERR_NAPI_INVALID_DATAVIEW_ARGS",
"byte_offset + byte_length should be less than or "
"equal to the size in bytes of the array passed in");
return napi_set_last_error(env, napi_pending_exception);
}
v8::Local<v8::DataView> DataView = v8::DataView::New(buffer, byte_offset,
byte_length);
*result = v8impl::JsValueFromV8LocalValue(DataView);
return GET_RETURN_STATUS(env);
}
napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
*result = val->IsDataView();
return napi_clear_last_error(env);
}
napi_status napi_get_dataview_info(napi_env env,
napi_value dataview,
size_t* byte_length,
void** data,
napi_value* arraybuffer,
size_t* byte_offset) {
CHECK_ENV(env);
CHECK_ARG(env, dataview);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(dataview);
RETURN_STATUS_IF_FALSE(env, value->IsDataView(), napi_invalid_arg);
v8::Local<v8::DataView> array = value.As<v8::DataView>();
if (byte_length != nullptr) {
*byte_length = array->ByteLength();
}
v8::Local<v8::ArrayBuffer> buffer;
if (data != nullptr || arraybuffer != nullptr) {
// Calling Buffer() may have the side effect of allocating the buffer,
// so only do this when it’s needed.
buffer = array->Buffer();
}
if (data != nullptr) {
*data = static_cast<uint8_t*>(buffer->GetBackingStore()->Data()) +
array->ByteOffset();
}
if (arraybuffer != nullptr) {
*arraybuffer = v8impl::JsValueFromV8LocalValue(buffer);
}
if (byte_offset != nullptr) {
*byte_offset = array->ByteOffset();
}
return napi_clear_last_error(env);
}
napi_status napi_get_version(napi_env env, uint32_t* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
*result = NAPI_VERSION;
return napi_clear_last_error(env);
}
napi_status napi_create_promise(napi_env env,
napi_deferred* deferred,
napi_value* promise) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, deferred);
CHECK_ARG(env, promise);
auto maybe = v8::Promise::Resolver::New(env->context());
CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
auto v8_resolver = maybe.ToLocalChecked();
auto v8_deferred = new v8impl::Persistent<v8::Value>();
v8_deferred->Reset(env->isolate, v8_resolver);
*deferred = v8impl::JsDeferredFromNodePersistent(v8_deferred);
*promise = v8impl::JsValueFromV8LocalValue(v8_resolver->GetPromise());
return GET_RETURN_STATUS(env);
}
napi_status napi_resolve_deferred(napi_env env,
napi_deferred deferred,
napi_value resolution) {
return v8impl::ConcludeDeferred(env, deferred, resolution, true);
}
napi_status napi_reject_deferred(napi_env env,
napi_deferred deferred,
napi_value resolution) {
return v8impl::ConcludeDeferred(env, deferred, resolution, false);
}
napi_status napi_is_promise(napi_env env,
napi_value value,
bool* is_promise) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, is_promise);
*is_promise = v8impl::V8LocalValueFromJsValue(value)->IsPromise();
return napi_clear_last_error(env);
}
napi_status napi_create_date(napi_env env,
double time,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
v8::MaybeLocal<v8::Value> maybe_date = v8::Date::New(env->context(), time);
CHECK_MAYBE_EMPTY(env, maybe_date, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(maybe_date.ToLocalChecked());
return GET_RETURN_STATUS(env);
}
napi_status napi_is_date(napi_env env,
napi_value value,
bool* is_date) {
CHECK_ENV(env);
CHECK_ARG(env, value);
CHECK_ARG(env, is_date);
*is_date = v8impl::V8LocalValueFromJsValue(value)->IsDate();
return napi_clear_last_error(env);
}
napi_status napi_get_date_value(napi_env env,
napi_value value,
double* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, value);
CHECK_ARG(env, result);
v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value);
RETURN_STATUS_IF_FALSE(env, val->IsDate(), napi_date_expected);
v8::Local<v8::Date> date = val.As<v8::Date>();
*result = date->ValueOf();
return GET_RETURN_STATUS(env);
}
napi_status napi_run_script(napi_env env,
napi_value script,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, script);
CHECK_ARG(env, result);
v8::Local<v8::Value> v8_script = v8impl::V8LocalValueFromJsValue(script);
if (!v8_script->IsString()) {
return napi_set_last_error(env, napi_string_expected);
}
v8::Local<v8::Context> context = env->context();
auto maybe_script = v8::Script::Compile(context,
v8::Local<v8::String>::Cast(v8_script));
CHECK_MAYBE_EMPTY(env, maybe_script, napi_generic_failure);
auto script_result =
maybe_script.ToLocalChecked()->Run(context);
CHECK_MAYBE_EMPTY(env, script_result, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(script_result.ToLocalChecked());
return GET_RETURN_STATUS(env);
}
napi_status napi_add_finalizer(napi_env env,
napi_value js_object,
void* native_object,
napi_finalize finalize_cb,
void* finalize_hint,
napi_ref* result) {
return v8impl::Wrap<v8impl::anonymous>(env,
js_object,
native_object,
finalize_cb,
finalize_hint,
result);
}
napi_status napi_adjust_external_memory(napi_env env,
int64_t change_in_bytes,
int64_t* adjusted_value) {
CHECK_ENV(env);
CHECK_ARG(env, adjusted_value);
*adjusted_value = env->isolate->AdjustAmountOfExternalAllocatedMemory(
change_in_bytes);
return napi_clear_last_error(env);
}
napi_status napi_set_instance_data(napi_env env,
void* data,
napi_finalize finalize_cb,
void* finalize_hint) {
CHECK_ENV(env);
v8impl::RefBase* old_data = static_cast<v8impl::RefBase*>(env->instance_data);
if (old_data != nullptr) {
// Our contract so far has been to not finalize any old data there may be.
// So we simply delete it.
v8impl::RefBase::Delete(old_data);
}
env->instance_data = v8impl::RefBase::New(env,
0,
true,
finalize_cb,
data,
finalize_hint);
return napi_clear_last_error(env);
}
napi_status napi_get_instance_data(napi_env env,
void** data) {
CHECK_ENV(env);
CHECK_ARG(env, data);
v8impl::RefBase* idata = static_cast<v8impl::RefBase*>(env->instance_data);
*data = (idata == nullptr ? nullptr : idata->Data());
return napi_clear_last_error(env);
}
napi_status napi_detach_arraybuffer(napi_env env, napi_value arraybuffer) {
CHECK_ENV(env);
CHECK_ARG(env, arraybuffer);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer);
RETURN_STATUS_IF_FALSE(
env, value->IsArrayBuffer(), napi_arraybuffer_expected);
v8::Local<v8::ArrayBuffer> it = value.As<v8::ArrayBuffer>();
RETURN_STATUS_IF_FALSE(
env, it->IsDetachable(), napi_detachable_arraybuffer_expected);
it->Detach();
return napi_clear_last_error(env);
}
napi_status napi_is_detached_arraybuffer(napi_env env,
napi_value arraybuffer,
bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, arraybuffer);
CHECK_ARG(env, result);
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer);
*result = value->IsArrayBuffer() &&
value.As<v8::ArrayBuffer>()->GetBackingStore()->Data() == nullptr;
return napi_clear_last_error(env);
}
|