deno_node 0.183.0

Node compatibility for Deno
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
// Copyright 2018-2026 the Deno authors. MIT license.

use std::borrow::Cow;
use std::cell::RefCell;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;

use deno_core::JsBuffer;
use deno_core::OpState;
use deno_core::ResourceId;
use deno_core::op2;
#[cfg(feature = "sync_fs")]
use deno_core::unsync::spawn_blocking;
use deno_core::v8;
use deno_fs::FileSystemRc;
use deno_fs::FsFileType;
use deno_fs::OpenOptions;
use deno_io::fs::FsResult;
use deno_permissions::CheckedPath;
use deno_permissions::CheckedPathBuf;
use deno_permissions::OpenAccessKind;
use deno_permissions::PermissionsContainer;
use serde::Serialize;
#[cfg(feature = "sync_fs")]
use tokio::task::JoinError;

use crate::ops::constant::UV_FS_COPYFILE_EXCL;

/// Extract the real OS file descriptor from a File trait object.
/// On Unix, this is the raw fd (already an i32).
/// On Windows, this duplicates the OS HANDLE and converts it to a CRT
/// file descriptor. The duplicate ensures the CRT fd and the File trait
/// object own independent handles, avoiding double-close on cleanup.
fn raw_fd_for_file(file: Rc<dyn deno_io::fs::File>) -> Result<i32, FsError> {
  let handle_fd = file.backing_fd().ok_or_else(|| {
    FsError::Io(std::io::Error::other(
      "Failed to get OS file descriptor from file",
    ))
  })?;

  #[cfg(unix)]
  {
    Ok(handle_fd)
  }

  #[cfg(windows)]
  {
    use windows_sys::Win32::Foundation::CloseHandle;
    use windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS;
    use windows_sys::Win32::Foundation::DuplicateHandle;
    use windows_sys::Win32::System::Threading::GetCurrentProcess;

    // Duplicate the OS handle so the CRT fd owns an independent copy.
    // This prevents double-close: dropping the Rc<dyn File> closes the
    // original handle, and libc::close(crt_fd) closes the duplicate.
    let mut dup_handle = std::ptr::null_mut();
    // SAFETY: `handle_fd` is a valid OS handle from the file. We duplicate
    // it into the current process with the same access rights.
    let ok = unsafe {
      DuplicateHandle(
        GetCurrentProcess(),
        handle_fd as _,
        GetCurrentProcess(),
        &mut dup_handle,
        0,
        0,
        DUPLICATE_SAME_ACCESS,
      )
    };
    if ok == 0 {
      return Err(FsError::Io(std::io::Error::last_os_error()));
    }

    // SAFETY: `dup_handle` is a valid duplicated OS handle.
    // `open_osfhandle` associates a CRT file descriptor with it so
    // that node:fs callers receive a POSIX-style fd.
    let crt_fd = unsafe { libc::open_osfhandle(dup_handle as isize, 0) };
    if crt_fd == -1 {
      // SAFETY: Clean up the duplicated handle on failure.
      unsafe { CloseHandle(dup_handle) };
      return Err(FsError::Io(std::io::Error::last_os_error()));
    }
    Ok(crt_fd)
  }
}

fn ebadf() -> FsError {
  FsError::Io(std::io::Error::from_raw_os_error(
    #[cfg(unix)]
    libc::EBADF,
    #[cfg(windows)]
    {
      // Win32 ERROR_INVALID_HANDLE, which maps to Node's EBADF
      6
    },
  ))
}

/// Get the File trait object for an OS file descriptor from FdTable.
fn file_for_fd(
  state: &OpState,
  fd: i32,
) -> Result<Rc<dyn deno_io::fs::File>, FsError> {
  state
    .borrow::<deno_io::FdTable>()
    .get(fd)
    .cloned()
    .ok_or_else(ebadf)
}

/// When `sync_fs` is enabled, `FileSystemRc` is `Arc` (Send) and we can
/// offload work to a blocking thread. Otherwise, run inline.
macro_rules! maybe_spawn_blocking {
  ($f:expr) => {{
    #[cfg(feature = "sync_fs")]
    {
      spawn_blocking($f).await.unwrap()
    }
    #[cfg(not(feature = "sync_fs"))]
    {
      ($f)()
    }
  }};
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
pub enum FsError {
  #[class(inherit)]
  #[error(transparent)]
  Permission(#[from] deno_permissions::PermissionCheckError),
  #[class(inherit)]
  #[error("{0}")]
  Io(
    #[from]
    #[inherit]
    std::io::Error,
  ),
  #[cfg(windows)]
  #[class(generic)]
  #[error("Path has no root.")]
  PathHasNoRoot,
  #[cfg(not(any(unix, windows)))]
  #[class(generic)]
  #[error("Unsupported platform.")]
  UnsupportedPlatform,
  #[class(inherit)]
  #[error(transparent)]
  Fs(
    #[from]
    #[inherit]
    deno_io::fs::FsError,
  ),
  #[class(inherit)]
  #[error(transparent)]
  Cp(#[from] CpError),
  #[class(inherit)]
  #[error(transparent)]
  NodeFs(#[from] NodeFsError),
  #[cfg(feature = "sync_fs")]
  #[class(inherit)]
  #[error(transparent)]
  JoinError(#[from] JoinError),
}

#[derive(Debug, Default)]
pub struct NodeFsErrorContext {
  message: Option<String>,
  path: Option<String>,
  dest: Option<String>,
  syscall: Option<String>,
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
#[class(generic)]
// Intentionally set the error message to be empty, so that in the JS side it will fall back to the UV error message
// https://github.com/denoland/deno/blob/f123d84e7d6e8036c3c38ecec6e25deb87a8829b/ext/node/polyfills/internal/errors.ts#L268-L270
#[error("")]
#[property("os_errno" = self.os_errno)]
#[property("message" = self.context.message.clone().unwrap_or_default().clone())]
#[property("path" = self.context.path.clone().unwrap_or_default().clone())]
#[property("dest" = self.context.dest.clone().unwrap_or_default().clone())]
#[property("syscall" = self.context.syscall.clone().unwrap_or_default().clone())]
pub struct NodeFsError {
  os_errno: i32,
  context: NodeFsErrorContext,
}

fn map_fs_error_to_node_fs_error(
  err: deno_io::fs::FsError,
  context: NodeFsErrorContext,
) -> FsError {
  let os_errno = match err {
    deno_io::fs::FsError::Io(ref io_err) => io_err.raw_os_error(),
    _ => None,
  };

  if let Some(os_errno) = os_errno {
    return NodeFsError { os_errno, context }.into();
  }

  FsError::Fs(err)
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
#[class(generic)]
#[error("{message}")]
#[property("kind" = self.kind())]
#[property("message" = self.message())]
#[property("path" = self.path())]
pub enum CpError {
  EInval { message: String, path: String },
  DirToNonDir { message: String, path: String },
  NonDirToDir { message: String, path: String },
  EExist { message: String, path: String },
  EIsDir { message: String, path: String },
  Socket { message: String, path: String },
  Fifo { message: String, path: String },
  Unknown { message: String, path: String },
  SymlinkToSubdirectory { message: String, path: String },
}

impl CpError {
  fn kind(&self) -> &'static str {
    match self {
      CpError::EInval { .. } => "EINVAL",
      CpError::DirToNonDir { .. } => "DIR_TO_NON_DIR",
      CpError::NonDirToDir { .. } => "NON_DIR_TO_DIR",
      CpError::EExist { .. } => "EEXIST",
      CpError::EIsDir { .. } => "EISDIR",
      CpError::Socket { .. } => "SOCKET",
      CpError::Fifo { .. } => "FIFO",
      CpError::Unknown { .. } => "UNKNOWN",
      CpError::SymlinkToSubdirectory { .. } => "SYMLINK_TO_SUBDIRECTORY",
    }
  }

  fn message(&self) -> String {
    match self {
      CpError::EInval { message, .. } => message.clone(),
      CpError::DirToNonDir { message, .. } => message.clone(),
      CpError::NonDirToDir { message, .. } => message.clone(),
      CpError::EExist { message, .. } => message.clone(),
      CpError::EIsDir { message, .. } => message.clone(),
      CpError::Socket { message, .. } => message.clone(),
      CpError::Fifo { message, .. } => message.clone(),
      CpError::Unknown { message, .. } => message.clone(),
      CpError::SymlinkToSubdirectory { message, .. } => message.clone(),
    }
  }

  fn path(&self) -> String {
    match self {
      CpError::EInval { path, .. } => path.clone(),
      CpError::DirToNonDir { path, .. } => path.clone(),
      CpError::NonDirToDir { path, .. } => path.clone(),
      CpError::EExist { path, .. } => path.clone(),
      CpError::EIsDir { path, .. } => path.clone(),
      CpError::Socket { path, .. } => path.clone(),
      CpError::Fifo { path, .. } => path.clone(),
      CpError::Unknown { path, .. } => path.clone(),
      CpError::SymlinkToSubdirectory { path, .. } => path.clone(),
    }
  }
}

#[op2(fast, stack_trace)]
pub fn op_node_fs_exists_sync(
  state: &mut OpState,
  #[string] path: &str,
) -> Result<bool, deno_permissions::PermissionCheckError> {
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(Path::new(path)),
    OpenAccessKind::ReadNoFollow,
    Some("node:fs.existsSync()"),
  )?;
  let fs = state.borrow::<FileSystemRc>();
  Ok(fs.exists_sync(&path))
}

#[op2(stack_trace)]
pub async fn op_node_fs_exists(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
) -> Result<bool, FsError> {
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(path)),
      OpenAccessKind::ReadNoFollow,
      Some("node:fs.exists()"),
    )?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };

  Ok(fs.exists_async(path.into_owned()).await?)
}

fn get_open_options(flags: i32, mode: Option<u32>) -> OpenOptions {
  let mut options = OpenOptions::from(flags);
  options.mode = mode;
  options
}

fn open_options_to_access_kind(open_options: &OpenOptions) -> OpenAccessKind {
  let read = open_options.read;
  let write = open_options.write || open_options.append || open_options.create;
  match (read, write) {
    (true, true) => OpenAccessKind::ReadWrite,
    (false, true) => OpenAccessKind::Write,
    (true, false) | (false, false) => OpenAccessKind::Read,
  }
}

#[op2(fast, stack_trace)]
#[smi]
pub fn op_node_open_sync(
  state: &mut OpState,
  #[string] path: &str,
  #[smi] flags: i32,
  #[smi] mode: u32,
) -> Result<i32, FsError> {
  let path = Path::new(path);
  let options = get_open_options(flags, Some(mode));

  let fs = state.borrow::<FileSystemRc>().clone();
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(path),
    open_options_to_access_kind(&options),
    Some("node:fs.openSync"),
  )?;
  let file = fs.open_sync(&path, options)?;
  let fd = raw_fd_for_file(file.clone())?;
  state.borrow_mut::<deno_io::FdTable>().register(fd, file);
  Ok(fd)
}

#[op2(stack_trace)]
#[smi]
pub async fn op_node_open(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
  #[smi] flags: i32,
  #[smi] mode: u32,
) -> Result<i32, FsError> {
  let path = PathBuf::from(path);
  let options = get_open_options(flags, Some(mode));

  let (fs, path) = {
    let mut state = state.borrow_mut();
    (
      state.borrow::<FileSystemRc>().clone(),
      state.borrow_mut::<PermissionsContainer>().check_open(
        Cow::Owned(path),
        open_options_to_access_kind(&options),
        Some("node:fs.open"),
      )?,
    )
  };
  let file = fs.open_async(path.as_owned(), options).await?;
  let fd = raw_fd_for_file(file.clone())?;

  let mut state = state.borrow_mut();
  state.borrow_mut::<deno_io::FdTable>().register(fd, file);
  Ok(fd)
}
#[derive(Debug, Serialize)]
pub struct StatFs {
  #[serde(rename = "type")]
  pub typ: u64,
  pub bsize: u64,
  pub blocks: u64,
  pub bfree: u64,
  pub bavail: u64,
  pub files: u64,
  pub ffree: u64,
}

#[op2(stack_trace)]
#[serde]
pub fn op_node_statfs_sync(
  state: &mut OpState,
  #[string] path: &str,
  bigint: bool,
) -> Result<StatFs, FsError> {
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(Path::new(path)),
    OpenAccessKind::ReadNoFollow,
    Some("node:fs.statfsSync"),
  )?;
  state
    .borrow_mut::<PermissionsContainer>()
    .check_sys("statfs", "node:fs.statfsSync")?;

  statfs(path, bigint)
}

