renfs 0.3.1

Bindings for ZenFS: A filesystem, anywhere
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
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
use std::{
    io::{IoSlice, IoSliceMut},
    time::{SystemTime, UNIX_EPOCH},
};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;

use super::api::{
    Dirent, Metadata, OpenOptions, ReadStreamOptions, StatFs, TempDir, WatchFileOptions,
    WatchOptions, WriteStreamOptions,
};

pub type File = u32;
pub type Dir = JsValue;

pub struct ReadStream {
    value: JsValue,
    iterator: JsValue,
}

pub fn create_read_stream(path: &str, options: ReadStreamOptions) -> Result<ReadStream, JsValue> {
    if options.chunk_size == 0 || options.chunk_size > u32::MAX as usize {
        return Err(invalid_path_error(
            "stream chunk size must be between 1 and u32::MAX",
        ));
    }
    if options.end.is_some_and(|end| end < options.start) {
        return Err(invalid_path_error("stream end must not be before start"));
    }
    const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
    if options.start > MAX_SAFE_INTEGER || options.end.is_some_and(|end| end >= MAX_SAFE_INTEGER) {
        return Err(invalid_path_error(
            "stream byte positions must be JavaScript safe integers",
        ));
    }
    let js_options = Object::new();
    Reflect::set(
        &js_options,
        &JsValue::from_str("highWaterMark"),
        &JsValue::from_f64(options.chunk_size as f64),
    )?;
    if options.start != 0 {
        Reflect::set(
            &js_options,
            &JsValue::from_str("start"),
            &JsValue::from_f64(options.start as f64),
        )?;
    }
    if let Some(end) = options.end {
        Reflect::set(
            &js_options,
            &JsValue::from_str("end"),
            &JsValue::from_f64(end as f64),
        )?;
    }
    let value = call_fs(
        "createReadStream",
        &[JsValue::from_str(path), js_options.into()],
    )?;
    let symbol = js_sys::Symbol::async_iterator();
    let method = Reflect::get(&value, &symbol.into())?.dyn_into::<Function>()?;
    let iterator = method.call0(&value)?;
    Ok(ReadStream { value, iterator })
}

pub async fn stream_read(stream: &mut ReadStream) -> Result<Option<Vec<u8>>, JsValue> {
    let next =
        Reflect::get(&stream.iterator, &JsValue::from_str("next"))?.dyn_into::<Function>()?;
    let promise = next
        .call0(&stream.iterator)?
        .dyn_into::<js_sys::Promise>()?;
    let result = JsFuture::from(promise).await?;
    if Reflect::get(&result, &JsValue::from_str("done"))?.as_bool() == Some(true) {
        return Ok(None);
    }
    let value = Reflect::get(&result, &JsValue::from_str("value"))?;
    if !value.is_instance_of::<Uint8Array>() {
        return Err(JsValue::from_str(
            "ZenFS read stream returned a non-byte chunk",
        ));
    }
    Ok(Some(Uint8Array::new(&value).to_vec()))
}

pub fn read_stream_destroy(stream: &ReadStream) -> Result<(), JsValue> {
    let method =
        Reflect::get(&stream.value, &JsValue::from_str("destroy"))?.dyn_into::<Function>()?;
    method.call0(&stream.value)?;
    Ok(())
}

pub struct WriteStream {
    value: JsValue,
}

pub fn create_write_stream(
    path: &str,
    options: WriteStreamOptions,
) -> Result<WriteStream, JsValue> {
    if options.start.is_some_and(|start| start > (1 << 53) - 1) {
        return Err(invalid_path_error(
            "stream byte positions must be JavaScript safe integers",
        ));
    }
    let js_options = Object::new();
    if let Some(start) = options.start {
        Reflect::set(
            &js_options,
            &JsValue::from_str("start"),
            &JsValue::from_f64(start as f64),
        )?;
    }
    let value = call_fs(
        "createWriteStream",
        &[JsValue::from_str(path), js_options.into()],
    )?;
    Ok(WriteStream { value })
}

pub async fn stream_write(stream: &mut WriteStream, bytes: &[u8]) -> Result<(), JsValue> {
    let write = Reflect::get(&stream.value, &JsValue::from_str("write"))?.dyn_into::<Function>()?;
    let chunk = Uint8Array::from(bytes);
    let promise = js_sys::Promise::new(&mut |resolve, reject| {
        let callback_reject = reject.clone();
        let callback = Closure::once_into_js(move |error: JsValue| {
            if error.is_null() || error.is_undefined() {
                let _ = resolve.call0(&JsValue::UNDEFINED);
            } else {
                let _ = callback_reject.call1(&JsValue::UNDEFINED, &error);
            }
        });
        if let Err(error) = write.call2(&stream.value, &chunk, &callback) {
            let _ = reject.call1(&JsValue::UNDEFINED, &error);
        }
    });
    JsFuture::from(promise).await?;
    Ok(())
}

pub async fn stream_end(stream: &mut WriteStream) -> Result<(), JsValue> {
    let end = Reflect::get(&stream.value, &JsValue::from_str("end"))?.dyn_into::<Function>()?;
    let promise = js_sys::Promise::new(&mut |resolve, reject| {
        let callback = Closure::once_into_js(move || {
            let _ = resolve.call0(&JsValue::UNDEFINED);
        });
        if let Err(error) = end.call1(&stream.value, &callback) {
            let _ = reject.call1(&JsValue::UNDEFINED, &error);
        }
    });
    JsFuture::from(promise).await?;
    Ok(())
}

pub fn write_stream_destroy(stream: &WriteStream) -> Result<(), JsValue> {
    let method =
        Reflect::get(&stream.value, &JsValue::from_str("destroy"))?.dyn_into::<Function>()?;
    method.call0(&stream.value)?;
    Ok(())
}

pub struct Watcher {
    value: JsValue,
    _callback: Closure<dyn FnMut(JsValue, JsValue)>,
}

pub fn watch(
    path: &str,
    options: WatchOptions,
    mut listener: Box<dyn FnMut(&str, &str) + Send>,
) -> Result<Watcher, JsValue> {
    let js_options = Object::new();
    Reflect::set(
        &js_options,
        &JsValue::from_str("recursive"),
        &JsValue::from_bool(options.recursive),
    )?;
    Reflect::set(
        &js_options,
        &JsValue::from_str("persistent"),
        &JsValue::from_bool(options.persistent),
    )?;
    let callback = Closure::wrap(Box::new(move |event: JsValue, name: JsValue| {
        if let (Some(event), Some(name)) = (event.as_string(), name.as_string()) {
            listener(&event, &name);
        }
    }) as Box<dyn FnMut(JsValue, JsValue)>);
    let value = call_fs(
        "watch",
        &[
            JsValue::from_str(path),
            js_options.into(),
            callback.as_ref().clone(),
        ],
    )?;
    Ok(Watcher {
        value,
        _callback: callback,
    })
}

pub fn watch_close(watcher: &Watcher) -> Result<(), JsValue> {
    let close =
        Reflect::get(&watcher.value, &JsValue::from_str("close"))?.dyn_into::<Function>()?;
    close.call0(&watcher.value)?;
    Ok(())
}

thread_local! {
    static FILE_WATCHES: std::cell::RefCell<std::collections::HashMap<String, Vec<(u64, Closure<dyn FnMut(JsValue, JsValue)>)>>> = Default::default();
    static NEXT_FILE_WATCH_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
}

pub fn watch_file(
    path: &str,
    options: WatchFileOptions,
    mut listener: Box<dyn FnMut(Metadata, Metadata) + Send>,
) -> Result<u64, JsValue> {
    if options.interval.is_zero() {
        return Err(invalid_path_error("watch interval must be positive"));
    }
    let js_options = Object::new();
    Reflect::set(
        &js_options,
        &JsValue::from_str("interval"),
        &JsValue::from_f64(options.interval.as_secs_f64() * 1000.0),
    )?;
    Reflect::set(
        &js_options,
        &JsValue::from_str("persistent"),
        &JsValue::from_bool(options.persistent),
    )?;
    let callback = Closure::wrap(Box::new(move |curr: JsValue, prev: JsValue| {
        if let (Ok(curr), Ok(prev)) = (metadata_from_stats(&curr), metadata_from_stats(&prev)) {
            listener(curr, prev);
        }
    }) as Box<dyn FnMut(JsValue, JsValue)>);
    call_fs(
        "watchFile",
        &[
            JsValue::from_str(path),
            js_options.into(),
            callback.as_ref().clone(),
        ],
    )?;
    let id = NEXT_FILE_WATCH_ID.with(|next| {
        let id = next.get();
        next.set(id.wrapping_add(1));
        id
    });
    FILE_WATCHES.with(|watches| {
        watches
            .borrow_mut()
            .entry(path.to_owned())
            .or_default()
            .push((id, callback))
    });
    Ok(id)
}

pub fn unwatch_file(path: &str, id: Option<u64>) -> Result<(), JsValue> {
    FILE_WATCHES.with(|watches| {
        let mut watches = watches.borrow_mut();
        if let Some(id) = id {
            if let Some(list) = watches.get_mut(path) {
                if let Some(index) = list.iter().position(|(candidate, _)| *candidate == id) {
                    call_fs(
                        "unwatchFile",
                        &[JsValue::from_str(path), list[index].1.as_ref().clone()],
                    )?;
                    list.remove(index);
                    if list.is_empty() {
                        watches.remove(path);
                    }
                }
            }
        } else {
            call_fs("unwatchFile", &[JsValue::from_str(path)])?;
            watches.remove(path);
        }
        Ok(())
    })
}

pub fn invalid_path_error(message: &str) -> JsValue {
    JsValue::from_str(message)
}