#[op2(stack_trace)]
#[serde]
#[allow(clippy::unused_async, reason = "sometimes async")]
pub async fn op_node_statfs(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
  bigint: bool,
) -> Result<StatFs, FsError> {
  let path = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(path)),
      OpenAccessKind::ReadNoFollow,
      Some("node:fs.statfs"),
    )?;
    state
      .borrow_mut::<PermissionsContainer>()
      .check_sys("statfs", "node:fs.statfs")?;
    path
  };

  maybe_spawn_blocking!(move || statfs(path, bigint))
}

// TODO(dsherret): move this method onto FileSystem trait as this is completely
// bypassing the FileSystem trait.
fn statfs(path: CheckedPath, bigint: bool) -> Result<StatFs, FsError> {
  #[cfg(unix)]
  {
    use std::os::unix::ffi::OsStrExt;

    let path = path.as_os_str();
    let mut cpath = path.as_bytes().to_vec();
    cpath.push(0);
    if bigint {
      #[cfg(not(any(
        target_os = "macos",
        target_os = "freebsd",
        target_os = "openbsd"
      )))]
      // SAFETY: `cpath` is NUL-terminated and result is pointer to valid statfs memory.
      let (code, result) = unsafe {
        let mut result: libc::statfs64 = std::mem::zeroed();
        (libc::statfs64(cpath.as_ptr() as _, &mut result), result)
      };
      #[cfg(any(
        target_os = "macos",
        target_os = "freebsd",
        target_os = "openbsd"
      ))]
      // SAFETY: `cpath` is NUL-terminated and result is pointer to valid statfs memory.
      let (code, result) = unsafe {
        let mut result: libc::statfs = std::mem::zeroed();
        (libc::statfs(cpath.as_ptr() as _, &mut result), result)
      };
      if code == -1 {
        return Err(std::io::Error::last_os_error().into());
      }
      Ok(StatFs {
        #[cfg(not(target_os = "openbsd"))]
        typ: result.f_type as _,
        #[cfg(target_os = "openbsd")]
        typ: 0 as _,
        bsize: result.f_bsize as _,
        blocks: result.f_blocks as _,
        bfree: result.f_bfree as _,
        bavail: result.f_bavail as _,
        files: result.f_files as _,
        ffree: result.f_ffree as _,
      })
    } else {
      // SAFETY: `cpath` is NUL-terminated and result is pointer to valid statfs memory.
      let (code, result) = unsafe {
        let mut result: libc::statfs = std::mem::zeroed();
        (libc::statfs(cpath.as_ptr() as _, &mut result), result)
      };
      if code == -1 {
        return Err(std::io::Error::last_os_error().into());
      }
      Ok(StatFs {
        #[cfg(not(target_os = "openbsd"))]
        typ: result.f_type as _,
        #[cfg(target_os = "openbsd")]
        typ: 0 as _,
        bsize: result.f_bsize as _,
        blocks: result.f_blocks as _,
        bfree: result.f_bfree as _,
        bavail: result.f_bavail as _,
        files: result.f_files as _,
        ffree: result.f_ffree as _,
      })
    }
  }
  #[cfg(windows)]
  {
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;

    use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceW;

    let _ = bigint;
    #[allow(clippy::disallowed_methods, reason = "TODO: move onto RealFs")]
    let path = path.canonicalize()?;
    let root = path.ancestors().last().ok_or(FsError::PathHasNoRoot)?;
    let mut root = OsStr::new(root).encode_wide().collect::<Vec<_>>();
    root.push(0);
    let mut sectors_per_cluster = 0;
    let mut bytes_per_sector = 0;
    let mut available_clusters = 0;
    let mut total_clusters = 0;
    let mut code = 0;
    let mut retries = 0;
    // We retry here because libuv does: https://github.com/libuv/libuv/blob/fa6745b4f26470dae5ee4fcbb1ee082f780277e0/src/win/fs.c#L2705
    while code == 0 && retries < 2 {
      // SAFETY: Normal GetDiskFreeSpaceW usage.
      code = unsafe {
        GetDiskFreeSpaceW(
          root.as_ptr(),
          &mut sectors_per_cluster,
          &mut bytes_per_sector,
          &mut available_clusters,
          &mut total_clusters,
        )
      };
      retries += 1;
    }
    if code == 0 {
      return Err(std::io::Error::last_os_error().into());
    }
    Ok(StatFs {
      typ: 0,
      bsize: (bytes_per_sector * sectors_per_cluster) as _,
      blocks: total_clusters as _,
      bfree: available_clusters as _,
      bavail: available_clusters as _,
      files: 0,
      ffree: 0,
    })
  }
  #[cfg(not(any(unix, windows)))]
  {
    let _ = path;
    let _ = bigint;
    Err(FsError::UnsupportedPlatform)
  }
}

#[op2(fast, stack_trace)]
pub fn op_node_lutimes_sync(
  state: &mut OpState,
  #[string] path: &str,
  #[number] atime_secs: i64,
  #[smi] atime_nanos: u32,
  #[number] mtime_secs: i64,
  #[smi] mtime_nanos: u32,
) -> Result<(), FsError> {
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(Path::new(path)),
    OpenAccessKind::WriteNoFollow,
    Some("node:fs.lutimes"),
  )?;

  let fs = state.borrow::<FileSystemRc>();
  fs.lutime_sync(&path, atime_secs, atime_nanos, mtime_secs, mtime_nanos)?;
  Ok(())
}

#[op2(stack_trace)]
pub async fn op_node_lutimes(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
  #[number] atime_secs: i64,
  #[smi] atime_nanos: u32,
  #[number] mtime_secs: i64,
  #[smi] mtime_nanos: u32,
) -> Result<(), FsError> {
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(path)),
      OpenAccessKind::WriteNoFollow,
      Some("node:fs.lutimesSync"),
    )?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };

  fs.lutime_async(
    path.into_owned(),
    atime_secs,
    atime_nanos,
    mtime_secs,
    mtime_nanos,
  )
  .await?;

  Ok(())
}

#[op2(stack_trace)]
pub fn op_node_lchown_sync(
  state: &mut OpState,
  #[string] path: &str,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsError> {
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(Path::new(path)),
    OpenAccessKind::WriteNoFollow,
    Some("node:fs.lchownSync"),
  )?;
  let fs = state.borrow::<FileSystemRc>();
  fs.lchown_sync(&path, uid, gid)?;
  Ok(())
}

#[op2(stack_trace)]
pub async fn op_node_lchown(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsError> {
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(path)),
      OpenAccessKind::WriteNoFollow,
      Some("node:fs.lchown"),
    )?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };
  fs.lchown_async(path.into_owned(), uid, gid).await?;
  Ok(())
}

#[op2(fast, stack_trace)]
pub fn op_node_lchmod_sync(
  state: &mut OpState,
  #[string] path: &str,
  #[smi] mode: u32,
) -> Result<(), FsError> {
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(Path::new(path)),
    OpenAccessKind::WriteNoFollow,
    Some("node:fs.lchmodSync"),
  )?;
  let fs = state.borrow::<FileSystemRc>();
  fs.lchmod_sync(&path, mode)?;
  Ok(())
}

#[op2(stack_trace)]
pub async fn op_node_lchmod(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
  #[smi] mode: u32,
) -> Result<(), FsError> {
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(path)),
      OpenAccessKind::WriteNoFollow,
      Some("node:fs.lchmod"),
    )?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };
  fs.lchmod_async(path.into_owned(), mode).await?;
  Ok(())
}

#[op2(stack_trace)]
#[string]
pub fn op_node_mkdtemp_sync(
  state: &mut OpState,
  #[string] path: &str,
) -> Result<String, FsError> {
  // https://github.com/nodejs/node/blob/2ea31e53c61463727c002c2d862615081940f355/deps/uv/src/unix/os390-syscalls.c#L409
  for _ in 0..libc::TMP_MAX {
    let path = temp_path_append_suffix(path);
    let checked_path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Borrowed(Path::new(&path)),
      OpenAccessKind::WriteNoFollow,
      Some("node:fs.mkdtempSync()"),
    )?;
    let fs = state.borrow::<FileSystemRc>();

    match fs.mkdir_sync(&checked_path, false, Some(0o700)) {
      Ok(()) => return Ok(path),
      Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
        continue;
      }
      Err(err) => return Err(FsError::Fs(err)),
    }
  }

  Err(FsError::Io(std::io::Error::new(
    std::io::ErrorKind::AlreadyExists,
    "too many temp dirs exist",
  )))
}

#[op2(stack_trace)]
#[string]
pub async fn op_node_mkdtemp(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
) -> Result<String, FsError> {
  // https://github.com/nodejs/node/blob/2ea31e53c61463727c002c2d862615081940f355/deps/uv/src/unix/os390-syscalls.c#L409
  for _ in 0..libc::TMP_MAX {
    let path = temp_path_append_suffix(&path);
    let (fs, checked_path) = {
      let mut state = state.borrow_mut();
      let checked_path =
        state.borrow_mut::<PermissionsContainer>().check_open(
          Cow::Owned(PathBuf::from(path.clone())),
          OpenAccessKind::WriteNoFollow,
          Some("node:fs.mkdtemp()"),
        )?;
      (state.borrow::<FileSystemRc>().clone(), checked_path)
    };

    match fs
      .mkdir_async(checked_path.into_owned(), false, Some(0o700))
      .await
    {
      Ok(()) => return Ok(path),
      Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
        continue;
      }
      Err(err) => return Err(FsError::Fs(err)),
    }
  }

  Err(FsError::Io(std::io::Error::new(
    std::io::ErrorKind::AlreadyExists,
    "too many temp dirs exist",
  )))
}

fn temp_path_append_suffix(prefix: &str) -> String {
  use rand::Rng;
  use rand::distributions::Alphanumeric;
  use rand::rngs::OsRng;

  let suffix: String =
    (0..6).map(|_| OsRng.sample(Alphanumeric) as char).collect();
  format!("{}{}", prefix, suffix)
}

#[op2(fast, stack_trace)]
pub fn op_node_rmdir_sync(
  state: &mut OpState,
  #[string] path: &str,
) -> Result<(), FsError> {
  let path = state.borrow_mut::<PermissionsContainer>().check_open(
    Cow::Borrowed(Path::new(path)),
    OpenAccessKind::WriteNoFollow,
    Some("node:fs.rmdirSync"),
  )?;
  let fs = state.borrow::<FileSystemRc>();
  fs.rmdir_sync(&path)?;
  Ok(())
}

#[op2(stack_trace)]
pub async fn op_node_rmdir(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
) -> Result<(), FsError> {
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(path)),
      OpenAccessKind::WriteNoFollow,
      Some("node:fs.rmdir"),
    )?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };
  fs.rmdir_async(path.into_owned()).await?;
  Ok(())
}

/// Create an anonymous pipe pair and return (read_fd, write_fd).
/// The returned fds are NOT registered in FdTable; the caller
/// is responsible for registering or closing them.
#[cfg(unix)]
#[op2]
#[serde]
pub fn op_node_create_pipe() -> Result<(i32, i32), FsError> {
  let mut fds = [0i32; 2];
  // SAFETY: pipe() writes two valid fds into the array on success.
  let ret = unsafe { libc::pipe(fds.as_mut_ptr()) };
  if ret != 0 {
    return Err(FsError::Io(std::io::Error::last_os_error()));
  }
  Ok((fds[0], fds[1]))
}

#[cfg(windows)]
#[op2]
#[serde]
pub fn op_node_create_pipe() -> Result<(i32, i32), FsError> {
  use windows_sys::Win32::Foundation::CloseHandle;
  use windows_sys::Win32::System::Pipes::CreatePipe;

  let mut read_handle = std::ptr::null_mut();
  let mut write_handle = std::ptr::null_mut();

  // SAFETY: CreatePipe writes valid handles on success.
  let ok = unsafe {
    CreatePipe(&mut read_handle, &mut write_handle, std::ptr::null(), 0)
  };
  if ok == 0 {
    return Err(FsError::Io(std::io::Error::last_os_error()));
  }

  // Convert OS handles to CRT file descriptors.
  // SAFETY: read_handle and write_handle are valid pipe handles from
  // CreatePipe. open_osfhandle takes ownership of the handle on success.
  let read_fd = unsafe { libc::open_osfhandle(read_handle as isize, 0) };
  // SAFETY: Same as above for the write handle.
  let write_fd = unsafe { libc::open_osfhandle(write_handle as isize, 0) };

  if read_fd == -1 || write_fd == -1 {
    // Clean up on failure: close whichever succeeded as a CRT fd,
    // and close the raw OS handle for whichever failed.
    if read_fd != -1 {
      // SAFETY: read_fd is a valid CRT fd from open_osfhandle.
      unsafe {
        libc::close(read_fd);
      }
    } else {
      // SAFETY: read_handle is still a valid OS handle (open_osfhandle failed).
      unsafe {
        CloseHandle(read_handle);
      }
    }
    if write_fd != -1 {
      // SAFETY: write_fd is a valid CRT fd from open_osfhandle.
      unsafe {
        libc::close(write_fd);
      }
    } else {
      // SAFETY: write_handle is still a valid OS handle (open_osfhandle failed).
      unsafe {
        CloseHandle(write_handle);
      }
    }
    return Err(ebadf());
  }

  Ok((read_fd, write_fd))
}

// ============================================================
// fd-based ops for node:fs (accept real OS fd, not RID)
// ============================================================

/// Set blocking or non-blocking mode on an OS file descriptor.
/// Matches libuv's `uv_stream_set_blocking`.
#[cfg(unix)]
#[op2(fast)]
#[smi]
pub fn op_node_fd_set_blocking(fd: i32, blocking: bool) -> i32 {
  // SAFETY: fcntl with F_GETFL/F_SETFL is safe on valid fds.
  // Returns -1 on invalid fd, which we map to UV_EBADF.
  unsafe {
    let flags = libc::fcntl(fd, libc::F_GETFL);
    if flags == -1 {
      return -libc::EBADF;
    }
    let flags = if blocking {
      flags & !libc::O_NONBLOCK
    } else {
      flags | libc::O_NONBLOCK
    };
    if libc::fcntl(fd, libc::F_SETFL, flags) == -1 {
      return -libc::EBADF;
    }
    0
  }
}

#[cfg(windows)]
#[op2(fast)]
#[smi]
pub fn op_node_fd_set_blocking(_fd: i32, _blocking: bool) -> i32 {
  // On Windows, named pipes and console handles don't support
  // toggling blocking mode via a simple flag. The Windows-specific
  // behavior is handled at the I/O level instead.
  0
}

#[op2(fast)]
pub fn op_node_fs_close(state: &mut OpState, fd: i32) -> Result<(), FsError> {
  // FdTable.remove() drops the Rc<dyn File> and cancels the cancel handle,
  // which will abort any in-flight async reads on this fd.
  let file = state
    .borrow_mut::<deno_io::FdTable>()
    .remove(fd)
    .ok_or_else(ebadf)?;

  // For stdio fds (0/1/2), also remove the corresponding resource table
  // entry so that Deno.stdin/stdout/stderr see the fd as closed and
  // release their Rc clone of the same File.
  if (0..=2).contains(&fd)
    && let Ok(resource) = state.resource_table.take_any(fd as ResourceId)
  {
    resource.close();
  }

  // Dropping the Rc<dyn File> will close the underlying OS file descriptor
  // when the reference count reaches zero (via std::fs::File Drop).
  drop(file);

  // On Windows, `raw_fd_for_file` creates a CRT file descriptor via
  // `open_osfhandle` on a duplicated OS handle. The File Drop above closes
  // the original handle; `libc::close` closes the duplicate and frees the
  // CRT fd slot.
  #[cfg(windows)]
  {
    // SAFETY: `fd` is a valid CRT file descriptor created by
    // `open_osfhandle` in `raw_fd_for_file`.
    unsafe {
      libc::close(fd);
    }
  }

  Ok(())
}

/// Read from a raw OS fd using libc. No dup, no clone -- the read uses the
/// fd number directly, so closing the fd from another thread interrupts the
/// Positioned read: if position >= 0, uses pread to read without moving the
/// file cursor. If position < 0, reads from the current position.
fn read_with_position(
  file: Rc<dyn deno_io::fs::File>,
  buf: &mut [u8],
  position: i64,
) -> Result<u32, FsError> {
  if position >= 0 {
    let nread = file.read_at_sync(buf, position as u64)?;
    Ok(nread as u32)
  } else {
    let nread = file.read_sync(buf)?;
    Ok(nread as u32)
  }
}

#[op2(fast)]
#[smi]
pub fn op_node_fs_read_sync(
  state: &mut OpState,
  fd: i32,
  #[buffer] buf: &mut [u8],
  #[number] position: i64,
) -> Result<u32, FsError> {
  let file = file_for_fd(state, fd)?;
  read_with_position(file, buf, position)
}

/// Async read for node:fs. Runs a blocking read on a spawned thread using
/// the raw OS fd directly (no dup/clone). When the fd is closed via
/// Async read for node:fs. Uses the File trait from FdTable for proper
/// I/O through the file handle.
#[op2]
#[smi]
pub async fn op_node_fs_read_deferred(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[buffer] buf: JsBuffer,
  #[number] position: i64,
) -> Result<u32, FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  if position >= 0 {
    let view = deno_core::BufMutView::from(buf);
    let (nread, _) = file.read_at_async(view, position as u64).await?;
    Ok(nread as u32)
  } else {
    let view = deno_core::BufMutView::from(buf);
    let (nread, _) = file.read_byob(view).await?;
    Ok(nread as u32)
  }
}

/// Positioned write: if position >= 0, uses pwrite to write without moving
/// the file cursor. If position < 0, writes at the current position.
/// Handles partial writes internally by looping until all bytes are written.
fn write_with_position(
  file: Rc<dyn deno_io::fs::File>,
  buf: &[u8],
  position: i64,
) -> Result<u32, FsError> {
  if position >= 0 {
    let mut total = 0usize;
    while total < buf.len() {
      let nwritten = file
        .clone()
        .write_at_sync(&buf[total..], position as u64 + total as u64)?;
      total += nwritten;
    }
    Ok(total as u32)
  } else {
    let mut total = 0usize;
    while total < buf.len() {
      let nwritten = file.clone().write_sync(&buf[total..])?;
      total += nwritten;
    }
    Ok(total as u32)
  }
}

#[op2(fast)]
#[smi]
pub fn op_node_fs_write_sync(
  state: &mut OpState,
  fd: i32,
  #[buffer] buf: &[u8],
  #[number] position: i64,
) -> Result<u32, FsError> {
  let file = file_for_fd(state, fd)?;
  write_with_position(file, buf, position)
}

/// Async write for node:fs. Performs the write synchronously but resolves
/// the promise on the next event loop tick.
#[allow(
  clippy::unused_async,
  reason = "async required for deferred op scheduling"
)]
#[op2(async(deferred))]
#[smi]
pub async fn op_node_fs_write_deferred(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[buffer] buf: JsBuffer,
  #[number] position: i64,
) -> Result<u32, FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  write_with_position(file, &buf, position)
}

#[op2(fast)]
#[number]
pub fn op_node_fs_seek_sync(
  state: &mut OpState,
  fd: i32,
  #[number] offset: i64,
  #[smi] whence: i32,
) -> Result<u64, FsError> {
  let file = file_for_fd(state, fd)?;
  let seek_from = match whence {
    0 => std::io::SeekFrom::Start(offset as u64),
    1 => std::io::SeekFrom::Current(offset),
    2 => std::io::SeekFrom::End(offset),
    _ => {
      return Err(FsError::Io(std::io::Error::new(
        std::io::ErrorKind::InvalidInput,
        "invalid whence",
      )));
    }
  };
  let pos = file.seek_sync(seek_from)?;
  Ok(pos)
}

#[op2]
#[number]
pub async fn op_node_fs_seek(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[number] offset: i64,
  #[smi] whence: i32,
) -> Result<u64, FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  let seek_from = match whence {
    0 => std::io::SeekFrom::Start(offset as u64),
    1 => std::io::SeekFrom::Current(offset),
    2 => std::io::SeekFrom::End(offset),
    _ => {
      return Err(FsError::Io(std::io::Error::new(
        std::io::ErrorKind::InvalidInput,
        "invalid whence",
      )));
    }
  };
  let pos = file.seek_async(seek_from).await?;
  Ok(pos)
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
/// Stat result returned to JS. Uses f64 for numeric fields to ensure
/// they always serialize as JS Number (not BigInt). BigInt conversion
/// for the bigint stat API is handled on the JS side by CFISBIS.
pub struct NodeFsStat {
  pub is_file: bool,
  pub is_directory: bool,
  pub is_symlink: bool,
  pub size: f64,
  pub mtime_ms: Option<f64>,
  pub atime_ms: Option<f64>,
  pub birthtime_ms: Option<f64>,
  pub ctime_ms: Option<f64>,
  pub dev: f64,
  pub ino: f64,
  pub mode: u32,
  pub nlink: f64,
  pub uid: u32,
  pub gid: u32,
  pub rdev: f64,
  pub blksize: f64,
  pub blocks: f64,
  pub is_block_device: bool,
  pub is_char_device: bool,
  pub is_fifo: bool,
  pub is_socket: bool,
}