#[cfg(test)]
#[wasm_bindgen(module = "https://esm.sh/@zenfs/core@2.7.6?bundle&target=es2022")]
extern "C" {
    #[wasm_bindgen(thread_local_v2, js_name = fs)]
    static ZEN_FS: JsValue;
}

#[cfg(test)]
macro_rules! zenfs_setup_imports {
    ($module:literal) => {
        #[wasm_bindgen(module = $module)]
        extern "C" {
            #[wasm_bindgen(catch, js_name = configure)]
            fn zenfs_configure(configuration: &JsValue) -> Result<js_sys::Promise, JsValue>;
            #[wasm_bindgen(catch, js_name = configureSync)]
            fn zenfs_configure_sync(configuration: &JsValue) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = configureSingle)]
            fn zenfs_configure_single(configuration: &JsValue) -> Result<js_sys::Promise, JsValue>;
            #[wasm_bindgen(catch, js_name = configureSingleSync)]
            fn zenfs_configure_single_sync(configuration: &JsValue) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = configureFileSystem)]
            fn zenfs_configure_file_system(
                filesystem: &JsValue,
                configuration: &JsValue,
            ) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = resolveMountConfig)]
            fn zenfs_resolve_mount_config(
                configuration: &JsValue,
            ) -> Result<js_sys::Promise, JsValue>;
            #[wasm_bindgen(catch, js_name = resolveMountConfigSync)]
            fn zenfs_resolve_mount_config_sync(configuration: &JsValue)
            -> Result<JsValue, JsValue>;
            #[wasm_bindgen(catch, js_name = resolveRemoteMount)]
            fn zenfs_resolve_remote_mount(
                channel: &JsValue,
                configuration: &JsValue,
            ) -> Result<js_sys::Promise, JsValue>;
            #[wasm_bindgen(catch, js_name = mount)]
            fn zenfs_mount(mount_point: &str, filesystem: &JsValue) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = umount)]
            fn zenfs_umount(mount_point: &str) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = sync)]
            fn zenfs_sync() -> Result<js_sys::Promise, JsValue>;
            #[wasm_bindgen(catch, js_name = waitOnline)]
            fn zenfs_wait_online(worker: &JsValue) -> Result<js_sys::Promise, JsValue>;
            #[wasm_bindgen(catch, js_name = attachFS)]
            fn zenfs_attach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = detachFS)]
            fn zenfs_detach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue>;
            #[wasm_bindgen(catch, js_name = globToRegex)]
            fn zenfs_glob_to_regex(pattern: &str) -> Result<JsValue, JsValue>;
            #[wasm_bindgen(catch, js_name = normalizePath)]
            fn zenfs_normalize_path(path: &str) -> Result<String, JsValue>;

            #[wasm_bindgen(thread_local_v2, js_name = mounts)]
            static ZEN_MOUNTS: JsValue;
            #[wasm_bindgen(thread_local_v2, js_name = promises)]
            static ZEN_PROMISES: JsValue;
            #[wasm_bindgen(thread_local_v2, js_name = default)]
            static ZEN_DEFAULT: JsValue;
            #[wasm_bindgen(thread_local_v2, js_name = vfs)]
            static ZEN_VFS: JsValue;
            #[wasm_bindgen(thread_local_v2, js_name = version)]
            static ZEN_VERSION: JsValue;
            #[wasm_bindgen(thread_local_v2, js_name = constants)]
            static ZEN_CONSTANTS: JsValue;
        }
    };
}

#[cfg(not(test))]
#[wasm_bindgen(inline_js = r#"
function canResolveZenFs() {
    try {
        if (typeof import.meta.resolve === "function") {
            import.meta.resolve("@zenfs/core");
            return true;
        }
    } catch (_) {
        return false;
    }

    try {
        return [...document.querySelectorAll('script[type="importmap"]')]
            .some((script) => Object.hasOwn(JSON.parse(script.textContent || "{}").imports || {}, "@zenfs/core"));
    } catch (_) {
        return false;
    }
}

let zenfsModule = null;
const zenfsModulePromise = canResolveZenFs()
    ? import("@zenfs/core").then((module) => (zenfsModule = module, module)).catch(() => null)
    : Promise.resolve(null);

function requireZenFs() {
    if (!zenfsModule) {
        throw new Error("ZenFS is not available or has not finished loading");
    }
    return zenfsModule;
}

export function zenfs_is_configured() {
    if (!zenfsModule) return false;
    const mounts = zenfsModule.mounts;
    return mounts instanceof Map ? mounts.size > 0 : Object.keys(mounts || {}).length > 0;
}

export function zenfs_get_export(name) {
    return zenfsModule ? zenfsModule[name] : undefined;
}

export function zenfs_call_sync(name, args) {
    const fn = requireZenFs()[name];
    if (typeof fn !== "function") throw new TypeError(`ZenFS export ${name} is not a function`);
    return fn(...args);
}

export async function zenfs_call_async(name, args) {
    let module = zenfsModule || await zenfsModulePromise;
    if (!module && canResolveZenFs()) {
        module = await import("@zenfs/core").then((loaded) => (zenfsModule = loaded, loaded)).catch(() => null);
    }
    if (!module) throw new Error("ZenFS is not available; enable the webfs feature to use its fallback");
    const fn = module[name];
    if (typeof fn !== "function") throw new TypeError(`ZenFS export ${name} is not a function`);
    return fn(...args);
}
"#)]
extern "C" {
    fn zenfs_is_configured() -> bool;
    fn zenfs_get_export(name: &str) -> JsValue;
    #[wasm_bindgen(catch)]
    fn zenfs_call_sync(name: &str, args: &Array) -> Result<JsValue, JsValue>;
    #[wasm_bindgen(catch)]
    fn zenfs_call_async(name: &str, args: &Array) -> Result<js_sys::Promise, JsValue>;
}

#[cfg(not(test))]
struct ZenFsExport(&'static str);

#[cfg(not(test))]
impl ZenFsExport {
    fn with<R>(&self, f: impl FnOnce(&JsValue) -> R) -> R {
        let value = zenfs_get_export(self.0);
        f(&value)
    }
}

#[cfg(not(test))]
const ZEN_FS: ZenFsExport = ZenFsExport("fs");
#[cfg(not(test))]
const ZEN_MOUNTS: ZenFsExport = ZenFsExport("mounts");
#[cfg(not(test))]
const ZEN_PROMISES: ZenFsExport = ZenFsExport("promises");
#[cfg(not(test))]
const ZEN_DEFAULT: ZenFsExport = ZenFsExport("default");
#[cfg(not(test))]
const ZEN_VFS: ZenFsExport = ZenFsExport("vfs");
#[cfg(not(test))]
const ZEN_VERSION: ZenFsExport = ZenFsExport("version");
#[cfg(not(test))]
const ZEN_CONSTANTS: ZenFsExport = ZenFsExport("constants");

#[cfg(not(test))]
fn call_zenfs_sync(name: &str, args: &[JsValue]) -> Result<JsValue, JsValue> {
    zenfs_call_sync(name, &Array::from_iter(args.iter().cloned()))
}

#[cfg(not(test))]
fn call_zenfs_async(name: &str, args: &[JsValue]) -> Result<js_sys::Promise, JsValue> {
    zenfs_call_async(name, &Array::from_iter(args.iter().cloned()))
}

#[cfg(all(not(test), feature = "webfs", feature = "zenfs"))]
pub fn is_configured() -> bool {
    zenfs_is_configured()
}

#[cfg(all(test, feature = "webfs", feature = "zenfs"))]
pub fn is_configured() -> bool {
    true
}

#[cfg(not(test))]
fn zenfs_configure(configuration: &JsValue) -> Result<js_sys::Promise, JsValue> {
    call_zenfs_async("configure", &[configuration.clone()])
}

#[cfg(not(test))]
fn zenfs_configure_sync(configuration: &JsValue) -> Result<(), JsValue> {
    call_zenfs_sync("configureSync", &[configuration.clone()]).map(|_| ())
}

#[cfg(not(test))]
fn zenfs_configure_single(configuration: &JsValue) -> Result<js_sys::Promise, JsValue> {
    call_zenfs_async("configureSingle", &[configuration.clone()])
}

#[cfg(not(test))]
fn zenfs_configure_single_sync(configuration: &JsValue) -> Result<(), JsValue> {
    call_zenfs_sync("configureSingleSync", &[configuration.clone()]).map(|_| ())
}

#[cfg(not(test))]
fn zenfs_configure_file_system(
    filesystem: &JsValue,
    configuration: &JsValue,
) -> Result<(), JsValue> {
    call_zenfs_sync(
        "configureFileSystem",
        &[filesystem.clone(), configuration.clone()],
    )
    .map(|_| ())
}

#[cfg(not(test))]
fn zenfs_resolve_mount_config(configuration: &JsValue) -> Result<js_sys::Promise, JsValue> {
    call_zenfs_async("resolveMountConfig", &[configuration.clone()])
}

#[cfg(not(test))]
fn zenfs_resolve_mount_config_sync(configuration: &JsValue) -> Result<JsValue, JsValue> {
    call_zenfs_sync("resolveMountConfigSync", &[configuration.clone()])
}

#[cfg(not(test))]
fn zenfs_resolve_remote_mount(
    channel: &JsValue,
    configuration: &JsValue,
) -> Result<js_sys::Promise, JsValue> {
    call_zenfs_async(
        "resolveRemoteMount",
        &[channel.clone(), configuration.clone()],
    )
}

#[cfg(not(test))]
fn zenfs_mount(mount_point: &str, filesystem: &JsValue) -> Result<(), JsValue> {
    call_zenfs_sync(
        "mount",
        &[JsValue::from_str(mount_point), filesystem.clone()],
    )
    .map(|_| ())
}

#[cfg(not(test))]
fn zenfs_umount(mount_point: &str) -> Result<(), JsValue> {
    call_zenfs_sync("umount", &[JsValue::from_str(mount_point)]).map(|_| ())
}

#[cfg(not(test))]
fn zenfs_sync() -> Result<js_sys::Promise, JsValue> {
    call_zenfs_async("sync", &[])
}

#[cfg(not(test))]
fn zenfs_wait_online(worker: &JsValue) -> Result<js_sys::Promise, JsValue> {
    call_zenfs_async("waitOnline", &[worker.clone()])
}

#[cfg(not(test))]
fn zenfs_attach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
    call_zenfs_sync("attachFS", &[channel.clone(), filesystem.clone()]).map(|_| ())
}