impl From<deno_io::fs::FsStat> for NodeFsStat {
  fn from(stat: deno_io::fs::FsStat) -> Self {
    NodeFsStat {
      is_file: stat.is_file,
      is_directory: stat.is_directory,
      is_symlink: stat.is_symlink,
      size: stat.size as f64,
      mtime_ms: stat.mtime.map(|v| v as f64),
      atime_ms: stat.atime.map(|v| v as f64),
      birthtime_ms: stat.birthtime.map(|v| v as f64),
      ctime_ms: stat.ctime.map(|v| v as f64),
      dev: stat.dev as f64,
      ino: stat.ino.unwrap_or(0) as f64,
      mode: stat.mode,
      nlink: stat.nlink.unwrap_or(0) as f64,
      uid: stat.uid,
      gid: stat.gid,
      rdev: stat.rdev as f64,
      blksize: stat.blksize as f64,
      blocks: stat.blocks.unwrap_or(0) as f64,
      is_block_device: stat.is_block_device,
      is_char_device: stat.is_char_device,
      is_fifo: stat.is_fifo,
      is_socket: stat.is_socket,
    }
  }
}

#[op2]
#[serde]
pub fn op_node_fs_fstat_sync(
  state: &mut OpState,
  fd: i32,
) -> Result<NodeFsStat, FsError> {
  let file = file_for_fd(state, fd)?;
  let stat = file.stat_sync()?;
  Ok(NodeFsStat::from(stat))
}

#[op2]
#[serde]
pub async fn op_node_fs_fstat(
  state: Rc<RefCell<OpState>>,
  fd: i32,
) -> Result<NodeFsStat, FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  let stat = file.stat_async().await?;
  Ok(NodeFsStat::from(stat))
}

#[op2(fast)]
pub fn op_node_fs_ftruncate_sync(
  state: &mut OpState,
  fd: i32,
  #[number] len: u64,
) -> Result<(), FsError> {
  let file = file_for_fd(state, fd)?;
  file.truncate_sync(len)?;
  Ok(())
}

#[op2]
pub async fn op_node_fs_ftruncate(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[number] len: u64,
) -> Result<(), FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  file.truncate_async(len).await?;
  Ok(())
}

#[op2(fast)]
pub fn op_node_fs_fsync_sync(
  state: &mut OpState,
  fd: i32,
) -> Result<(), FsError> {
  let file = file_for_fd(state, fd)?;
  file.sync_sync()?;
  Ok(())
}

#[op2]
pub async fn op_node_fs_fsync(
  state: Rc<RefCell<OpState>>,
  fd: i32,
) -> Result<(), FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  file.sync_async().await?;
  Ok(())
}

#[op2(fast)]
pub fn op_node_fs_fdatasync_sync(
  state: &mut OpState,
  fd: i32,
) -> Result<(), FsError> {
  let file = file_for_fd(state, fd)?;
  file.datasync_sync()?;
  Ok(())
}

#[op2]
pub async fn op_node_fs_fdatasync(
  state: Rc<RefCell<OpState>>,
  fd: i32,
) -> Result<(), FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  file.datasync_async().await?;
  Ok(())
}

#[op2(fast)]
pub fn op_node_fs_futimes_sync(
  state: &mut OpState,
  fd: i32,
  #[number] atime_secs: i64,
  #[smi] atime_nanos: u32,
  #[number] mtime_secs: i64,
  #[smi] mtime_nanos: u32,
) -> Result<(), FsError> {
  let file = file_for_fd(state, fd)?;
  file.utime_sync(atime_secs, atime_nanos, mtime_secs, mtime_nanos)?;
  Ok(())
}

#[op2]
pub async fn op_node_fs_futimes(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[number] atime_secs: i64,
  #[smi] atime_nanos: u32,
  #[number] mtime_secs: i64,
  #[smi] mtime_nanos: u32,
) -> Result<(), FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  file
    .utime_async(atime_secs, atime_nanos, mtime_secs, mtime_nanos)
    .await?;
  Ok(())
}

#[op2(fast)]
pub fn op_node_fs_fchmod_sync(
  state: &mut OpState,
  fd: i32,
  #[smi] mode: u32,
) -> Result<(), FsError> {
  let file = file_for_fd(state, fd)?;
  file.chmod_sync(mode)?;
  Ok(())
}

#[op2]
pub async fn op_node_fs_fchmod(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[smi] mode: u32,
) -> Result<(), FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  file.chmod_async(mode).await?;
  Ok(())
}

#[op2(fast)]
pub fn op_node_fs_fchown_sync(
  state: &mut OpState,
  fd: i32,
  #[smi] uid: u32,
  #[smi] gid: u32,
) -> Result<(), FsError> {
  let file = file_for_fd(state, fd)?;
  file.chown_sync(Some(uid), Some(gid))?;
  Ok(())
}

#[op2]
pub async fn op_node_fs_fchown(
  state: Rc<RefCell<OpState>>,
  fd: i32,
  #[smi] uid: u32,
  #[smi] gid: u32,
) -> Result<(), FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  file.chown_async(Some(uid), Some(gid)).await?;
  Ok(())
}

#[op2]
#[buffer]
pub fn op_node_fs_read_file_sync(
  state: &mut OpState,
  fd: i32,
) -> Result<Vec<u8>, FsError> {
  let file = file_for_fd(state, fd)?;
  let buf = file.read_all_sync()?;
  Ok(buf.to_vec())
}

#[op2]
#[buffer]
pub async fn op_node_fs_read_file(
  state: Rc<RefCell<OpState>>,
  fd: i32,
) -> Result<Vec<u8>, FsError> {
  let file = file_for_fd(&state.borrow(), fd)?;
  let buf = file.read_all_async().await?;
  Ok(buf.to_vec())
}

const CP_IS_DEST_EXISTS_FLAG: u64 = 1u64 << 32;
const CP_IS_SRC_DIRECTORY_FLAG: u64 = 1u64 << 33;
const CP_IS_SRC_FILE_FLAG: u64 = 1u64 << 34;
const CP_IS_SRC_CHAR_DEVICE_FLAG: u64 = 1u64 << 35;
const CP_IS_SRC_BLOCK_DEVICE_FLAG: u64 = 1u64 << 36;
const CP_IS_SRC_SYMLINK_FLAG: u64 = 1u64 << 37;
const CP_IS_SRC_SOCKET_FLAG: u64 = 1u64 << 38;
const CP_IS_SRC_FIFO_FLAG: u64 = 1u64 << 39;

/// Bit-packed stat metadata passed to JS for `cp` operations.
///
/// Layout (u64):
/// - bits 0..31  : src mode (`st_mode`)
/// - bit 32      : destination exists
/// - bits 33..39 : source type flags (dir, file, char/block device, symlink, socket, fifo)
fn compact_stat_info(
  src_stat: &deno_io::fs::FsStat,
  is_dest_exists: bool,
) -> u64 {
  let mut packed = src_stat.mode as u64;
  if is_dest_exists {
    packed |= CP_IS_DEST_EXISTS_FLAG;
  }
  if src_stat.is_file {
    packed |= CP_IS_SRC_FILE_FLAG;
  }
  if src_stat.is_directory {
    packed |= CP_IS_SRC_DIRECTORY_FLAG;
  }
  if src_stat.is_char_device {
    packed |= CP_IS_SRC_CHAR_DEVICE_FLAG;
  }
  if src_stat.is_block_device {
    packed |= CP_IS_SRC_BLOCK_DEVICE_FLAG;
  }
  if src_stat.is_symlink {
    packed |= CP_IS_SRC_SYMLINK_FLAG;
  }
  if src_stat.is_socket {
    packed |= CP_IS_SRC_SOCKET_FLAG;
  }
  if src_stat.is_fifo {
    packed |= CP_IS_SRC_FIFO_FLAG;
  }
  packed
}

struct CpCheckPathsSyncResult {
  is_dest_exists: bool,
  is_src_directory: bool,
  is_src_file: bool,
  is_src_char_device: bool,
  is_src_block_device: bool,
  is_src_symlink: bool,
  is_src_socket: bool,
  is_src_fifo: bool,
  src_mode: u32,
  src_dev: u64,
  src_ino: u64,
}

// To save the cost of multiple round trips between Rust and JS,
// we pack the necessary metadata for `cp` operations into a single u64 value and pass it to JS.
#[derive(Debug)]
struct CpCheckPathsResult {
  src_dev: u64,
  src_ino: u64,
  stat_info: u64,
}

#[derive(Clone, Copy)]
struct CpSyncOptions<'a> {
  dereference: bool,
  recursive: bool,
  force: bool,
  error_on_exist: bool,
  preserve_timestamps: bool,
  verbatim_symlinks: bool,
  mode: u32,
  filter: Option<v8::Local<'a, v8::Function>>,
}

enum CpSyncRunStatus {
  Completed,
  JsException,
}

fn call_cp_sync_filter<'a>(
  scope: &mut v8::PinScope<'a, '_>,
  filter: v8::Local<'a, v8::Function>,
  src: &str,
  dest: &str,
) -> Option<bool> {
  v8::tc_scope!(tc_scope, scope);

  let recv = v8::undefined(tc_scope);
  let src = v8::String::new(tc_scope, src).unwrap();
  let dest = v8::String::new(tc_scope, dest).unwrap();

  let result = filter.call(tc_scope, recv.into(), &[src.into(), dest.into()]);
  if tc_scope.has_caught() || tc_scope.has_terminated() {
    tc_scope.rethrow();
    return None;
  }

  Some(result.unwrap().boolean_value(tc_scope))
}

fn cp_sync_copy_dir<'a>(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  scope: &mut v8::PinScope<'a, '_>,
  src: &str,
  dest: &str,
  opts: CpSyncOptions<'a>,
) -> Result<CpSyncRunStatus, FsError> {
  let src_path = check_cp_path(state, src, OpenAccessKind::ReadNoFollow)?;
  let entries =
    fs.read_dir_sync(&src_path.as_checked_path())
      .map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(src.to_string()),
            syscall: Some("opendir".into()),
            ..Default::default()
          },
        )
      })?;

  for entry in entries {
    let src_item = Path::new(src)
      .join(&entry.name)
      .to_string_lossy()
      .to_string();
    let dest_item = Path::new(dest)
      .join(&entry.name)
      .to_string_lossy()
      .to_string();

    if let Some(filter) = opts.filter {
      let Some(should_copy) =
        call_cp_sync_filter(scope, filter, &src_item, &dest_item)
      else {
        return Ok(CpSyncRunStatus::JsException);
      };

      if !should_copy {
        continue;
      }
    }

    let stat_info = check_paths_impl_sync(
      state,
      fs,
      &src_item,
      &dest_item,
      opts.dereference,
    )?;

    match cp_sync_dispatch(
      state, fs, scope, &stat_info, &src_item, &dest_item, opts,
    )? {
      CpSyncRunStatus::Completed => {}
      CpSyncRunStatus::JsException => return Ok(CpSyncRunStatus::JsException),
    }
  }

  Ok(CpSyncRunStatus::Completed)
}

fn cp_sync_mkdir_and_copy<'a>(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  scope: &mut v8::PinScope<'a, '_>,
  src_mode: u32,
  src: &str,
  dest: &str,
  opts: CpSyncOptions<'a>,
) -> Result<CpSyncRunStatus, FsError> {
  let dest_path = check_cp_path(state, dest, OpenAccessKind::Write)?;
  fs.mkdir_sync(&dest_path.as_checked_path(), false, None)
    .map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(dest.to_string()),
          syscall: Some("mkdir".into()),
          ..Default::default()
        },
      )
    })?;

  let result = cp_sync_copy_dir(state, fs, scope, src, dest, opts)?;
  if let CpSyncRunStatus::JsException = result {
    return Ok(result);
  }

  set_dest_mode(fs, &dest_path.as_checked_path(), src_mode)?;
  Ok(CpSyncRunStatus::Completed)
}

fn cp_sync_on_dir<'a>(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  scope: &mut v8::PinScope<'a, '_>,
  stat_info: &CpCheckPathsSyncResult,
  src: &str,
  dest: &str,
  opts: CpSyncOptions<'a>,
) -> Result<CpSyncRunStatus, FsError> {
  if !stat_info.is_dest_exists {
    return cp_sync_mkdir_and_copy(
      state,
      fs,
      scope,
      stat_info.src_mode,
      src,
      dest,
      opts,
    );
  }

  cp_sync_copy_dir(state, fs, scope, src, dest, opts)
}

fn cp_sync_dispatch<'a>(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  scope: &mut v8::PinScope<'a, '_>,
  stat_info: &CpCheckPathsSyncResult,
  src: &str,
  dest: &str,
  opts: CpSyncOptions<'a>,
) -> Result<CpSyncRunStatus, FsError> {
  if stat_info.is_src_directory && opts.recursive {
    return cp_sync_on_dir(state, fs, scope, stat_info, src, dest, opts);
  } else if stat_info.is_src_directory {
    return Err(
      CpError::EIsDir {
        message: format!("{} is a directory (not copied)", src),
        path: src.to_string(),
      }
      .into(),
    );
  } else if stat_info.is_src_file
    || stat_info.is_src_char_device
    || stat_info.is_src_block_device
  {
    op_node_cp_on_file_sync(state, fs, src, dest, stat_info, &opts)?;
    return Ok(CpSyncRunStatus::Completed);
  } else if stat_info.is_src_symlink {
    op_node_cp_on_link_sync(
      state,
      fs,
      src,
      dest,
      stat_info.is_dest_exists,
      opts.verbatim_symlinks,
    )?;
    return Ok(CpSyncRunStatus::Completed);
  } else if stat_info.is_src_socket {
    return Err(
      CpError::Socket {
        message: format!("cannot copy a socket file: {}", dest),
        path: dest.to_string(),
      }
      .into(),
    );
  } else if stat_info.is_src_fifo {
    return Err(
      CpError::Fifo {
        message: format!("cannot copy a FIFO pipe: {}", dest),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  Err(
    CpError::Unknown {
      message: format!("cannot copy an unknown file type: {}", dest),
      path: dest.to_string(),
    }
    .into(),
  )
}

/// Check if two stat results refer to the same file (same dev + ino).
fn are_identical_stat(
  src_stat: &deno_io::fs::FsStat,
  dest_stat: &deno_io::fs::FsStat,
) -> bool {
  match (dest_stat.ino, src_stat.ino) {
    (Some(dest_ino), Some(src_ino)) if dest_ino > 0 && dest_stat.dev > 0 => {
      dest_ino == src_ino && dest_stat.dev == src_stat.dev
    }
    _ => false,
  }
}

fn is_src_subdir(src: &str, dest: &str) -> bool {
  let src_resolved =
    std::path::absolute(src).unwrap_or_else(|_| PathBuf::from(src));
  let dest_resolved =
    std::path::absolute(dest).unwrap_or_else(|_| PathBuf::from(dest));

  let src_components = src_resolved.components().collect::<Vec<_>>();
  let dest_components = dest_resolved.components().collect::<Vec<_>>();

  src_components
    .iter()
    .enumerate()
    .all(|(i, c)| dest_components.get(i) == Some(c))
}

/// As this function attempts to get the absolute path of the target,
/// callers of this function should ensure that the permissions are granted
/// with at minimum using `.check_read_all()`.
fn cp_symlink_type(
  fs: &FileSystemRc,
  target: &CheckedPathBuf,
  link_path: &CheckedPathBuf,
) -> Option<FsFileType> {
  #[cfg(windows)]
  {
    // Mirror node polyfill behavior: resolve target relative to the link
    // path, infer dir/file from stat, and default to file on any error.
    // https://github.com/nodejs/node/blob/70f6b58ac655234435a99d72b857dd7b316d34bf/lib/fs.js#L1806-L1837
    if let Ok(absolute_target) = std::path::absolute(
      Path::new(link_path.as_os_str())
        .join("..")
        .join(target.as_os_str()),
    ) {
      let checked_target = CheckedPathBuf::unsafe_new(absolute_target);
      let checked_target = checked_target.as_checked_path();
      if let Ok(stat) = fs.stat_sync(&checked_target)
        && stat.is_directory
      {
        return Some(FsFileType::Directory);
      }
    }

    Some(FsFileType::File)
  }

  #[cfg(not(windows))]
  {
    let _ = (fs, target, link_path);
    None
  }
}

#[allow(clippy::unused_async, reason = "sometimes it's async")]
async fn cp_create_symlink(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  target: String,
  link_path: String,
) -> Result<(), FsError> {
  {
    let mut state = state.borrow_mut();
    let permissions = state.borrow_mut::<PermissionsContainer>();
    permissions.check_write_all("node:fs.symlink")?;
    permissions.check_read_all("node:fs.symlink")?;
  }
  let fs = fs.clone();
  maybe_spawn_blocking!(move || -> Result<(), FsError> {
    // PERMISSIONS: ok because we verified --allow-write and --allow-read above
    let oldpath = CheckedPathBuf::unsafe_new(PathBuf::from(&target));
    let newpath = CheckedPathBuf::unsafe_new(PathBuf::from(&link_path));
    let file_type = cp_symlink_type(&fs, &oldpath, &newpath);
    let oldpath = oldpath.as_checked_path();
    let newpath = newpath.as_checked_path();

    fs.symlink_sync(&oldpath, &newpath, file_type)
      .map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(target),
            dest: Some(link_path),
            syscall: Some("symlink".into()),
            ..Default::default()
          },
        )
      })?;
    Ok(())
  })
}

fn check_cp_path(
  state: &Rc<RefCell<OpState>>,
  path: &str,
  access_kind: OpenAccessKind,
) -> Result<CheckedPathBuf, FsError> {
  let mut state = state.borrow_mut();
  Ok(
    state
      .borrow_mut::<PermissionsContainer>()
      .check_open(
        Cow::Owned(PathBuf::from(path)),
        access_kind,
        Some("node:fs.cp"),
      )?
      .into_owned(),
  )
}