#[cfg(not(test))]
fn zenfs_detach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
    call_zenfs_sync("detachFS", &[channel.clone(), filesystem.clone()]).map(|_| ())
}

#[cfg(not(test))]
fn zenfs_glob_to_regex(pattern: &str) -> Result<JsValue, JsValue> {
    call_zenfs_sync("globToRegex", &[JsValue::from_str(pattern)])
}

#[cfg(not(test))]
fn zenfs_normalize_path(path: &str) -> Result<String, JsValue> {
    call_zenfs_sync("normalizePath", &[JsValue::from_str(path)])?
        .as_string()
        .ok_or_else(|| JsValue::from_str("ZenFS normalizePath did not return a string"))
}

#[cfg(test)]
zenfs_setup_imports!("https://esm.sh/@zenfs/core@2.7.6?bundle&target=es2022");

async fn await_zenfs_promise(promise: js_sys::Promise) -> Result<JsValue, JsValue> {
    JsFuture::from(promise).await
}

#[wasm_bindgen]
pub async fn configure(configuration: &JsValue) -> Result<(), JsValue> {
    await_zenfs_promise(zenfs_configure(configuration)?).await?;
    Ok(())
}

#[wasm_bindgen(js_name = configureSync)]
pub fn configure_sync(configuration: &JsValue) -> Result<(), JsValue> {
    zenfs_configure_sync(configuration)
}

#[wasm_bindgen(js_name = configureSingle)]
pub async fn configure_single(configuration: &JsValue) -> Result<(), JsValue> {
    await_zenfs_promise(zenfs_configure_single(configuration)?).await?;
    Ok(())
}

#[wasm_bindgen(js_name = configureSingleSync)]
pub fn configure_single_sync(configuration: &JsValue) -> Result<(), JsValue> {
    zenfs_configure_single_sync(configuration)
}

#[wasm_bindgen(js_name = configureFileSystem)]
pub fn configure_file_system(filesystem: &JsValue, configuration: &JsValue) -> Result<(), JsValue> {
    zenfs_configure_file_system(filesystem, configuration)
}

#[wasm_bindgen(js_name = resolveMountConfig)]
pub async fn resolve_mount_config(configuration: &JsValue) -> Result<JsValue, JsValue> {
    await_zenfs_promise(zenfs_resolve_mount_config(configuration)?).await
}

#[wasm_bindgen(js_name = resolveMountConfigSync)]
pub fn resolve_mount_config_sync(configuration: &JsValue) -> Result<JsValue, JsValue> {
    zenfs_resolve_mount_config_sync(configuration)
}

#[wasm_bindgen(js_name = resolveRemoteMount)]
pub async fn resolve_remote_mount(
    channel: &JsValue,
    configuration: &JsValue,
) -> Result<JsValue, JsValue> {
    await_zenfs_promise(zenfs_resolve_remote_mount(channel, configuration)?).await
}

#[wasm_bindgen]
pub fn mount(mount_point: &str, filesystem: &JsValue) -> Result<(), JsValue> {
    zenfs_mount(mount_point, filesystem)
}

#[wasm_bindgen]
pub fn umount(mount_point: &str) -> Result<(), JsValue> {
    zenfs_umount(mount_point)
}

#[wasm_bindgen]
pub fn mounts() -> JsValue {
    ZEN_MOUNTS.with(JsValue::clone)
}

#[wasm_bindgen]
pub async fn sync() -> Result<(), JsValue> {
    await_zenfs_promise(zenfs_sync()?).await?;
    Ok(())
}

#[wasm_bindgen(js_name = waitOnline)]
pub async fn wait_online(worker: &JsValue) -> Result<(), JsValue> {
    await_zenfs_promise(zenfs_wait_online(worker)?).await?;
    Ok(())
}

#[wasm_bindgen(js_name = attachFS)]
pub fn attach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
    zenfs_attach_fs(channel, filesystem)
}

#[wasm_bindgen(js_name = detachFS)]
pub fn detach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
    zenfs_detach_fs(channel, filesystem)
}

#[wasm_bindgen(js_name = fs)]
pub fn zenfs_fs() -> JsValue {
    ZEN_FS.with(JsValue::clone)
}

#[wasm_bindgen]
pub fn promises() -> JsValue {
    ZEN_PROMISES.with(JsValue::clone)
}

// wasm-bindgen reserves the module's default export for its initializer.
#[wasm_bindgen(js_name = defaultFs)]
pub fn default_fs() -> JsValue {
    ZEN_DEFAULT.with(JsValue::clone)
}

#[wasm_bindgen]
pub fn vfs() -> JsValue {
    ZEN_VFS.with(JsValue::clone)
}

#[wasm_bindgen]
pub fn version() -> JsValue {
    ZEN_VERSION.with(JsValue::clone)
}

#[wasm_bindgen]
pub fn constants() -> JsValue {
    ZEN_CONSTANTS.with(JsValue::clone)
}

fn call_fs(method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
    let fs = ZEN_FS.with(JsValue::clone);
    let method = Reflect::get(&fs, &JsValue::from_str(method))?;
    let method = method
        .dyn_into::<Function>()
        .map_err(|_| JsValue::from_str("ZenFS method is not a function"))?;
    let arguments = Array::from_iter(arguments.iter().cloned());

    // `Function::apply` captures exceptions thrown by ZenFS and returns them as
    // `Err`, which wasm-bindgen exposes as a normal JavaScript exception.
    method.apply(&fs, &arguments)
}

async fn call_fs_promise(method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
    let fs = ZEN_FS.with(JsValue::clone);
    let promises = Reflect::get(&fs, &JsValue::from_str("promises"))?;
    let method = Reflect::get(&promises, &JsValue::from_str(method))?
        .dyn_into::<Function>()
        .map_err(|_| JsValue::from_str("ZenFS promise method is not a function"))?;
    let arguments = Array::from_iter(arguments.iter().cloned());
    let promise = method
        .apply(&promises, &arguments)?
        .dyn_into::<js_sys::Promise>()?;
    JsFuture::from(promise).await
}

async fn call_fs_callback(method_name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
    let fs = ZEN_FS.with(JsValue::clone);
    let method = Reflect::get(&fs, &JsValue::from_str(method_name))?
        .dyn_into::<Function>()
        .map_err(|_| JsValue::from_str("ZenFS callback method is not a function"))?;
    let arguments = Array::from_iter(arguments.iter().cloned());
    let promise = js_sys::Promise::new(&mut |resolve, reject| {
        let callback_resolve = resolve.clone();
        let callback_reject = reject.clone();
        let callback = Closure::once_into_js(move |error: JsValue, value: JsValue| {
            if error.is_null() || error.is_undefined() {
                let _ = callback_resolve.call1(&JsValue::UNDEFINED, &value);
            } else {
                let _ = callback_reject.call1(&JsValue::UNDEFINED, &error);
            }
        });
        arguments.push(&callback);
        if let Err(error) = method.apply(&fs, &arguments) {
            let _ = reject.call1(&JsValue::UNDEFINED, &error);
        }
    });
    JsFuture::from(promise).await
}

fn mkdir_options(recursive: bool) -> Result<JsValue, JsValue> {
    let options = Object::new();
    Reflect::set(
        &options,
        &JsValue::from_str("recursive"),
        &JsValue::from_bool(recursive),
    )?;
    Ok(options.into())
}

fn removal_options(recursive: bool, force: bool) -> Result<JsValue, JsValue> {
    let options = Object::new();
    Reflect::set(
        &options,
        &JsValue::from_str("recursive"),
        &JsValue::from_bool(recursive),
    )?;
    Reflect::set(
        &options,
        &JsValue::from_str("force"),
        &JsValue::from_bool(force),
    )?;
    Ok(options.into())
}

fn returned_string(value: JsValue, method: &str) -> Result<String, JsValue> {
    value
        .as_string()
        .ok_or_else(|| JsValue::from_str(&format!("ZenFS {method} did not return a string")))
}

fn returned_names(value: JsValue) -> Result<Vec<String>, JsValue> {
    Array::from(&value)
        .iter()
        .map(|value| returned_string(value, "directory listing"))
        .collect()
}

fn descriptor_value(fd: &File) -> JsValue {
    JsValue::from_f64(f64::from(*fd))
}

fn returned_usize(value: JsValue, operation: &str) -> Result<usize, JsValue> {
    value
        .as_f64()
        .filter(|value| value.is_finite() && *value >= 0.0)
        .map(|value| value as usize)
        .ok_or_else(|| JsValue::from_str(&format!("ZenFS {operation} did not return a byte count")))
}

fn returned_descriptor(value: JsValue) -> Result<File, JsValue> {
    value
        .as_f64()
        .filter(|fd| fd.is_finite() && *fd >= 0.0 && *fd <= f64::from(u32::MAX))
        .map(|fd| fd as u32)
        .ok_or_else(|| JsValue::from_str("ZenFS open did not return a file descriptor"))
}