fn check_paths_impl_sync(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  dest: &str,
  dereference: bool,
) -> Result<CpCheckPathsSyncResult, FsError> {
  let (src_stat_result, dest_result, syscall) = if dereference {
    let src_path = check_cp_path(state, src, OpenAccessKind::Read)?;
    let dest_path = check_cp_path(state, dest, OpenAccessKind::Read)?;
    (
      fs.stat_sync(&src_path.as_checked_path()),
      fs.stat_sync(&dest_path.as_checked_path()),
      "stat".to_string(),
    )
  } else {
    let src_path = check_cp_path(state, src, OpenAccessKind::ReadNoFollow)?;
    let dest_path = check_cp_path(state, dest, OpenAccessKind::ReadNoFollow)?;
    (
      fs.lstat_sync(&src_path.as_checked_path()),
      fs.lstat_sync(&dest_path.as_checked_path()),
      "lstat".to_string(),
    )
  };

  let src_stat = src_stat_result.map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(src.to_string()),
        syscall: Some(syscall.to_string()),
        ..Default::default()
      },
    )
  })?;

  let dest_stat = match dest_result {
    Ok(stat) => Some(stat),
    Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
    Err(e) => {
      return Err(map_fs_error_to_node_fs_error(
        e,
        NodeFsErrorContext {
          path: Some(dest.to_string()),
          syscall: Some(syscall),
          ..Default::default()
        },
      ));
    }
  };

  let src_dev = src_stat.dev;
  let src_ino = src_stat.ino.unwrap_or(0);

  if let Some(ref dest_stat) = dest_stat {
    if are_identical_stat(&src_stat, dest_stat) {
      return Err(
        CpError::EInval {
          message: "src and dest cannot be the same".to_string(),
          path: dest.to_string(),
        }
        .into(),
      );
    }
    if src_stat.is_directory && !dest_stat.is_directory {
      return Err(
        CpError::DirToNonDir {
          message: format!(
            "cannot overwrite non-directory {} with directory {}",
            dest, src
          ),
          path: dest.to_string(),
        }
        .into(),
      );
    }
    if !src_stat.is_directory && dest_stat.is_directory {
      return Err(
        CpError::NonDirToDir {
          message: format!(
            "cannot overwrite directory {} with non-directory {}",
            dest, src
          ),
          path: dest.to_string(),
        }
        .into(),
      );
    }
  }

  if src_stat.is_directory && is_src_subdir(src, dest) {
    return Err(
      CpError::EInval {
        message: format!(
          "cannot copy {} to a subdirectory of self {}",
          src, dest
        ),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  Ok(CpCheckPathsSyncResult {
    src_dev,
    src_ino,
    src_mode: src_stat.mode,
    is_dest_exists: dest_stat.is_some(),
    is_src_directory: src_stat.is_directory,
    is_src_file: src_stat.is_file,
    is_src_char_device: src_stat.is_char_device,
    is_src_block_device: src_stat.is_block_device,
    is_src_symlink: src_stat.is_symlink,
    is_src_socket: src_stat.is_socket,
    is_src_fifo: src_stat.is_fifo,
  })
}

/// Validates src and dest paths for a cp operation.
/// Checks identity, directory type conflicts, and subdirectory relationships.
#[allow(clippy::unused_async, reason = "sometimes async depending on cfg")]
async fn check_paths_impl(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  dest: &str,
  dereference: bool,
) -> Result<CpCheckPathsResult, FsError> {
  let open_access_kind = if dereference {
    OpenAccessKind::Read
  } else {
    OpenAccessKind::ReadNoFollow
  };

  let src_path = check_cp_path(state, src, open_access_kind)?;
  let dest_path = check_cp_path(state, dest, open_access_kind)?;

  let fs = fs.clone();
  let (src_stat_result, dest_result, syscall) =
    maybe_spawn_blocking!(move || -> (FsResult<_>, FsResult<_>, String) {
      let src_path = src_path.as_checked_path();
      let dest_path = dest_path.as_checked_path();
      if dereference {
        (
          fs.stat_sync(&src_path),
          fs.stat_sync(&dest_path),
          "stat".to_string(),
        )
      } else {
        (
          fs.lstat_sync(&src_path),
          fs.lstat_sync(&dest_path),
          "lstat".to_string(),
        )
      }
    });

  let src_stat = src_stat_result.map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(src.to_string()),
        syscall: Some(syscall.clone()),
        ..Default::default()
      },
    )
  })?;

  let dest_stat = match dest_result {
    Ok(stat) => Some(stat),
    Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
    Err(e) => {
      return Err(map_fs_error_to_node_fs_error(
        e,
        NodeFsErrorContext {
          path: Some(dest.to_string()),
          syscall: Some(syscall),
          ..Default::default()
        },
      ));
    }
  };

  let src_dev = src_stat.dev;
  let src_ino = src_stat.ino.unwrap_or(0);

  if let Some(ref dest_stat) = dest_stat {
    if are_identical_stat(&src_stat, dest_stat) {
      return Err(
        CpError::EInval {
          message: "src and dest cannot be the same".to_string(),
          path: dest.to_string(),
        }
        .into(),
      );
    }
    if src_stat.is_directory && !dest_stat.is_directory {
      return Err(
        CpError::DirToNonDir {
          message: format!(
            "cannot overwrite non-directory {} with directory {}",
            dest, src
          ),
          path: dest.to_string(),
        }
        .into(),
      );
    }
    if !src_stat.is_directory && dest_stat.is_directory {
      return Err(
        CpError::NonDirToDir {
          message: format!(
            "cannot overwrite directory {} with non-directory {}",
            dest, src
          ),
          path: dest.to_string(),
        }
        .into(),
      );
    }
  }

  if src_stat.is_directory && is_src_subdir(src, dest) {
    return Err(
      CpError::EInval {
        message: format!(
          "cannot copy {} to a subdirectory of self {}",
          src, dest
        ),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  Ok(CpCheckPathsResult {
    src_dev,
    src_ino,
    stat_info: compact_stat_info(&src_stat, dest_stat.is_some()),
  })
}

/// Validates src and dest paths for recursive cp operations.
/// Returns stat info for the source file
#[op2(stack_trace)]
#[bigint]
pub async fn op_node_cp_check_paths_recursive(
  state: Rc<RefCell<OpState>>,
  #[string] src: String,
  #[string] dest: String,
  dereference: bool,
) -> Result<u64, FsError> {
  let fs = {
    let state = state.borrow();
    state.borrow::<FileSystemRc>().clone()
  };

  let result = check_paths_impl(&state, &fs, &src, &dest, dereference).await?;

  Ok(result.stat_info)
}

/// Validates src and dest paths, checks parent paths, and ensures
/// parent directory exists
/// Returns stat info for the source file
#[op2(stack_trace)]
#[bigint]
pub async fn op_node_cp_validate_and_prepare(
  state: Rc<RefCell<OpState>>,
  #[string] src: String,
  #[string] dest: String,
  dereference: bool,
) -> Result<u64, FsError> {
  let fs = {
    let state = state.borrow();
    state.borrow::<FileSystemRc>().clone()
  };

  let check_result =
    check_paths_impl(&state, &fs, &src, &dest, dereference).await?;

  check_parent_paths_impl(
    &state,
    &fs,
    &src,
    check_result.src_dev,
    check_result.src_ino,
    &dest,
  )
  .await?;

  ensure_parent_dir_impl(&state, &fs, &dest).await?;

  Ok(check_result.stat_info)
}

/// Validates src and dest paths, checks parent paths, and ensures
/// parent directory exists for cpSync.
/// Returns stat info for the source file.
fn op_node_cp_validate_and_prepare_sync(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  dest: &str,
  dereference: bool,
) -> Result<CpCheckPathsSyncResult, FsError> {
  let check_result = check_paths_impl_sync(state, fs, src, dest, dereference)?;

  check_parent_paths_impl_sync(
    state,
    fs,
    src,
    check_result.src_dev,
    check_result.src_ino,
    dest,
  )?;

  ensure_parent_dir_impl_sync(state, fs, dest)?;

  Ok(check_result)
}

#[op2(fast, reentrant, stack_trace)]
pub fn op_node_cp_sync<'a>(
  state: Rc<RefCell<OpState>>,
  scope: &mut v8::PinScope<'a, '_>,
  #[string] src: &str,
  #[string] dest: &str,
  dereference: bool,
  recursive: bool,
  force: bool,
  error_on_exist: bool,
  preserve_timestamps: bool,
  verbatim_symlinks: bool,
  #[smi] mode: u32,
  filter: v8::Local<'a, v8::Value>,
) -> Result<(), FsError> {
  let fs = {
    let state = state.borrow();
    state.borrow::<FileSystemRc>().clone()
  };

  let stat_info =
    op_node_cp_validate_and_prepare_sync(&state, &fs, src, dest, dereference)?;

  let filter = v8::Local::<v8::Function>::try_from(filter).ok();

  let opts = CpSyncOptions {
    dereference,
    recursive,
    force,
    error_on_exist,
    preserve_timestamps,
    verbatim_symlinks,
    mode,
    filter,
  };

  match cp_sync_dispatch(&state, &fs, scope, &stat_info, src, dest, opts)? {
    // Treat JsException as success here so the pending V8 exception can propagate
    // naturally, preserving the original JS stack instead of rethrowing from Rust.
    CpSyncRunStatus::Completed | CpSyncRunStatus::JsException => Ok(()),
  }
}

/// Recursively check if dest parent is a subdirectory of src.
/// It works for all file types including symlinks since it
/// checks the src and dest inodes. It starts from the deepest
/// parent and stops once it reaches the src parent or the root path.
async fn check_parent_paths_impl(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  src_dev: u64,
  src_ino: u64,
  dest: &str,
) -> Result<(), FsError> {
  let src_parent = Path::new(src)
    .parent()
    .map(Cow::Borrowed)
    .unwrap_or_default();
  let src_parent = deno_path_util::strip_unc_prefix(
    fs.realpath_sync(&CheckedPath::unsafe_new(Cow::Borrowed(&src_parent)))
      .unwrap_or_else(|_| {
        fs.cwd()
          .map(|cwd| cwd.join(&src_parent))
          .unwrap_or_else(|_| src_parent.into_owned())
      }),
  );

  let mut current = Path::new(dest)
    .parent()
    .map(|p| p.to_path_buf())
    .unwrap_or_default();
  current = deno_path_util::strip_unc_prefix(
    fs.realpath_sync(&CheckedPath::unsafe_new(Cow::Borrowed(&current)))
      .unwrap_or_else(|_| std::path::absolute(&current).unwrap_or(current)),
  );

  loop {
    if current == src_parent {
      return Ok(());
    }

    // Check if current is the root
    if current.parent().is_none() || current.parent() == Some(&current) {
      return Ok(());
    }

    let current_str = current.to_string_lossy();
    let checked_path =
      match check_cp_path(state, &current_str, OpenAccessKind::Read) {
        Ok(p) => p,
        // When read permission is ignored, the check returns NotFound.
        // Treat it like a non-existent directory: stop walking.
        Err(FsError::Permission(e))
          if e.kind() == std::io::ErrorKind::NotFound =>
        {
          return Ok(());
        }
        Err(e) => return Err(e),
      };
    let stat_result = fs.stat_async(checked_path).await;
    match stat_result {
      Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
      Err(e) => {
        return Err(map_fs_error_to_node_fs_error(
          e,
          NodeFsErrorContext {
            path: Some(current_str.to_string()),
            syscall: Some("stat".to_string()),
            ..Default::default()
          },
        ));
      }
      Ok(dest_stat) => {
        // Check if src and current parent are identical (same dev + ino)
        if let Some(dest_ino) = dest_stat.ino
          && dest_ino == src_ino
          && dest_stat.dev == src_dev
        {
          return Err(
            CpError::EInval {
              message: format!(
                "cannot copy {} to a subdirectory of self {}",
                src, dest
              ),
              path: dest.to_string(),
            }
            .into(),
          );
        }
      }
    }

    current = match current.parent() {
      Some(p) => p.to_path_buf(),
      None => return Ok(()),
    };
  }
}

fn check_parent_paths_impl_sync(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  src_dev: u64,
  src_ino: u64,
  dest: &str,
) -> Result<(), FsError> {
  let src_parent = Path::new(src)
    .parent()
    .map(Cow::Borrowed)
    .unwrap_or_default();
  let src_parent = deno_path_util::strip_unc_prefix(
    fs.realpath_sync(&CheckedPath::unsafe_new(Cow::Borrowed(&src_parent)))
      .unwrap_or_else(|_| {
        fs.cwd()
          .map(|cwd| cwd.join(&src_parent))
          .unwrap_or_else(|_| src_parent.into_owned())
      }),
  );

  let mut current = Path::new(dest)
    .parent()
    .map(|p| p.to_path_buf())
    .unwrap_or_default();
  current = deno_path_util::strip_unc_prefix(
    fs.realpath_sync(&CheckedPath::unsafe_new(Cow::Borrowed(&current)))
      .unwrap_or_else(|_| std::path::absolute(&current).unwrap_or(current)),
  );

  loop {
    if current == src_parent {
      return Ok(());
    }

    // Check if current is the root
    if current.parent().is_none() || current.parent() == Some(&current) {
      return Ok(());
    }

    let current_str = current.to_string_lossy();
    let checked_path =
      match check_cp_path(state, &current_str, OpenAccessKind::Read) {
        Ok(p) => p,
        // When read permission is ignored, the check returns NotFound.
        // Treat it like a non-existent directory: stop walking.
        Err(FsError::Permission(e))
          if e.kind() == std::io::ErrorKind::NotFound =>
        {
          return Ok(());
        }
        Err(e) => return Err(e),
      };
    match fs.stat_sync(&checked_path.as_checked_path()) {
      Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
      Err(e) => {
        return Err(map_fs_error_to_node_fs_error(
          e,
          NodeFsErrorContext {
            path: Some(current_str.to_string()),
            syscall: Some("stat".to_string()),
            ..Default::default()
          },
        ));
      }
      Ok(dest_stat) => {
        // Check if src and current parent are identical (same dev + ino)
        if let Some(dest_ino) = dest_stat.ino
          && dest_ino == src_ino
          && dest_stat.dev == src_dev
        {
          return Err(
            CpError::EInval {
              message: format!(
                "cannot copy {} to a subdirectory of self {}",
                src, dest
              ),
              path: dest.to_string(),
            }
            .into(),
          );
        }
      }
    }

    current = match current.parent() {
      Some(p) => p.to_path_buf(),
      None => return Ok(()),
    };
  }
}

/// Ensures the parent directory of `dest` exists, creating it recursively
/// if needed.
async fn ensure_parent_dir_impl(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  dest: &str,
) -> Result<(), FsError> {
  let dest_parent = Path::new(dest)
    .parent()
    .map(|p| p.to_path_buf())
    .unwrap_or_default();

  let parent_str = dest_parent.to_string_lossy();
  let checked_parent = check_cp_path(state, &parent_str, OpenAccessKind::Read)?;
  let exists = fs.exists_async(checked_parent).await.map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(parent_str.to_string()),
        syscall: Some("exists".into()),
        ..Default::default()
      },
    )
  })?;
  if !exists {
    let checked_parent =
      check_cp_path(state, &parent_str, OpenAccessKind::Write)?;
    fs.mkdir_async(checked_parent, true, None)
      .await
      .map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(parent_str.to_string()),
            syscall: Some("mkdir".into()),
            ..Default::default()
          },
        )
      })?;
  }
  Ok(())
}

fn ensure_parent_dir_impl_sync(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  dest: &str,
) -> Result<(), FsError> {
  let dest_parent = Path::new(dest)
    .parent()
    .map(|p| p.to_path_buf())
    .unwrap_or_default();

  let parent_str = dest_parent.to_string_lossy();
  let checked_parent = check_cp_path(state, &parent_str, OpenAccessKind::Read)?;
  let exists = fs.exists_sync(&checked_parent.as_checked_path());

  if !exists {
    let checked_parent =
      check_cp_path(state, &parent_str, OpenAccessKind::Write)?;
    fs.mkdir_sync(&checked_parent.as_checked_path(), true, None)
      .map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(parent_str.to_string()),
            syscall: Some("mkdir".into()),
            ..Default::default()
          },
        )
      })?;
  }

  Ok(())
}

fn handle_timestamps_and_mode(
  fs: &FileSystemRc,
  src_path: &CheckedPath,
  dest_path: &CheckedPath,
  src_mode: u32,
) -> Result<(), FsError> {
  // Make sure the file is writable before setting the timestamp
  // otherwise open fails with EPERM when invoked with 'r+' (through utimes call)
  if file_is_not_writable(src_mode) {
    let mode = src_mode | 0o200;
    set_dest_mode(fs, dest_path, mode)?;
  }

  // Set timestamps from a fresh stat of src (atime is modified by read).
  set_dest_timestamps_and_mode(fs, src_path, dest_path, src_mode)?;
  Ok(())
}

fn file_is_not_writable(mode: u32) -> bool {
  (mode & 0o200) == 0
}

fn cp_mode_has_copyfile_excl(mode: u32) -> bool {
  let copyfile_excl = UV_FS_COPYFILE_EXCL as u32;
  (mode & copyfile_excl) == copyfile_excl
}

fn set_dest_mode(
  fs: &FileSystemRc,
  dest_path: &CheckedPath,
  mode: u32,
) -> Result<(), FsError> {
  if mode == 0 {
    return Ok(());
  }

  fs.chmod_sync(dest_path, mode as _).map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(dest_path.to_string_lossy().to_string()),
        syscall: Some("chmod".into()),
        ..Default::default()
      },
    )
  })?;
  Ok(())
}

fn set_dest_timestamps_and_mode(
  fs: &FileSystemRc,
  src_path: &CheckedPath,
  dest_path: &CheckedPath,
  src_mode: u32,
) -> Result<(), FsError> {
  // Re-stat src to get fresh atime/mtime
  let src_stat = fs.stat_sync(src_path).map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(src_path.to_string_lossy().to_string()),
        syscall: Some("stat".into()),
        ..Default::default()
      },
    )
  })?;

  if let (Some(atime), Some(mtime)) = (src_stat.atime, src_stat.mtime) {
    // FsStat stores times as milliseconds since the Unix epoch.
    // utime_async expects split values: whole seconds + nanoseconds remainder.
    let atime_secs = (atime / 1000) as i64;
    // Remaining milliseconds are converted to nanoseconds.
    let atime_nanos = ((atime % 1000) * 1_000_000) as u32;
    let mtime_secs = (mtime / 1000) as i64;
    // Same conversion for mtime: ms remainder -> ns.
    let mtime_nanos = ((mtime % 1000) * 1_000_000) as u32;
    fs.utime_sync(dest_path, atime_secs, atime_nanos, mtime_secs, mtime_nanos)
      .map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(dest_path.to_string_lossy().to_string()),
            syscall: Some("utime".into()),
            ..Default::default()
          },
        )
      })?;
  }

  set_dest_mode(fs, dest_path, src_mode)?;
  Ok(())
}

/// Handle copying a single file.
///
/// If dest does not exist, copies src to dest directly.
/// If dest exists and force is true, removes dest and copies.
/// If dest exists and error_on_exist is true, returns an EExist error.
/// Otherwise does nothing.
///
/// When preserve_timestamps is true, copies the timestamps from src to dest
/// and ensures the file is writable before doing so.
#[op2(stack_trace)]
pub async fn op_node_cp_on_file(
  state: Rc<RefCell<OpState>>,
  #[string] src: String,
  #[string] dest: String,
  #[smi] src_mode: u32,
  dest_exists: bool,
  force: bool,
  error_on_exist: bool,
  preserve_timestamps: bool,
  #[smi] mode: u32,
) -> Result<(), FsError> {
  let fs = {
    let state = state.borrow();
    state.borrow::<FileSystemRc>().clone()
  };

  if dest_exists {
    if force {
      // Remove dest, then copy
      let dest_path = check_cp_path(&state, &dest, OpenAccessKind::Write)?;
      fs.remove_async(dest_path, false).await.map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(dest.clone()),
            syscall: Some("unlink".into()),
            ..Default::default()
          },
        )
      })?;
    } else if error_on_exist {
      return Err(
        CpError::EExist {
          message: format!("{} already exists", dest),
          path: dest.to_string(),
        }
        .into(),
      );
    } else {
      // Neither force nor errorOnExist: do nothing
      return Ok(());
    }
  }

  // Copy file: read from src, write to dest
  if cp_mode_has_copyfile_excl(mode) {
    let dest_path = check_cp_path(&state, &dest, OpenAccessKind::ReadNoFollow)?;
    match fs.lstat_async(dest_path.clone()).await {
      Ok(_) => {
        return Err(
          CpError::EExist {
            message: format!("{} already exists", dest),
            path: dest.to_string(),
          }
          .into(),
        );
      }
      Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
      Err(err) => {
        return Err(map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(dest.to_string()),
            syscall: Some("lstat".into()),
            ..Default::default()
          },
        ));
      }
    }
  }

  let src_path = check_cp_path(&state, &src, OpenAccessKind::Read)?;
  let dest_path = check_cp_path(&state, &dest, OpenAccessKind::Write)?;

  maybe_spawn_blocking!(move || -> Result<(), FsError> {
    fs.copy_file_sync(
      &src_path.as_checked_path(),
      &dest_path.as_checked_path(),
    )
    .map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(src_path.to_string_lossy().to_string()),
          dest: Some(dest_path.to_string_lossy().to_string()),
          syscall: Some("copyfile".into()),
          ..Default::default()
        },
      )
    })?;
    if preserve_timestamps {
      handle_timestamps_and_mode(
        &fs,
        &src_path.as_checked_path(),
        &dest_path.as_checked_path(),
        src_mode,
      )?;
    } else {
      set_dest_mode(&fs, &dest_path.as_checked_path(), src_mode)?;
    }
    Ok(())
  })
}

fn op_node_cp_on_file_sync(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  dest: &str,
  stat_info: &CpCheckPathsSyncResult,
  opts: &CpSyncOptions,
) -> Result<(), FsError> {
  if stat_info.is_dest_exists {
    if opts.force {
      // Remove dest, then copy.
      let dest_path = check_cp_path(state, dest, OpenAccessKind::Write)?;
      fs.remove_sync(&dest_path.as_checked_path(), false)
        .map_err(|err| {
          map_fs_error_to_node_fs_error(
            err,
            NodeFsErrorContext {
              path: Some(dest.to_string()),
              syscall: Some("unlink".into()),
              ..Default::default()
            },
          )
        })?;
    } else if opts.error_on_exist {
      return Err(
        CpError::EExist {
          message: format!("{} already exists", dest),
          path: dest.to_string(),
        }
        .into(),
      );
    } else {
      // Neither force nor errorOnExist: do nothing.
      return Ok(());
    }
  }

  if cp_mode_has_copyfile_excl(opts.mode) {
    let dest_path = check_cp_path(state, dest, OpenAccessKind::ReadNoFollow)?;
    match fs.lstat_sync(&dest_path.as_checked_path()) {
      Ok(_) => {
        return Err(
          CpError::EExist {
            message: format!("{} already exists", dest),
            path: dest.to_string(),
          }
          .into(),
        );
      }
      Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
      Err(err) => {
        return Err(map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(dest.to_string()),
            syscall: Some("lstat".into()),
            ..Default::default()
          },
        ));
      }
    }
  }

  let src_path = check_cp_path(state, src, OpenAccessKind::Read)?;
  let dest_path = check_cp_path(state, dest, OpenAccessKind::Write)?;

  fs.copy_file_sync(&src_path.as_checked_path(), &dest_path.as_checked_path())
    .map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(src.to_string()),
          dest: Some(dest.to_string()),
          syscall: Some("copyfile".into()),
          ..Default::default()
        },
      )
    })?;

  if opts.preserve_timestamps {
    handle_timestamps_and_mode(
      fs,
      &src_path.as_checked_path(),
      &dest_path.as_checked_path(),
      stat_info.src_mode,
    )?;
  } else {
    set_dest_mode(fs, &dest_path.as_checked_path(), stat_info.src_mode)?;
  }

  Ok(())
}