fn open_flags(options: &OpenOptions) -> Result<&'static str, JsValue> {
    if !options.read && !options.write && !options.append {
        return Err(JsValue::from_str(
            "at least one file access mode is required",
        ));
    }
    if options.truncate && !options.write && !options.append && !options.create_new {
        return Err(JsValue::from_str("truncate requires write access"));
    }
    if options.create && !options.write && !options.append {
        return Err(JsValue::from_str("create requires write or append access"));
    }
    if options.create_new && !options.write && !options.append {
        return Err(JsValue::from_str(
            "create_new requires write or append access",
        ));
    }

    Ok(if options.append {
        match (options.read, options.create_new) {
            (true, true) => "ax+",
            (false, true) => "ax",
            (true, false) => "a+",
            (false, false) => "a",
        }
    } else if options.create_new {
        if options.read { "wx+" } else { "wx" }
    } else if options.truncate || options.create {
        if options.read { "w+" } else { "w" }
    } else if options.write {
        "r+"
    } else {
        "r"
    })
}

#[wasm_bindgen(js_name = appDir)]
pub fn app_dir(name: &str) -> Result<String, JsValue> {
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\\') {
        return Err(JsValue::from_str(
            "application name must be a single path component",
        ));
    }

    let path = format!("/app/{name}");
    let options = mkdir_options(true)?;
    call_fs("mkdirSync", &[JsValue::from_str(&path), options])?;
    Ok(path)
}

#[wasm_bindgen(js_name = exists)]
pub async fn exists(path: &str) -> Result<bool, JsValue> {
    call_fs_promise("exists", &[JsValue::from_str(path)])
        .await?
        .as_bool()
        .ok_or_else(|| JsValue::from_str("ZenFS exists did not return a boolean"))
}

pub fn exists_sync(path: &str) -> Result<bool, JsValue> {
    call_fs("existsSync", &[JsValue::from_str(path)])?
        .as_bool()
        .ok_or_else(|| JsValue::from_str("ZenFS existsSync did not return a boolean"))
}

pub async fn access(path: &str, mode: u32) -> Result<(), JsValue> {
    call_fs_promise(
        "access",
        &[JsValue::from_str(path), JsValue::from_f64(f64::from(mode))],
    )
    .await?;
    Ok(())
}

pub fn access_sync(path: &str, mode: u32) -> Result<(), JsValue> {
    call_fs(
        "accessSync",
        &[JsValue::from_str(path), JsValue::from_f64(f64::from(mode))],
    )?;
    Ok(())
}

#[wasm_bindgen(js_name = readText)]
pub fn read_text(path: &str) -> Result<String, JsValue> {
    call_fs(
        "readFileSync",
        &[JsValue::from_str(path), JsValue::from_str("utf8")],
    )?
    .as_string()
    .ok_or_else(|| JsValue::from_str("ZenFS did not return a UTF-8 string"))
}

#[wasm_bindgen(js_name = writeText)]
pub fn write_text(path: &str, contents: &str) -> Result<(), JsValue> {
    call_fs(
        "writeFileSync",
        &[JsValue::from_str(path), JsValue::from_str(contents)],
    )?;
    Ok(())
}

#[wasm_bindgen(js_name = appendText)]
pub fn append_text(path: &str, contents: &str) -> Result<(), JsValue> {
    call_fs(
        "appendFileSync",
        &[JsValue::from_str(path), JsValue::from_str(contents)],
    )?;
    Ok(())
}

pub async fn append_file(path: &str, contents: &[u8]) -> Result<(), JsValue> {
    let contents = Uint8Array::from(contents);
    call_fs_promise("appendFile", &[JsValue::from_str(path), contents.into()]).await?;
    Ok(())
}

pub fn append_file_sync(path: &str, contents: &[u8]) -> Result<(), JsValue> {
    let contents = Uint8Array::from(contents);
    call_fs(
        "appendFileSync",
        &[JsValue::from_str(path), contents.into()],
    )?;
    Ok(())
}

#[wasm_bindgen(js_name = readFile)]
pub async fn read_file(path: &str) -> Result<Vec<u8>, JsValue> {
    let contents = call_fs_promise("readFile", &[JsValue::from_str(path)]).await?;
    Ok(Uint8Array::new(&contents).to_vec())
}

pub fn read_file_sync(path: &str) -> Result<Vec<u8>, JsValue> {
    let contents = call_fs("readFileSync", &[JsValue::from_str(path)])?;
    Ok(Uint8Array::new(&contents).to_vec())
}

#[wasm_bindgen(js_name = writeFile)]
pub async fn write_file(path: &str, contents: &[u8]) -> Result<(), JsValue> {
    let contents = Uint8Array::from(contents);
    call_fs_promise("writeFile", &[JsValue::from_str(path), contents.into()]).await?;
    Ok(())
}

pub fn write_file_sync(path: &str, contents: &[u8]) -> Result<(), JsValue> {
    let contents = Uint8Array::from(contents);
    call_fs("writeFileSync", &[JsValue::from_str(path), contents.into()])?;
    Ok(())
}

#[wasm_bindgen(js_name = copyFile)]
pub async fn copy_file(from: &str, to: &str) -> Result<(), JsValue> {
    call_fs_promise(
        "copyFile",
        &[JsValue::from_str(from), JsValue::from_str(to)],
    )
    .await?;
    Ok(())
}

pub fn copy_file_sync(from: &str, to: &str) -> Result<(), JsValue> {
    call_fs(
        "copyFileSync",
        &[JsValue::from_str(from), JsValue::from_str(to)],
    )?;
    Ok(())
}

pub async fn cp(from: &str, to: &str) -> Result<(), JsValue> {
    let options = Object::new();
    Reflect::set(&options, &JsValue::from_str("recursive"), &JsValue::TRUE)?;
    call_fs_promise(
        "cp",
        &[
            JsValue::from_str(from),
            JsValue::from_str(to),
            options.into(),
        ],
    )
    .await?;
    Ok(())
}

pub fn cp_sync(from: &str, to: &str) -> Result<(), JsValue> {
    let options = Object::new();
    Reflect::set(&options, &JsValue::from_str("recursive"), &JsValue::TRUE)?;
    call_fs(
        "cpSync",
        &[
            JsValue::from_str(from),
            JsValue::from_str(to),
            options.into(),
        ],
    )?;
    Ok(())
}

pub fn open_sync(path: &str, options: &OpenOptions) -> Result<File, JsValue> {
    let flags = open_flags(options)?;
    if options.append && !options.create && !options.create_new {
        let exists = call_fs("existsSync", &[JsValue::from_str(path)])?
            .as_bool()
            .ok_or_else(|| JsValue::from_str("ZenFS existsSync did not return a boolean"))?;
        if !exists {
            let descriptor = call_fs(
                "openSync",
                &[JsValue::from_str(path), JsValue::from_str("r")],
            )?;
            call_fs("closeSync", &[descriptor])?;
        }
    }
    let descriptor =
        if options.create && !options.create_new && !options.truncate && !options.append {
            match call_fs(
                "openSync",
                &[JsValue::from_str(path), JsValue::from_str("r+")],
            ) {
                Ok(descriptor) => descriptor,
                Err(error) if is_no_entry(&error) => call_fs(
                    "openSync",
                    &[JsValue::from_str(path), JsValue::from_str("w+")],
                )?,
                Err(error) => return Err(error),
            }
        } else if options.truncate && !options.create && !options.create_new && !options.append {
            let descriptor = call_fs(
                "openSync",
                &[JsValue::from_str(path), JsValue::from_str("r+")],
            )?;
            let descriptor = descriptor
                .as_f64()
                .filter(|fd| fd.is_finite() && *fd >= 0.0 && *fd <= f64::from(u32::MAX))
                .ok_or_else(|| {
                    JsValue::from_str("ZenFS openSync did not return a file descriptor")
                })? as u32;
            if let Err(error) = call_fs(
                "ftruncateSync",
                &[
                    JsValue::from_f64(f64::from(descriptor)),
                    JsValue::from_f64(0.0),
                ],
            ) {
                let _ = call_fs("closeSync", &[JsValue::from_f64(f64::from(descriptor))]);
                return Err(error);
            }
            return Ok(descriptor);
        } else {
            call_fs(
                "openSync",
                &[JsValue::from_str(path), JsValue::from_str(flags)],
            )?
        };
    let descriptor = descriptor
        .as_f64()
        .filter(|fd| fd.is_finite() && *fd >= 0.0 && *fd <= f64::from(u32::MAX))
        .ok_or_else(|| JsValue::from_str("ZenFS openSync did not return a file descriptor"))?;
    let descriptor = descriptor as u32;
    if options.truncate
        && options.append
        && let Err(error) = call_fs(
            "ftruncateSync",
            &[
                JsValue::from_f64(f64::from(descriptor)),
                JsValue::from_f64(0.0),
            ],
        )
    {
        let _ = call_fs("closeSync", &[JsValue::from_f64(f64::from(descriptor))]);
        return Err(error);
    }
    Ok(descriptor)
}

pub async fn open(path: &str, options: &OpenOptions) -> Result<File, JsValue> {
    let flags = open_flags(options)?;
    if options.append && !options.create && !options.create_new {
        let exists = call_fs_promise("exists", &[JsValue::from_str(path)])
            .await?
            .as_bool()
            .ok_or_else(|| JsValue::from_str("ZenFS exists did not return a boolean"))?;
        if !exists {
            let descriptor =
                call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("r")])
                    .await?;
            call_fs_callback("close", &[descriptor]).await?;
        }
    }

    let descriptor = if options.create
        && !options.create_new
        && !options.truncate
        && !options.append
    {
        match call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("r+")]).await {
            Ok(descriptor) => descriptor,
            Err(error) if is_no_entry(&error) => {
                call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("w+")])
                    .await?
            }
            Err(error) => return Err(error),
        }
    } else if options.truncate && !options.create && !options.create_new && !options.append {
        let descriptor =
            call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("r+")]).await?;
        if let Err(error) =
            call_fs_callback("ftruncate", &[descriptor.clone(), JsValue::from_f64(0.0)]).await
        {
            let _ = call_fs_callback("close", &[descriptor]).await;
            return Err(error);
        }
        descriptor
    } else {
        call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str(flags)]).await?
    };

    let descriptor = returned_descriptor(descriptor)?;
    if options.truncate
        && options.append
        && let Err(error) = call_fs_callback(
            "ftruncate",
            &[
                JsValue::from_f64(f64::from(descriptor)),
                JsValue::from_f64(0.0),
            ],
        )
        .await
    {
        let _ = call_fs_callback("close", &[JsValue::from_f64(f64::from(descriptor))]).await;
        return Err(error);
    }
    Ok(descriptor)
}