#[op2(stack_trace)]
pub async fn op_node_cp_on_link(
  state: Rc<RefCell<OpState>>,
  #[string] src: String,
  #[string] dest: String,
  dest_exists: bool,
  verbatim_symlinks: bool,
) -> Result<(), FsError> {
  let fs = {
    let state = state.borrow();
    state.borrow::<FileSystemRc>().clone()
  };

  let src_path = check_cp_path(&state, &src, OpenAccessKind::ReadNoFollow)?;
  let resolved_src_buf =
    fs.read_link_async(src_path.clone()).await.map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(src.clone()),
          syscall: Some("readlink".into()),
          ..Default::default()
        },
      )
    })?;
  let mut resolved_src = resolved_src_buf.to_string_lossy().to_string();

  // Resolve relative symlink targets
  if !verbatim_symlinks
    && !Path::new(&resolved_src).is_absolute()
    && let Some(parent) = Path::new(&src).parent()
  {
    resolved_src = parent.join(&resolved_src).to_string_lossy().to_string();
  }

  if !dest_exists {
    cp_create_symlink(&state, &fs, resolved_src.to_string(), dest).await?;
    return Ok(());
  }

  // Dest exists — try to read it as a symlink
  let dest_path = check_cp_path(&state, &dest, OpenAccessKind::ReadNoFollow)?;
  let resolved_dest_result = fs.read_link_async(dest_path).await;
  let resolved_dest = match resolved_dest_result {
    Ok(p) => {
      let s = p.to_string_lossy().to_string();
      // If relative, resolve against dirname(dest)
      if !Path::new(&s).is_absolute() {
        if let Some(parent) = Path::new(&dest).parent() {
          parent.join(&s).to_string_lossy().to_string()
        } else {
          s
        }
      } else {
        s
      }
    }
    Err(e) => {
      let kind = e.kind();
      // EINVAL or UNKNOWN means dest is a regular file/directory, not a symlink
      if kind == std::io::ErrorKind::InvalidInput
        || kind == std::io::ErrorKind::Other
      {
        cp_create_symlink(
          &state,
          &fs,
          resolved_src.to_string(),
          dest.to_string(),
        )
        .await?;
        return Ok(());
      }

      #[cfg(windows)]
      {
        use winapi::shared::winerror::ERROR_NOT_A_REPARSE_POINT;

        let os_error = e.into_io_error();
        let Some(errno) = os_error.raw_os_error() else {
          return Err(FsError::Io(os_error));
        };

        let errno = errno as u32;
        if errno != ERROR_NOT_A_REPARSE_POINT {
          return Err(
            NodeFsError {
              os_errno: errno as _,
              context: NodeFsErrorContext {
                path: Some(resolved_src),
                dest: Some(dest),
                syscall: Some("symlink".into()),
                ..Default::default()
              },
            }
            .into(),
          );
        }

        return cp_create_symlink(
          &state,
          &fs,
          resolved_src.to_string(),
          dest.to_string(),
        )
        .await;
      }
      #[cfg(not(windows))]
      {
        return Err(map_fs_error_to_node_fs_error(
          e,
          NodeFsErrorContext {
            path: Some(resolved_src),
            dest: Some(dest),
            syscall: Some("symlink".into()),
            ..Default::default()
          },
        ));
      }
    }
  };

  // Check subdirectory relationships
  let src_path = check_cp_path(&state, &src, OpenAccessKind::Read)?;
  let src_stat = fs.stat_async(src_path).await.map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(src),
        syscall: Some("stat".into()),
        ..Default::default()
      },
    )
  })?;

  let src_is_dir = src_stat.is_directory;
  if src_is_dir && is_src_subdir(&resolved_src, &resolved_dest) {
    return Err(
      CpError::EInval {
        message: format!(
          "cannot copy {} to a subdirectory of self {}",
          resolved_src, resolved_dest
        ),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  // Do not copy if src is a subdir of dest since unlinking
  // dest would remove src contents and create a broken symlink.
  if src_is_dir && is_src_subdir(&resolved_dest, &resolved_src) {
    return Err(
      CpError::SymlinkToSubdirectory {
        message: format!(
          "cannot overwrite {} with {}",
          resolved_dest, resolved_src
        ),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  {
    let mut state = state.borrow_mut();
    let permissions = state.borrow_mut::<PermissionsContainer>();
    permissions.check_write_all("node:fs.cp")?;
    permissions.check_read_all("node:fs.cp")?;
  }

  // Unlink dest and create new symlink
  maybe_spawn_blocking!(move || -> Result<(), FsError> {
    let src_path_buf = CheckedPathBuf::unsafe_new(PathBuf::from(&resolved_src));
    let dest_path_buf = CheckedPathBuf::unsafe_new(PathBuf::from(&dest));
    let src_path = src_path_buf.as_checked_path();
    let dest_path = dest_path_buf.as_checked_path();

    fs.remove_sync(&dest_path, false).map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(dest_path.to_string_lossy().to_string()),
          syscall: Some("unlink".into()),
          ..Default::default()
        },
      )
    })?;

    let file_type = cp_symlink_type(&fs, &src_path_buf, &dest_path_buf);
    fs.symlink_sync(&src_path, &dest_path, file_type)
      .map_err(|err| {
        map_fs_error_to_node_fs_error(
          err,
          NodeFsErrorContext {
            path: Some(src_path.to_string_lossy().to_string()),
            dest: Some(dest_path.to_string_lossy().to_string()),
            syscall: Some("symlink".into()),
            ..Default::default()
          },
        )
      })
  })
}

fn op_node_cp_on_link_sync(
  state: &Rc<RefCell<OpState>>,
  fs: &FileSystemRc,
  src: &str,
  dest: &str,
  dest_exists: bool,
  verbatim_symlinks: bool,
) -> Result<(), FsError> {
  let src_path = check_cp_path(state, src, OpenAccessKind::ReadNoFollow)?;
  let resolved_src_buf = fs
    .read_link_sync(&src_path.as_checked_path())
    .map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(src.to_string()),
          syscall: Some("readlink".into()),
          ..Default::default()
        },
      )
    })?;
  let mut resolved_src = resolved_src_buf.to_string_lossy().to_string();

  // Resolve relative symlink targets.
  if !verbatim_symlinks
    && !Path::new(&resolved_src).is_absolute()
    && let Some(parent) = Path::new(src).parent()
  {
    resolved_src = parent.join(&resolved_src).to_string_lossy().to_string();
  }

  if !dest_exists {
    {
      let mut state = state.borrow_mut();
      state
        .borrow_mut::<PermissionsContainer>()
        .check_write_all("node:fs.symlink")?;
      state
        .borrow_mut::<PermissionsContainer>()
        .check_read_all("node:fs.symlink")?;
    }

    let oldpath = CheckedPathBuf::unsafe_new(PathBuf::from(&resolved_src));
    let newpath = CheckedPathBuf::unsafe_new(PathBuf::from(dest));
    let file_type = cp_symlink_type(fs, &oldpath, &newpath);
    fs.symlink_sync(
      &oldpath.as_checked_path(),
      &newpath.as_checked_path(),
      file_type,
    )
    .map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(resolved_src),
          dest: Some(dest.to_string()),
          syscall: Some("symlink".into()),
          ..Default::default()
        },
      )
    })?;
    return Ok(());
  }

  // Dest exists — try to read it as a symlink.
  let dest_path = check_cp_path(state, dest, OpenAccessKind::ReadNoFollow)?;
  let resolved_dest_result = fs.read_link_sync(&dest_path.as_checked_path());
  let resolved_dest = match resolved_dest_result {
    Ok(p) => {
      let s = p.to_string_lossy().to_string();
      // If relative, resolve against dirname(dest).
      if !Path::new(&s).is_absolute() {
        if let Some(parent) = Path::new(dest).parent() {
          parent.join(&s).to_string_lossy().to_string()
        } else {
          s
        }
      } else {
        s
      }
    }
    Err(e) => {
      let kind = e.kind();
      // EINVAL or UNKNOWN means dest is a regular file/directory, not a symlink.
      if kind == std::io::ErrorKind::InvalidInput
        || kind == std::io::ErrorKind::Other
      {
        {
          let mut state = state.borrow_mut();
          state
            .borrow_mut::<PermissionsContainer>()
            .check_write_all("node:fs.symlink")?;
          state
            .borrow_mut::<PermissionsContainer>()
            .check_read_all("node:fs.symlink")?;
        }

        let oldpath = CheckedPathBuf::unsafe_new(PathBuf::from(&resolved_src));
        let newpath = CheckedPathBuf::unsafe_new(PathBuf::from(dest));
        let file_type = cp_symlink_type(fs, &oldpath, &newpath);
        fs.symlink_sync(
          &oldpath.as_checked_path(),
          &newpath.as_checked_path(),
          file_type,
        )
        .map_err(|err| {
          map_fs_error_to_node_fs_error(
            err,
            NodeFsErrorContext {
              path: Some(resolved_src.clone()),
              dest: Some(dest.to_string()),
              syscall: Some("symlink".into()),
              ..Default::default()
            },
          )
        })?;
        return Ok(());
      }

      #[cfg(windows)]
      {
        use winapi::shared::winerror::ERROR_NOT_A_REPARSE_POINT;

        let os_error = e.into_io_error();
        let Some(errno) = os_error.raw_os_error() else {
          return Err(FsError::Io(os_error));
        };

        let errno = errno as u32;
        if errno != ERROR_NOT_A_REPARSE_POINT {
          return Err(
            NodeFsError {
              os_errno: errno as _,
              context: NodeFsErrorContext {
                path: Some(resolved_src),
                dest: Some(dest.to_string()),
                syscall: Some("symlink".into()),
                ..Default::default()
              },
            }
            .into(),
          );
        }

        {
          let mut state = state.borrow_mut();
          state
            .borrow_mut::<PermissionsContainer>()
            .check_write_all("node:fs.symlink")?;
          state
            .borrow_mut::<PermissionsContainer>()
            .check_read_all("node:fs.symlink")?;
        }

        let oldpath = CheckedPathBuf::unsafe_new(PathBuf::from(&resolved_src));
        let newpath = CheckedPathBuf::unsafe_new(PathBuf::from(dest));
        let file_type = cp_symlink_type(fs, &oldpath, &newpath);
        fs.symlink_sync(
          &oldpath.as_checked_path(),
          &newpath.as_checked_path(),
          file_type,
        )
        .map_err(|err| {
          map_fs_error_to_node_fs_error(
            err,
            NodeFsErrorContext {
              path: Some(resolved_src.clone()),
              dest: Some(dest.to_string()),
              syscall: Some("symlink".into()),
              ..Default::default()
            },
          )
        })?;
        return Ok(());
      }
      #[cfg(not(windows))]
      {
        return Err(map_fs_error_to_node_fs_error(
          e,
          NodeFsErrorContext {
            path: Some(resolved_src),
            dest: Some(dest.to_string()),
            syscall: Some("symlink".into()),
            ..Default::default()
          },
        ));
      }
    }
  };

  // Check subdirectory relationships.
  let src_path = check_cp_path(state, src, OpenAccessKind::Read)?;
  let src_stat = fs.stat_sync(&src_path.as_checked_path()).map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(src.to_string()),
        syscall: Some("stat".into()),
        ..Default::default()
      },
    )
  })?;

  let src_is_dir = src_stat.is_directory;
  if src_is_dir && is_src_subdir(&resolved_src, &resolved_dest) {
    return Err(
      CpError::EInval {
        message: format!(
          "cannot copy {} to a subdirectory of self {}",
          resolved_src, resolved_dest
        ),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  // Do not copy if src is a subdir of dest since unlinking
  // dest would remove src contents and create a broken symlink.
  if src_is_dir && is_src_subdir(&resolved_dest, &resolved_src) {
    return Err(
      CpError::SymlinkToSubdirectory {
        message: format!(
          "cannot overwrite {} with {}",
          resolved_dest, resolved_src
        ),
        path: dest.to_string(),
      }
      .into(),
    );
  }

  let dest_path = {
    let mut state = state.borrow_mut();
    state.borrow_mut::<PermissionsContainer>().check_open(
      Cow::Owned(PathBuf::from(dest)),
      OpenAccessKind::Write,
      Some("node:fs.rm"),
    )?
  };

  fs.remove_sync(&dest_path, false).map_err(|err| {
    map_fs_error_to_node_fs_error(
      err,
      NodeFsErrorContext {
        path: Some(dest_path.to_string_lossy().to_string()),
        syscall: Some("unlink".into()),
        ..Default::default()
      },
    )
  })?;

  {
    let mut state = state.borrow_mut();
    state
      .borrow_mut::<PermissionsContainer>()
      .check_write_all("node:fs.symlink")?;
    state
      .borrow_mut::<PermissionsContainer>()
      .check_read_all("node:fs.symlink")?;
  }

  let src_path_buf = CheckedPathBuf::unsafe_new(PathBuf::from(&resolved_src));
  let dest_path_buf = CheckedPathBuf::unsafe_new(dest_path.to_path_buf());
  let src_path = src_path_buf.as_checked_path();

  let file_type = cp_symlink_type(fs, &src_path_buf, &dest_path_buf);
  fs.symlink_sync(&src_path, &dest_path, file_type)
    .map_err(|err| {
      map_fs_error_to_node_fs_error(
        err,
        NodeFsErrorContext {
          path: Some(src_path.to_string_lossy().to_string()),
          dest: Some(dest_path.to_string_lossy().to_string()),
          syscall: Some("symlink".into()),
          ..Default::default()
        },
      )
    })
}

#[cfg(test)]
mod tests {
  use super::is_src_subdir;

  #[test]
  fn test_is_src_subdir() {
    let base = std::env::temp_dir().join("deno_is_src_subdir_test");
    let src = base.join("src");
    let child = src.join("child");
    let sibling = base.join("sibling");

    let src = src.to_string_lossy().into_owned();
    let child = child.to_string_lossy().into_owned();
    let sibling = sibling.to_string_lossy().into_owned();

    assert!(is_src_subdir(&src, &child));
    assert!(is_src_subdir(&src, &src));
    assert!(!is_src_subdir(&src, &sibling));
    assert!(!is_src_subdir(&child, &src));
  }
}