fn is_no_entry(error: &JsValue) -> bool {
    Reflect::get(error, &JsValue::from_str("code"))
        .ok()
        .and_then(|code| code.as_string())
        .as_deref()
        == Some("ENOENT")
}

pub async fn open_as_blob(path: &str) -> Result<Vec<u8>, JsValue> {
    let result = call_fs("openAsBlob", &[JsValue::from_str(path)])?;
    let promise = result
        .dyn_into::<js_sys::Promise>()
        .map_err(|_| JsValue::from_str("ZenFS openAsBlob did not return a promise"))?;
    let blob = JsFuture::from(promise).await?;
    let array_buffer = Reflect::get(&blob, &JsValue::from_str("arrayBuffer"))?
        .dyn_into::<Function>()
        .map_err(|_| JsValue::from_str("ZenFS openAsBlob did not return a Blob"))?;
    let array_buffer = array_buffer.call0(&blob)?.dyn_into::<js_sys::Promise>()?;
    let buffer = JsFuture::from(array_buffer).await?;
    Ok(Uint8Array::new(&buffer).to_vec())
}

pub fn close_sync(file: File) -> Result<(), JsValue> {
    call_fs("closeSync", &[descriptor_value(&file)])?;
    Ok(())
}

pub async fn close(file: &File) -> Result<(), JsValue> {
    call_fs_callback("close", &[descriptor_value(file)]).await?;
    Ok(())
}

pub fn read_sync(file: &mut File, buffer: &mut [u8]) -> Result<usize, JsValue> {
    let target = Uint8Array::new_with_length(buffer.len() as u32);
    let count = call_fs(
        "readSync",
        &[
            descriptor_value(file),
            target.clone().into(),
            JsValue::from_f64(0.0),
            JsValue::from_f64(buffer.len() as f64),
            JsValue::NULL,
        ],
    )?;
    let count = returned_usize(count, "readSync")?;
    let count = count.min(buffer.len());
    target
        .subarray(0, count as u32)
        .copy_to(&mut buffer[..count]);
    Ok(count)
}

pub async fn read(file: &mut File, buffer: &mut [u8]) -> Result<usize, JsValue> {
    let target = Uint8Array::new_with_length(buffer.len() as u32);
    let count = call_fs_callback(
        "read",
        &[
            descriptor_value(file),
            target.clone().into(),
            JsValue::from_f64(0.0),
            JsValue::from_f64(buffer.len() as f64),
            JsValue::NULL,
        ],
    )
    .await?;
    let count = returned_usize(count, "read")?.min(buffer.len());
    target
        .subarray(0, count as u32)
        .copy_to(&mut buffer[..count]);
    Ok(count)
}

pub fn write_sync(file: &mut File, buffer: &[u8]) -> Result<usize, JsValue> {
    let contents = Uint8Array::from(buffer);
    let count = call_fs(
        "writeSync",
        &[
            descriptor_value(file),
            contents.into(),
            JsValue::from_f64(0.0),
            JsValue::from_f64(buffer.len() as f64),
            JsValue::NULL,
        ],
    )?;
    returned_usize(count, "writeSync")
}

pub async fn write(file: &mut File, buffer: &[u8]) -> Result<usize, JsValue> {
    let contents = Uint8Array::from(buffer);
    let count = call_fs_callback(
        "write",
        &[
            descriptor_value(file),
            contents.into(),
            JsValue::from_f64(0.0),
            JsValue::from_f64(buffer.len() as f64),
            JsValue::NULL,
        ],
    )
    .await?;
    returned_usize(count, "write")
}

pub fn readv_sync(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> Result<usize, JsValue> {
    let arrays = buffers
        .iter()
        .map(|buffer| Uint8Array::from(&buffer[..]))
        .collect::<Vec<_>>();
    let js_buffers = Array::new();
    for buffer in &arrays {
        js_buffers.push(buffer);
    }
    let count = call_fs(
        "readvSync",
        &[descriptor_value(file), js_buffers.into(), JsValue::NULL],
    )?;
    let count = returned_usize(count, "readvSync")?;
    let mut remaining = count;
    for (target, source) in buffers.iter_mut().zip(arrays.iter()) {
        let copied = remaining.min(target.len());
        source
            .subarray(0, copied as u32)
            .copy_to(&mut target[..copied]);
        remaining -= copied;
        if remaining == 0 {
            break;
        }
    }
    Ok(count)
}

pub async fn readv(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> Result<usize, JsValue> {
    let arrays = buffers
        .iter()
        .map(|buffer| Uint8Array::from(&buffer[..]))
        .collect::<Vec<_>>();
    let js_buffers = Array::new();
    for buffer in &arrays {
        js_buffers.push(buffer);
    }
    let count = call_fs_callback(
        "readv",
        &[descriptor_value(file), js_buffers.into(), JsValue::NULL],
    )
    .await?;
    let count = returned_usize(count, "readv")?;
    let mut remaining = count;
    for (target, source) in buffers.iter_mut().zip(arrays.iter()) {
        let copied = remaining.min(target.len());
        source
            .subarray(0, copied as u32)
            .copy_to(&mut target[..copied]);
        remaining -= copied;
        if remaining == 0 {
            break;
        }
    }
    Ok(count)
}

pub fn writev_sync(file: &mut File, buffers: &[IoSlice<'_>]) -> Result<usize, JsValue> {
    let js_buffers = Array::new();
    for buffer in buffers {
        js_buffers.push(&Uint8Array::from(&buffer[..]));
    }
    let count = call_fs(
        "writevSync",
        &[descriptor_value(file), js_buffers.into(), JsValue::NULL],
    )?;
    returned_usize(count, "writevSync")
}

pub async fn writev(file: &mut File, buffers: &[IoSlice<'_>]) -> Result<usize, JsValue> {
    let js_buffers = Array::new();
    for buffer in buffers {
        js_buffers.push(&Uint8Array::from(&buffer[..]));
    }
    let count = call_fs_callback(
        "writev",
        &[descriptor_value(file), js_buffers.into(), JsValue::NULL],
    )
    .await?;
    returned_usize(count, "writev")
}

fn stats_bool(stats: &JsValue, name: &str) -> Result<bool, JsValue> {
    let member = Reflect::get(stats, &JsValue::from_str(name))?;
    if let Ok(method) = member.clone().dyn_into::<Function>() {
        method
            .call0(stats)?
            .as_bool()
            .ok_or_else(|| JsValue::from_str("ZenFS stat method did not return a boolean"))
    } else {
        member
            .as_bool()
            .ok_or_else(|| JsValue::from_str("ZenFS stat property was not a boolean"))
    }
}

fn metadata_from_stats(stats: &JsValue) -> Result<Metadata, JsValue> {
    let len = Reflect::get(stats, &JsValue::from_str("size"))?
        .as_f64()
        .filter(|size| size.is_finite() && *size >= 0.0)
        .map(|size| size as u64)
        .ok_or_else(|| JsValue::from_str("ZenFS stat size was not a non-negative number"))?;
    Ok(Metadata::from_parts(
        len,
        stats_bool(stats, "isFile")?,
        stats_bool(stats, "isDirectory")?,
        stats_bool(stats, "isSymbolicLink")?,
    ))
}

fn statfs_field(stats: &JsValue, field: &str) -> Result<f64, JsValue> {
    let value = Reflect::get(stats, &JsValue::from_str(field))?;
    value
        .as_f64()
        .filter(|value| value.is_finite() && *value >= 0.0)
        .ok_or_else(|| {
            JsValue::from_str(&format!(
                "ZenFS statfs field {field} was not a non-negative number: {value:?}"
            ))
        })
}

fn statfs_from_stats(stats: &JsValue) -> Result<StatFs, JsValue> {
    Ok(StatFs {
        block_size: statfs_field(stats, "bsize")? as u64,
        blocks: statfs_field(stats, "blocks")?,
        blocks_free: statfs_field(stats, "bfree")?,
        blocks_available: statfs_field(stats, "bavail")?,
        files: statfs_field(stats, "files")?,
        files_free: statfs_field(stats, "ffree")?,
    })
}

fn js_time(time: SystemTime) -> JsValue {
    let seconds = match time.duration_since(UNIX_EPOCH) {
        Ok(duration) => duration.as_secs_f64(),
        Err(error) => -error.duration().as_secs_f64(),
    };
    JsValue::from_f64(seconds)
}

fn number(value: u32) -> JsValue {
    JsValue::from_f64(f64::from(value))
}

macro_rules! path_metadata {
    ($async_name:ident, $sync_name:ident, $js_name:literal, $js_sync:literal, $output:ty, $convert:ident) => {
        pub fn $sync_name(path: &str) -> Result<$output, JsValue> {
            $convert(&call_fs($js_sync, &[JsValue::from_str(path)])?)
        }
        pub async fn $async_name(path: &str) -> Result<$output, JsValue> {
            $convert(&call_fs_promise($js_name, &[JsValue::from_str(path)]).await?)
        }
    };
}

path_metadata!(
    stat,
    stat_sync,
    "stat",
    "statSync",
    Metadata,
    metadata_from_stats
);
path_metadata!(
    lstat,
    lstat_sync,
    "lstat",
    "lstatSync",
    Metadata,
    metadata_from_stats
);
path_metadata!(
    statfs,
    statfs_sync,
    "statfs",
    "statfsSync",
    StatFs,
    statfs_from_stats
);

macro_rules! metadata_change {
    ($async_name:ident, $sync_name:ident, $js_name:literal, $js_sync:literal, ($($arg:ident: $type:ty => $value:expr),*)) => {
        pub fn $sync_name(path: &str, $($arg: $type),*) -> Result<(), JsValue> {
            call_fs($js_sync, &[JsValue::from_str(path), $($value),*])?;
            Ok(())
        }
        pub async fn $async_name(path: &str, $($arg: $type),*) -> Result<(), JsValue> {
            call_fs_promise($js_name, &[JsValue::from_str(path), $($value),*]).await?;
            Ok(())
        }
    };
}

metadata_change!(chmod, chmod_sync, "chmod", "chmodSync", (mode: u32 => number(mode)));
metadata_change!(lchmod, lchmod_sync, "lchmod", "lchmodSync", (mode: u32 => number(mode)));
metadata_change!(chown, chown_sync, "chown", "chownSync", (uid: u32 => number(uid), gid: u32 => number(gid)));
metadata_change!(lchown, lchown_sync, "lchown", "lchownSync", (uid: u32 => number(uid), gid: u32 => number(gid)));
metadata_change!(utimes, utimes_sync, "utimes", "utimesSync", (atime: SystemTime => js_time(atime), mtime: SystemTime => js_time(mtime)));
metadata_change!(lutimes, lutimes_sync, "lutimes", "lutimesSync", (atime: SystemTime => js_time(atime), mtime: SystemTime => js_time(mtime)));

macro_rules! descriptor_metadata_change {
    ($async_name:ident, $sync_name:ident, $js_name:literal, $js_sync:literal, ($($arg:ident: $type:ty => $value:expr),*)) => {
        pub fn $sync_name(file: &File, $($arg: $type),*) -> Result<(), JsValue> {
            call_fs($js_sync, &[descriptor_value(file), $($value),*])?;
            Ok(())
        }
        pub async fn $async_name(file: &File, $($arg: $type),*) -> Result<(), JsValue> {
            call_fs_callback($js_name, &[descriptor_value(file), $($value),*]).await?;
            Ok(())
        }
    };
}
descriptor_metadata_change!(fchmod, fchmod_sync, "fchmod", "fchmodSync", (mode: u32 => number(mode)));
descriptor_metadata_change!(fchown, fchown_sync, "fchown", "fchownSync", (uid: u32 => number(uid), gid: u32 => number(gid)));
descriptor_metadata_change!(futimes, futimes_sync, "futimes", "futimesSync", (atime: SystemTime => js_time(atime), mtime: SystemTime => js_time(mtime)));

pub fn fstat_sync(file: &File) -> Result<Metadata, JsValue> {
    let stats = call_fs("fstatSync", &[descriptor_value(file)])?;
    metadata_from_stats(&stats)
}

pub async fn fstat(file: &File) -> Result<Metadata, JsValue> {
    let stats = call_fs_callback("fstat", &[descriptor_value(file)]).await?;
    metadata_from_stats(&stats)
}

pub fn fsync_sync(file: &File) -> Result<(), JsValue> {
    call_fs("fsyncSync", &[descriptor_value(file)])?;
    Ok(())
}

pub async fn fsync(file: &File) -> Result<(), JsValue> {
    call_fs_callback("fsync", &[descriptor_value(file)]).await?;
    Ok(())
}

pub fn fdatasync_sync(file: &File) -> Result<(), JsValue> {
    call_fs("fdatasyncSync", &[descriptor_value(file)])?;
    Ok(())
}

pub async fn fdatasync(file: &File) -> Result<(), JsValue> {
    call_fs_callback("fdatasync", &[descriptor_value(file)]).await?;
    Ok(())
}

pub fn ftruncate_sync(file: &File, size: u64) -> Result<(), JsValue> {
    call_fs(
        "ftruncateSync",
        &[descriptor_value(file), JsValue::from_f64(size as f64)],
    )?;
    Ok(())
}

pub async fn ftruncate(file: &File, size: u64) -> Result<(), JsValue> {
    call_fs_callback(
        "ftruncate",
        &[descriptor_value(file), JsValue::from_f64(size as f64)],
    )
    .await?;
    Ok(())
}

pub fn truncate_sync(path: &str, len: u64) -> Result<(), JsValue> {
    call_fs(
        "truncateSync",
        &[JsValue::from_str(path), JsValue::from_f64(len as f64)],
    )?;
    Ok(())
}

pub async fn truncate(path: &str, len: u64) -> Result<(), JsValue> {
    call_fs_promise(
        "truncate",
        &[JsValue::from_str(path), JsValue::from_f64(len as f64)],
    )
    .await?;
    Ok(())
}

#[wasm_bindgen(js_name = createDir)]
pub fn create_dir(path: &str) -> Result<(), JsValue> {
    let options = mkdir_options(false)?;
    call_fs("mkdirSync", &[JsValue::from_str(path), options])?;
    Ok(())
}

#[wasm_bindgen(js_name = createDirAll)]
pub fn create_dir_all(path: &str) -> Result<(), JsValue> {
    let options = mkdir_options(true)?;
    call_fs("mkdirSync", &[JsValue::from_str(path), options])?;
    Ok(())
}

#[wasm_bindgen(js_name = readDir)]
pub fn read_dir(path: &str) -> Result<Vec<String>, JsValue> {
    readdir_sync(path)
}

pub fn mkdir_sync(path: &str, recursive: bool) -> Result<(), JsValue> {
    call_fs(
        "mkdirSync",
        &[JsValue::from_str(path), mkdir_options(recursive)?],
    )?;
    Ok(())
}

pub async fn mkdir(path: &str, recursive: bool) -> Result<(), JsValue> {
    call_fs_promise(
        "mkdir",
        &[JsValue::from_str(path), mkdir_options(recursive)?],
    )
    .await?;
    Ok(())
}

pub fn mkdtemp_sync(prefix: &str) -> Result<String, JsValue> {
    returned_string(
        call_fs("mkdtempSync", &[JsValue::from_str(prefix)])?,
        "mkdtempSync",
    )
}

pub async fn mkdtemp(prefix: &str) -> Result<String, JsValue> {
    returned_string(
        call_fs_promise("mkdtemp", &[JsValue::from_str(prefix)]).await?,
        "mkdtemp",
    )
}

pub fn mkdtemp_disposable_sync(prefix: &str) -> Result<TempDir, JsValue> {
    let value = call_fs("mkdtempDisposableSync", &[JsValue::from_str(prefix)])?;
    let path = returned_string(
        Reflect::get(&value, &JsValue::from_str("path"))?,
        "mkdtempDisposableSync",
    )?;
    Ok(TempDir { path })
}

pub fn readdir_sync(path: &str) -> Result<Vec<String>, JsValue> {
    returned_names(call_fs("readdirSync", &[JsValue::from_str(path)])?)
}

pub async fn readdir(path: &str) -> Result<Vec<String>, JsValue> {
    returned_names(call_fs_promise("readdir", &[JsValue::from_str(path)]).await?)
}

fn dir_entry(entry: JsValue) -> Result<Option<Dirent>, JsValue> {
    if entry.is_null() || entry.is_undefined() {
        return Ok(None);
    }
    let name = returned_string(
        Reflect::get(&entry, &JsValue::from_str("name"))?,
        "Dirent.name",
    )?;
    Ok(Some(Dirent::from_parts(
        name,
        stats_bool(&entry, "isFile")?,
        stats_bool(&entry, "isDirectory")?,
        stats_bool(&entry, "isSymbolicLink")?,
    )))
}

pub fn dir_read_sync(dir: &mut Dir) -> Result<Option<Dirent>, JsValue> {
    let read = Reflect::get(dir, &JsValue::from_str("readSync"))?.dyn_into::<Function>()?;
    dir_entry(read.call0(dir)?)
}

pub async fn dir_read(dir: &mut Dir) -> Result<Option<Dirent>, JsValue> {
    let read = Reflect::get(dir, &JsValue::from_str("read"))?.dyn_into::<Function>()?;
    let promise = read.call0(dir)?.dyn_into::<js_sys::Promise>()?;
    dir_entry(JsFuture::from(promise).await?)
}

pub fn dir_close_sync(dir: &Dir) -> Result<(), JsValue> {
    let close = Reflect::get(dir, &JsValue::from_str("closeSync"))?.dyn_into::<Function>()?;
    close.call0(dir)?;
    Ok(())
}

pub async fn dir_close(dir: &Dir) -> Result<(), JsValue> {
    let close = Reflect::get(dir, &JsValue::from_str("close"))?.dyn_into::<Function>()?;
    let promise = close.call0(dir)?.dyn_into::<js_sys::Promise>()?;
    JsFuture::from(promise).await?;
    Ok(())
}

pub fn open_dir_sync(path: &str) -> Result<Dir, JsValue> {
    call_fs("opendirSync", &[JsValue::from_str(path)])
}

pub async fn open_dir(path: &str) -> Result<Dir, JsValue> {
    call_fs_promise("opendir", &[JsValue::from_str(path)]).await
}

#[cfg(not(feature = "webfs"))]
pub fn opendir_sync(path: &str) -> Result<super::api::Dir, JsValue> {
    open_dir_sync(path).map(super::api::Dir::from_inner)
}

#[cfg(not(feature = "webfs"))]
pub async fn opendir(path: &str) -> Result<super::api::Dir, JsValue> {
    open_dir(path).await.map(super::api::Dir::from_inner)
}

#[cfg(all(test, feature = "webfs", feature = "zenfs"))]
pub fn opendir_sync(path: &str) -> Result<super::api::Dir, JsValue> {
    let inner = crate::implementation::Dir::ZenFs(open_dir_sync(path)?);
    Ok(super::api::Dir::from_inner(inner))
}

#[cfg(all(test, feature = "webfs", feature = "zenfs"))]
pub async fn opendir(path: &str) -> Result<super::api::Dir, JsValue> {
    let inner = crate::implementation::Dir::ZenFs(open_dir(path).await?);
    Ok(super::api::Dir::from_inner(inner))
}

pub fn rmdir_sync(path: &str) -> Result<(), JsValue> {
    call_fs("rmdirSync", &[JsValue::from_str(path)])?;
    Ok(())
}

pub async fn rmdir(path: &str) -> Result<(), JsValue> {
    call_fs_promise("rmdir", &[JsValue::from_str(path)]).await?;
    Ok(())
}

pub fn rm_sync(path: &str, recursive: bool, force: bool) -> Result<(), JsValue> {
    call_fs(
        "rmSync",
        &[JsValue::from_str(path), removal_options(recursive, force)?],
    )?;
    Ok(())
}

pub async fn rm(path: &str, recursive: bool, force: bool) -> Result<(), JsValue> {
    call_fs_promise(
        "rm",
        &[JsValue::from_str(path), removal_options(recursive, force)?],
    )
    .await?;
    Ok(())
}

pub fn realpath_sync(path: &str) -> Result<String, JsValue> {
    returned_string(
        call_fs("realpathSync", &[JsValue::from_str(path)])?,
        "realpathSync",
    )
}

pub async fn realpath(path: &str) -> Result<String, JsValue> {
    returned_string(
        call_fs_promise("realpath", &[JsValue::from_str(path)]).await?,
        "realpath",
    )
}

pub fn glob_sync(pattern: &str) -> Result<Vec<String>, JsValue> {
    returned_names(call_fs("globSync", &[JsValue::from_str(pattern)])?)
}

pub async fn glob(pattern: &str) -> Result<Vec<String>, JsValue> {
    returned_names(call_fs_callback("glob", &[JsValue::from_str(pattern)]).await?)
}

pub fn glob_to_regex(pattern: &str) -> Result<String, JsValue> {
    returned_string(
        Reflect::get(&zenfs_glob_to_regex(pattern)?, &JsValue::from_str("source"))?,
        "globToRegex",
    )
}

pub fn normalize_path(path: &str) -> Result<String, JsValue> {
    zenfs_normalize_path(path)
}

#[wasm_bindgen(js_name = removeFile)]
pub fn remove_file(path: &str) -> Result<(), JsValue> {
    call_fs("unlinkSync", &[JsValue::from_str(path)])?;
    Ok(())
}

#[wasm_bindgen(js_name = renameSync)]
pub fn rename_sync(from: &str, to: &str) -> Result<(), JsValue> {
    call_fs(
        "renameSync",
        &[JsValue::from_str(from), JsValue::from_str(to)],
    )?;
    Ok(())
}

#[wasm_bindgen(js_name = rename)]
pub async fn rename(from: &str, to: &str) -> Result<(), JsValue> {
    call_fs_promise("rename", &[JsValue::from_str(from), JsValue::from_str(to)]).await?;
    Ok(())
}

pub fn link_sync(original: &str, link: &str) -> Result<(), JsValue> {
    call_fs(
        "linkSync",
        &[JsValue::from_str(original), JsValue::from_str(link)],
    )?;
    Ok(())
}

pub async fn link(original: &str, link: &str) -> Result<(), JsValue> {
    call_fs_promise(
        "link",
        &[JsValue::from_str(original), JsValue::from_str(link)],
    )
    .await?;
    Ok(())
}

pub fn symlink_sync(target: &str, link: &str) -> Result<(), JsValue> {
    call_fs(
        "symlinkSync",
        &[JsValue::from_str(target), JsValue::from_str(link)],
    )?;
    Ok(())
}

pub async fn symlink(target: &str, link: &str) -> Result<(), JsValue> {
    call_fs_promise(
        "symlink",
        &[JsValue::from_str(target), JsValue::from_str(link)],
    )
    .await?;
    Ok(())
}

pub fn readlink_sync(path: &str) -> Result<String, JsValue> {
    returned_string(
        call_fs("readlinkSync", &[JsValue::from_str(path)])?,
        "readlinkSync",
    )
}

pub async fn readlink(path: &str) -> Result<String, JsValue> {
    returned_string(
        call_fs_promise("readlink", &[JsValue::from_str(path)]).await?,
        "readlink",
    )
}

pub fn unlink_sync(path: &str) -> Result<(), JsValue> {
    call_fs("unlinkSync", &[JsValue::from_str(path)])?;
    Ok(())
}

pub async fn unlink(path: &str) -> Result<(), JsValue> {
    call_fs_promise("unlink", &[JsValue::from_str(path)]).await?;
    Ok(())
}

#[cfg(all(test, not(all(feature = "webfs", not(feature = "zenfs")))))]
mod tests {
    use super::*;
    use wasm_bindgen_test::wasm_bindgen_test;

    fn test_path(name: &str) -> String {
        create_dir_all("/app").unwrap();
        format!("/app/renfs-{name}-{:x}", js_sys::Math::random().to_bits())
    }

    async fn wait_for_watch(milliseconds: u32) {
        let promise = js_sys::Promise::new(&mut |resolve, _reject| {
            let callback = Closure::once_into_js(move || {
                let _ = resolve.call0(&JsValue::UNDEFINED);
            });
            let set_timeout = Reflect::get(&js_sys::global(), &JsValue::from_str("setTimeout"))
                .unwrap()
                .dyn_into::<Function>()
                .unwrap();
            set_timeout
                .call2(
                    &JsValue::UNDEFINED,
                    &callback,
                    &JsValue::from_f64(f64::from(milliseconds)),
                )
                .unwrap();
        });
        JsFuture::from(promise).await.unwrap();
    }

    #[wasm_bindgen_test]
    async fn streams_use_zenfs_read_and_write_objects() {
        let root = test_path("streams");
        mkdir_sync(&root, false).unwrap();
        let dir = crate::Directory::new(&root).unwrap();
        let mut output = dir.create_write_stream("data").unwrap();
        output.write(b"abc").await.unwrap();
        output.write(b"defgh").await.unwrap();
        output.end().await.unwrap();
        assert_eq!(dir.read_text("data").unwrap(), "abcdefgh");

        let mut input = dir
            .create_read_stream_with_options(
                "data",
                crate::ReadStreamOptions {
                    start: 2,
                    end: Some(6),
                    chunk_size: 2,
                },
            )
            .unwrap();
        assert_eq!(input.read().await.unwrap(), Some(b"cd".to_vec()));
        assert_eq!(input.read().await.unwrap(), Some(b"ef".to_vec()));
        assert_eq!(input.read().await.unwrap(), Some(b"g".to_vec()));
        assert_eq!(input.read().await.unwrap(), None);
        input.destroy().unwrap();
        let mut replace = dir.create_write_stream("data").unwrap();
        replace.write(b"!").await.unwrap();
        replace.end().await.unwrap();
        assert_eq!(dir.read_text("data").unwrap(), "!");
        let mut positioned = dir
            .create_write_stream_with_options(
                "positioned",
                crate::WriteStreamOptions { start: Some(2) },
            )
            .unwrap();
        positioned.write(b"x").await.unwrap();
        positioned.end().await.unwrap();
        assert_eq!(dir.read_file_sync("positioned").unwrap(), b"\0\0x");

        let mut abandoned = dir.create_read_stream("data").unwrap();
        abandoned.destroy().unwrap();
        assert!(abandoned.read().await.is_err());
        let mut invalid = dir.create_write_stream("missing/child").unwrap();
        assert!(invalid.write(b"bad").await.is_err());
        invalid.destroy().unwrap();
        rm_sync(&root, true, false).unwrap();
    }

    #[wasm_bindgen_test]
    async fn watch_and_watch_file_notify_and_unsubscribe() {
        use std::sync::{Arc, Mutex};
        let root = test_path("watch");
        mkdir_sync(&root, false).unwrap();
        let file = format!("{root}/file");
        let events = Arc::new(Mutex::new(Vec::new()));
        let reported = Arc::clone(&events);
        let mut watcher = crate::fs::watch(&root, move |event, name| {
            reported
                .lock()
                .unwrap()
                .push((event.to_owned(), name.to_owned()));
        })
        .unwrap();
        write_text(&file, "a").unwrap();
        wait_for_watch(50).await;
        assert!(
            events
                .lock()
                .unwrap()
                .iter()
                .any(|(_, name)| name == "file")
        );
        watcher.close().unwrap();

        let first = Arc::new(Mutex::new(Vec::new()));
        let second = Arc::new(Mutex::new(Vec::new()));
        let options = crate::WatchFileOptions {
            interval: std::time::Duration::from_millis(20),
            ..Default::default()
        };
        let reported = Arc::clone(&first);
        let id = crate::fs::watch_file_with_options(&file, options, move |curr, prev| {
            reported.lock().unwrap().push((curr.len(), prev.len()));
        })
        .unwrap();
        let reported = Arc::clone(&second);
        crate::fs::watch_file_with_options(&file, options, move |curr, prev| {
            reported.lock().unwrap().push((curr.len(), prev.len()));
        })
        .unwrap();
        write_text(&file, "longer").unwrap();
        wait_for_watch(120).await;
        assert!(first.lock().unwrap().contains(&(6, 1)));
        assert!(second.lock().unwrap().contains(&(6, 1)));
        crate::fs::unwatch_file_listener(&file, id).unwrap();
        first.lock().unwrap().clear();
        second.lock().unwrap().clear();
        write_text(&file, "even longer").unwrap();
        wait_for_watch(120).await;
        assert!(first.lock().unwrap().is_empty());
        assert!(second.lock().unwrap().contains(&(11, 6)));
        crate::fs::unwatch_file(&file).unwrap();
        second.lock().unwrap().clear();
        write_text(&file, "gone quiet").unwrap();
        wait_for_watch(70).await;
        assert!(second.lock().unwrap().is_empty());
        rm_sync(&root, true, false).unwrap();
    }

    #[wasm_bindgen_test]
    fn app_dir_creates_a_directory_and_rejects_invalid_names() {
        let name = format!("renfs-test-{:x}", js_sys::Math::random().to_bits());
        let path = app_dir(&name).unwrap();

        assert_eq!(path, format!("/app/{name}"));
        assert!(exists_sync(&path).unwrap());

        for invalid in ["", ".", "..", "nested/name", r"nested\name"] {
            let error = app_dir(invalid).unwrap_err();
            assert_eq!(
                error.as_string().as_deref(),
                Some("application name must be a single path component")
            );
        }
    }

    #[wasm_bindgen_test]
    fn javascript_exceptions_are_returned_as_errors() {
        let missing = format!("{}/missing.txt", test_path("missing"));
        let error = read_text(&missing).unwrap_err();
        let message = Reflect::get(&error, &JsValue::from_str("message")).unwrap();
        let message = message.as_string().unwrap();

        assert!(message.starts_with("ENOENT:"));
        assert!(message.contains(&missing));
    }

    #[wasm_bindgen_test]
    async fn open_as_blob_reads_a_file_snapshot() {
        let path = test_path("blob");
        write_file_sync(&path, b"blob contents").unwrap();

        let blob = open_as_blob(&path).await.unwrap();

        assert_eq!(blob, b"blob contents");
    }

    #[wasm_bindgen_test]
    async fn promise_and_callback_filesystem_apis_are_async() {
        let path = test_path("async-apis");
        write_file(&path, b"async").await.unwrap();
        append_file(&path, b" file").await.unwrap();
        assert!(exists(&path).await.unwrap());
        assert_eq!(read_file(&path).await.unwrap(), b"async file");

        let mut options = OpenOptions::new();
        options.read(true);
        let mut file = open(&path, &options).await.unwrap();
        let mut contents = [0; 10];
        assert_eq!(
            read(&mut file, &mut contents).await.unwrap(),
            contents.len()
        );
        assert_eq!(&contents, b"async file");
        assert_eq!(fstat(&file).await.unwrap().len(), contents.len() as u64);
        close(&file).await.unwrap();
    }

    #[wasm_bindgen_test]
    async fn directory_and_path_apis_work() {
        let root = test_path("directory");
        mkdir(&root, false).await.unwrap();
        let nested = format!("{root}/nested");
        mkdir_sync(&nested, false).unwrap();
        assert_eq!(readdir_sync(&root).unwrap(), vec!["nested"]);
        assert_eq!(readdir(&root).await.unwrap(), vec!["nested"]);
        let mut opened = opendir_sync(&root).unwrap();
        let entry = opened.read_sync().unwrap().unwrap();
        assert_eq!(entry.name(), "nested");
        assert!(entry.is_dir());
        assert_eq!(opened.read_sync().unwrap(), None);
        opened.close_sync().unwrap();
        assert!(opened.read_sync().is_err());
        let mut opened = opendir(&root).await.unwrap();
        let entry = opened.read().await.unwrap().unwrap();
        assert_eq!(entry.name(), "nested");
        assert!(entry.is_dir());
        assert_eq!(opened.read().await.unwrap(), None);
        opened.close().await.unwrap();
        assert!(opened.read().await.is_err());
        assert_eq!(realpath_sync(&nested).unwrap(), nested);
        assert_eq!(realpath(&nested).await.unwrap(), nested);
        let expected = nested.trim_start_matches('/').to_owned();
        assert!(glob_sync(&format!("{root}/*")).unwrap().contains(&expected));
        assert!(
            glob(&format!("{root}/*"))
                .await
                .unwrap()
                .contains(&expected)
        );
        assert!(!glob_to_regex("*.txt").unwrap().is_empty());
        assert_eq!(
            normalize_path("/app/./nested/../file").unwrap(),
            "/app/file"
        );
        rmdir(&nested).await.unwrap();
        rm_sync(&root, true, false).unwrap();
        rm(&root, true, true).await.unwrap();
    }

    #[wasm_bindgen_test]
    async fn temporary_directory_apis_work() {
        let prefix = test_path("temporary");
        let first = mkdtemp_sync(&prefix).unwrap();
        let second = mkdtemp(&prefix).await.unwrap();
        assert_ne!(first, second);
        let disposable = mkdtemp_disposable_sync(&prefix).unwrap();
        let path = disposable.path().to_owned();
        assert!(exists_sync(&path).unwrap());
        drop(disposable);
        assert!(!exists_sync(&path).unwrap());
        rm_sync(&first, true, false).unwrap();
        rm_sync(&second, true, false).unwrap();
    }

    #[wasm_bindgen_test]
    async fn metadata_permissions_and_timestamps_work() {
        let root = test_path("metadata");
        mkdir_sync(&root, false).unwrap();
        let path = format!("{root}/file");
        write_file_sync(&path, b"hello").unwrap();
        assert_eq!(stat_sync(&path).unwrap().len(), 5);
        assert!(lstat_sync(&path).unwrap().is_file());
        assert_eq!(stat(&path).await.unwrap().len(), 5);
        assert!(lstat(&path).await.unwrap().is_file());
        assert!(statfs_sync(&path).unwrap().block_size > 0);
        assert!(statfs(&path).await.unwrap().blocks > 0.0);
        let time = UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000);
        chmod_sync(&path, 0o640).unwrap();
        chmod(&path, 0o600).await.unwrap();
        chown_sync(&path, 1, 1).unwrap();
        chown(&path, 1, 1).await.unwrap();
        utimes_sync(&path, time, time).unwrap();
        utimes(&path, time, time).await.unwrap();
        let options = OpenOptions {
            read: true,
            ..OpenOptions::default()
        };
        let file = open_sync(&path, &options).unwrap();
        fchmod_sync(&file, 0o644).unwrap();
        fchmod(&file, 0o600).await.unwrap();
        fchown_sync(&file, 1, 1).unwrap();
        fchown(&file, 1, 1).await.unwrap();
        futimes_sync(&file, time, time).unwrap();
        futimes(&file, time, time).await.unwrap();
        close_sync(file).unwrap();
        let link = format!("{root}/link");
        call_fs(
            "symlinkSync",
            &[JsValue::from_str(&path), JsValue::from_str(&link)],
        )
        .unwrap();
        assert!(lstat_sync(&link).unwrap().is_symlink());
        assert!(stat_sync(&link).unwrap().is_file());
        lchown_sync(&link, 1, 1).unwrap();
        lchown(&link, 1, 1).await.unwrap();
        lutimes_sync(&link, time, time).unwrap();
        lutimes(&link, time, time).await.unwrap();
        lchmod_sync(&link, 0o777).unwrap();
        lchmod(&link, 0o777).await.unwrap();
        rm_sync(&root, true, false).unwrap();
    }

    #[wasm_bindgen_test]
    async fn link_and_rename_apis_work() {
        let root = test_path("links");
        mkdir_sync(&root, false).unwrap();
        let source = format!("{root}/source");
        let hard = format!("{root}/hard");
        let moved = format!("{root}/moved");
        let symbolic = format!("{root}/symbolic");
        write_text(&source, "value").unwrap();
        link_sync(&source, &hard).unwrap();
        rename(&hard, &moved).await.unwrap();
        unlink_sync(&source).unwrap();
        assert_eq!(read_text(&moved).unwrap(), "value");
        link(&moved, &hard).await.unwrap();
        rename_sync(&hard, &source).unwrap();
        unlink(&source).await.unwrap();
        symlink_sync(&moved, &symbolic).unwrap();
        assert_eq!(readlink_sync(&symbolic).unwrap(), moved);
        assert_eq!(readlink(&symbolic).await.unwrap(), moved);
        unlink_sync(&symbolic).unwrap();
        symlink(&moved, &symbolic).await.unwrap();
        assert!(lstat_sync(&symbolic).unwrap().is_symlink());
        unlink(&symbolic).await.unwrap();
        unlink_sync(&moved).unwrap();
        rm_sync(&root, true, false).unwrap();
    }

    #[wasm_bindgen_test]
    async fn directory_symlink_targets_stay_relative_and_inside_root() {
        let root = test_path("relative-links");
        mkdir_sync(&root, false).unwrap();
        let dir = crate::Directory::new(&root).unwrap();
        dir.mkdir_sync("nested", false).unwrap();
        dir.write_text("source", "value").unwrap();
        dir.symlink_sync("../source", "nested/link").unwrap();
        assert_eq!(dir.readlink_sync("nested/link").unwrap(), "../source");
        assert_eq!(dir.read_text("nested/link").unwrap(), "value");
        let mut opened = dir.opendir_sync("nested").unwrap();
        let entry = opened.read_sync().unwrap().unwrap();
        assert_eq!(entry.name(), "link");
        assert!(entry.is_symlink());
        opened.close_sync().unwrap();
        dir.symlink("../missing", "nested/dangling").await.unwrap();
        assert_eq!(dir.readlink("nested/dangling").await.unwrap(), "../missing");
        assert!(dir.symlink_sync("../../outside", "nested/escape").is_err());
        dir.unlink("nested/link").await.unwrap();
        assert_eq!(dir.read_text("source").unwrap(), "value");
        rm_sync(&root, true, false).unwrap();
    }
}

#[cfg(all(test, not(all(feature = "webfs", not(feature = "zenfs")))))]
#[path = "implementation_tests.rs"]
mod shared_tests;