wasm-rquickjs 0.3.4

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// deno-lint-ignore-file

import { addAbortSignalNoValidate } from "__wasm_rquickjs_builtin/internal/streams/add-abort-signal";
import { Buffer } from "buffer";
import { debuglog } from "__wasm_rquickjs_builtin/internal/util/debuglog";
import { getDefaultHighWaterMark, getHighWaterMark } from "__wasm_rquickjs_builtin/internal/streams/state";
import { prependListener, Stream } from "__wasm_rquickjs_builtin/internal/streams/legacy";
import { StringDecoder } from "string_decoder";
import { validateObject, validateBoolean, validateAbortSignal, validateInteger } from "__wasm_rquickjs_builtin/internal/validators";
import {
    AbortError,
    aggregateTwoErrors,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_METHOD_NOT_IMPLEMENTED,
    ERR_OUT_OF_RANGE,
    ERR_STREAM_PUSH_AFTER_EOF,
    ERR_STREAM_UNSHIFT_AFTER_END_EVENT,
    ERR_UNKNOWN_ENCODING,
} from "__wasm_rquickjs_builtin/internal/errors";
import _from from "__wasm_rquickjs_builtin/internal/streams/from";
import BufferList from "__wasm_rquickjs_builtin/internal/streams/buffer_list";
import destroyImpl from "__wasm_rquickjs_builtin/internal/streams/destroy";
import EventEmitter from "events";
import { nextTick } from "node:process";
import { isDestroyed, isReadable } from "__wasm_rquickjs_builtin/internal/streams/utils";
import eos from "__wasm_rquickjs_builtin/internal/streams/end-of-stream";

let debug = debuglog("stream", (fn) => {
    debug = fn;
});

const kPaused = Symbol("kPaused");

const nop = () => { };

const { errorOrDestroy } = destroyImpl;

function ReadableState(options, stream, isDuplex) {
    // Duplex streams are both readable and writable, but share
    // the same options object.
    // However, some cases require setting options to different
    // values for the readable and the writable sides of the duplex stream.
    // These options can be provided separately as readableXXX and writableXXX.
    if (typeof isDuplex !== "boolean") {
        isDuplex = stream instanceof Stream.Duplex;
    }

    // Object stream flag. Used to make read(n) ignore n and to
    // make all the buffer merging and length checks go away.
    this.objectMode = !!(options && options.objectMode);

    if (isDuplex) {
        this.objectMode = this.objectMode ||
            !!(options && options.readableObjectMode);
    }

    // The point at which it stops calling _read() to fill the buffer
    // Note: 0 is a valid value, means "don't call _read preemptively ever"
    this.highWaterMark = options
        ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex)
        : getDefaultHighWaterMark(false);

    // A linked list is used to store data chunks instead of an array because the
    // linked list can remove elements from the beginning faster than
    // array.shift().
    this.buffer = new BufferList();
    this.length = 0;
    this.pipes = [];
    this.flowing = null;
    this.ended = false;
    this.endEmitted = false;
    this.reading = false;

    // Stream is still being constructed and cannot be
    // destroyed until construction finished or failed.
    // Async construction is opt in, therefore we start as
    // constructed.
    this.constructed = true;

    // A flag to be able to tell if the event 'readable'/'data' is emitted
    // immediately, or on a later tick.  We set this to true at first, because
    // any actions that shouldn't happen until "later" should generally also
    // not happen before the first read call.
    this.sync = true;

    // Whenever we return null, then we set a flag to say
    // that we're awaiting a 'readable' event emission.
    this.needReadable = false;
    this.emittedReadable = false;
    this.readableListening = false;
    this.resumeScheduled = false;
    this[kPaused] = null;

    // True if the error was already emitted and should not be thrown again.
    this.errorEmitted = false;

    // Should close be emitted on destroy. Defaults to true.
    this.emitClose = !options || options.emitClose !== false;

    // Should .destroy() be called after 'end' (and potentially 'finish').
    this.autoDestroy = !options || options.autoDestroy !== false;

    // Has it been destroyed.
    this.destroyed = false;

    // Indicates whether the stream has errored. When true no further
    // _read calls, 'data' or 'readable' events should occur. This is needed
    // since when autoDestroy is disabled we need a way to tell whether the
    // stream has failed.
    this.errored = null;

    // Indicates whether the stream has finished destroying.
    this.closed = false;

    // True if close has been emitted or would have been emitted
    // depending on emitClose.
    this.closeEmitted = false;

    // Crypto is kind of old and crusty.  Historically, its default string
    // encoding is 'binary' so we have to make this configurable.
    // Everything else in the universe uses 'utf8', though.
    this.defaultEncoding = (options && options.defaultEncoding) || "utf8";
    if (!Buffer.isEncoding(this.defaultEncoding)) {
        throw new ERR_UNKNOWN_ENCODING(this.defaultEncoding);
    }

    // Ref the piped dest which we need a drain event on it
    // type: null | Writable | Set<Writable>.
    this.awaitDrainWriters = null;
    this.multiAwaitDrain = false;

    // If true, a maybeReadMore has been scheduled.
    this.readingMore = false;

    this.dataEmitted = false;

    this.decoder = null;
    this.encoding = null;
    if (options && options.encoding) {
        this.decoder = new StringDecoder(options.encoding);
        this.encoding = options.encoding;
    }
}


function Readable(options) {
    if (!(this instanceof Readable)) {
        return new Readable(options);
    }

    // Pre-initialize _events with well-known event slots to preserve
    // property insertion order (matching Node.js v22 behavior).
    if (!this._events) {
        this._events = Object.create(null);
        this._events.close = undefined;
        this._events.error = undefined;
        this._events.data = undefined;
        this._events.end = undefined;
        this._events.readable = undefined;
        this._eventsCount = 0;
    }

    // Checking for a Stream.Duplex instance is faster here instead of inside
    // the ReadableState constructor, at least with V8 6.5.
    const isDuplex = this instanceof Stream.Duplex;

    this._readableState = new ReadableState(options, this, isDuplex);

    if (options) {
        if (typeof options.read === "function") {
            this._read = options.read;
        }

        if (typeof options.destroy === "function") {
            this._destroy = options.destroy;
        }

        if (typeof options.construct === "function") {
            this._construct = options.construct;
        }
    }

    Stream.call(this, options);

    if (options && options.signal && !isDuplex) {
        addAbortSignalNoValidate(options.signal, this);
    }

    destroyImpl.construct(this, () => {
        if (this._readableState.needReadable) {
            maybeReadMore(this, this._readableState);
        }
    });
}

Object.setPrototypeOf(Readable.prototype, Stream.prototype);
Object.setPrototypeOf(Readable, Stream);

Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
    cb(err);
};

Readable.prototype[EventEmitter.captureRejectionSymbol] = function (err) {
    this.destroy(err);
};

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
    return readableAddChunk(this, chunk, encoding, false);
};

// Unshift should *always* be something directly out of read().
Readable.prototype.unshift = function (chunk, encoding) {
    return readableAddChunk(this, chunk, encoding, true);
};

function readableAddChunk(stream, chunk, encoding, addToFront) {
    debug("readableAddChunk", chunk);
    const state = stream._readableState;

    let err;
    if (!state.objectMode) {
        if (typeof chunk === "string") {
            encoding = encoding || state.defaultEncoding;
            if (state.encoding !== encoding) {
                if (addToFront && state.encoding) {
                    // When unshifting, if state.encoding is set, we have to save
                    // the string in the BufferList with the state encoding.
                    chunk = Buffer.from(chunk, encoding).toString(state.encoding);
                } else {
                    chunk = Buffer.from(chunk, encoding);
                    encoding = "";
                }
            }
        } else if (chunk instanceof Buffer) {
            encoding = "";
        } else if (ArrayBuffer.isView(chunk)) {
            chunk = Stream._uint8ArrayToBuffer(chunk);
            encoding = "";
        } else if (chunk != null) {
            err = new ERR_INVALID_ARG_TYPE(
                "chunk",
                ["string", "Buffer", "TypedArray", "DataView"],
                chunk,
            );
        }
    }

    if (err) {
        errorOrDestroy(stream, err);
    } else if (chunk === null) {
        state.reading = false;
        onEofChunk(stream, state);
    } else if (state.objectMode || (chunk && chunk.length > 0)) {
        if (addToFront) {
            if (state.endEmitted) {
                errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
            } else {
                addChunk(stream, state, chunk, true);
            }
        } else if (state.ended) {
            errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
        } else if (state.destroyed || state.errored) {
            return false;
        } else {
            state.reading = false;
            if (state.decoder && !encoding) {
                chunk = state.decoder.write(chunk);
                if (state.objectMode || chunk.length !== 0) {
                    addChunk(stream, state, chunk, false);
                } else {
                    maybeReadMore(stream, state);
                }
            } else {
                addChunk(stream, state, chunk, false);
            }
        }
    } else if (!addToFront) {
        state.reading = false;
        maybeReadMore(stream, state);
    }

    // We can push more data if we are below the highWaterMark.
    // Also, if we have no data yet, we can stand some more bytes.
    // This is to work around cases where hwm=0, such as the repl.
    return !state.ended &&
        (state.length < state.highWaterMark || state.length === 0);
}


function addChunk(stream, state, chunk, addToFront) {
    if (
        state.flowing && state.length === 0 && !state.sync &&
        stream.listenerCount("data") > 0
    ) {
        // Use the guard to avoid creating `Set()` repeatedly
        // when we have multiple pipes.
        if (state.multiAwaitDrain) {
            state.awaitDrainWriters.clear();
        } else {
            state.awaitDrainWriters = null;
        }
        state.dataEmitted = true;
        stream.emit("data", chunk);
    } else {
        // Update the buffer info.
        state.length += state.objectMode ? 1 : chunk.length;
        if (addToFront) {
            state.buffer.unshift(chunk);
        } else {
            state.buffer.push(chunk);
        }

        if (state.needReadable) {
            emitReadable(stream);
        }
    }
    maybeReadMore(stream, state);
}

Readable.prototype.isPaused = function () {
    const state = this._readableState;
    return state[kPaused] === true || state.flowing === false;
};

// Backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
    const decoder = new StringDecoder(enc);
    this._readableState.decoder = decoder;
    // If setEncoding(null), decoder.encoding equals utf8.
    this._readableState.encoding = this._readableState.decoder.encoding;

    const buffer = this._readableState.buffer;
    // Iterate over current buffer to convert already stored Buffers:
    let content = "";
    for (const data of buffer) {
        content += decoder.write(data);
    }
    buffer.clear();
    if (content !== "") {
        buffer.push(content);
    }
    this._readableState.length = content.length;
    return this;
};

// Don't raise the hwm > 1GB.
const MAX_HWM = 0x40000000;
function computeNewHighWaterMark(n) {
    if (n > MAX_HWM) {
        throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n);
    } else if (n === MAX_HWM) {
        return MAX_HWM;
    } else {
        // Get the next highest power of 2 to prevent increasing hwm excessively in
        // tiny amounts.
        n--;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        n++;
    }
    return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
    if (n <= 0 || (state.length === 0 && state.ended)) {
        return 0;
    }
    if (state.objectMode) {
        return 1;
    }
    if (Number.isNaN(n)) {
        // Only flow one buffer at a time.
        if (state.flowing && state.length) {
            return state.buffer.first().length;
        }
        return state.length;
    }
    if (n <= state.length) {
        return n;
    }
    return state.ended ? state.length : 0;
}

// You can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
    debug("read", n);
    // Same as parseInt(undefined, 10), however V8 7.3 performance regressed
    // in this scenario, so we are doing it manually.
    if (n === undefined) {
        n = NaN;
    } else if (!Number.isInteger(n)) {
        n = Number.parseInt(n, 10);
    }
    const state = this._readableState;
    const nOrig = n;

    // If we're asking for more than the current hwm, then raise the hwm.
    if (n > state.highWaterMark) {
        state.highWaterMark = computeNewHighWaterMark(n);
    }

    if (n !== 0) {
        state.emittedReadable = false;
    }

    // If we're doing read(0) to trigger a readable event, but we
    // already have a bunch of data in the buffer, then just trigger
    // the 'readable' event and move on.
    if (
        n === 0 &&
        state.needReadable &&
        ((state.highWaterMark !== 0
            ? state.length >= state.highWaterMark
            : state.length > 0) ||
            state.ended)
    ) {
        debug("read: emitReadable", state.length, state.ended);
        if (state.length === 0 && state.ended) {
            endReadable(this);
        } else {
            emitReadable(this);
        }
        return null;
    }

    n = howMuchToRead(n, state);

    // If we've ended, and we're now clear, then finish it up.
    if (n === 0 && state.ended) {
        if (state.length === 0) {
            endReadable(this);
        }
        return null;
    }

    // All the actual chunk generation logic needs to be
    // *below* the call to _read.  The reason is that in certain
    // synthetic stream cases, such as passthrough streams, _read
    // may be a completely synchronous operation which may change
    // the state of the read buffer, providing enough data when
    // before there was *not* enough.
    //
    // So, the steps are:
    // 1. Figure out what the state of things will be after we do
    // a read from the buffer.
    //
    // 2. If that resulting state will trigger a _read, then call _read.
    // Note that this may be asynchronous, or synchronous.  Yes, it is
    // deeply ugly to write APIs this way, but that still doesn't mean
    // that the Readable class should behave improperly, as streams are
    // designed to be sync/async agnostic.
    // Take note if the _read call is sync or async (ie, if the read call
    // has returned yet), so that we know whether or not it's safe to emit
    // 'readable' etc.
    //
    // 3. Actually pull the requested chunks out of the buffer and return.

    // if we need a readable event, then we need to do some reading.
    let doRead = state.needReadable;
    debug("need readable", doRead);

    // If we currently have less than the highWaterMark, then also read some.
    if (state.length === 0 || state.length - n < state.highWaterMark) {
        doRead = true;
        debug("length less than watermark", doRead);
    }

    // However, if we've ended, then there's no point, if we're already
    // reading, then it's unnecessary, if we're constructing we have to wait,
    // and if we're destroyed or errored, then it's not allowed,
    if (
        state.ended || state.reading || state.destroyed || state.errored ||
        !state.constructed
    ) {
        doRead = false;
        debug("reading, ended or constructing", doRead);
    } else if (doRead) {
        debug("do read");
        state.reading = true;
        state.sync = true;
        // If the length is currently zero, then we *need* a readable event.
        if (state.length === 0) {
            state.needReadable = true;
        }

        // Call internal read method
        try {
            this._read(state.highWaterMark);
        } catch (err) {
            errorOrDestroy(this, err);
        }

        state.sync = false;
        // If _read pushed data synchronously, then `reading` will be false,
        // and we need to re-evaluate how much data we can return to the user.
        if (!state.reading) {
            n = howMuchToRead(nOrig, state);
        }
    }

    let ret;
    if (n > 0) {
        ret = fromList(n, state);
    } else {
        ret = null;
    }

    if (ret === null) {
        state.needReadable = state.length <= state.highWaterMark;
        n = 0;
    } else {
        state.length -= n;
        if (state.multiAwaitDrain) {
            state.awaitDrainWriters.clear();
        } else {
            state.awaitDrainWriters = null;
        }
    }

    if (state.length === 0) {
        // If we have nothing in the buffer, then we want to know
        // as soon as we *do* get something into the buffer.
        if (!state.ended) {
            state.needReadable = true;
        }

        // If we tried to read() past the EOF, then emit end on the next tick.
        if (nOrig !== n && state.ended) {
            endReadable(this);
        }
    }

    if (ret !== null) {
        state.dataEmitted = true;
        this.emit("data", ret);
    }

    return ret;
};

function onEofChunk(stream, state) {
    debug("onEofChunk");
    if (state.ended) return;
    if (state.decoder) {
        const chunk = state.decoder.end();
        if (chunk && chunk.length) {
            state.buffer.push(chunk);
            state.length += state.objectMode ? 1 : chunk.length;
        }
    }
    state.ended = true;

    if (state.sync) {
        // If we are sync, wait until next tick to emit the data.
        // Otherwise we risk emitting data in the flow()
        // the readable code triggers during a read() call.
        emitReadable(stream);
    } else {
        // Emit 'readable' now to make sure it gets picked up.
        state.needReadable = false;
        state.emittedReadable = true;
        // We have to emit readable now that we are EOF. Modules
        // in the ecosystem (e.g. dicer) rely on this event being sync.
        emitReadable_(stream);
    }
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
    const state = stream._readableState;
    debug("emitReadable", state.needReadable, state.emittedReadable);
    state.needReadable = false;
    if (!state.emittedReadable) {
        debug("emitReadable", state.flowing);
        state.emittedReadable = true;
        nextTick(emitReadable_, stream);
    }
}

function emitReadable_(stream) {
    const state = stream._readableState;
    debug("emitReadable_", state.destroyed, state.length, state.ended);
    if (!state.destroyed && !state.errored && (state.length || state.ended)) {
        stream.emit("readable");
        state.emittedReadable = false;
    }

    // The stream needs another readable event if:
    // 1. It is not flowing, as the flow mechanism will take
    //    care of it.
    // 2. It is not ended.
    // 3. It is below the highWaterMark, so we can schedule
    //    another readable later.
    state.needReadable = !state.flowing &&
        !state.ended &&
        state.length <= state.highWaterMark;
    flow(stream);
}

// At this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
    if (!state.readingMore && state.constructed) {
        state.readingMore = true;
        nextTick(maybeReadMore_, stream, state);
    }
}

function maybeReadMore_(stream, state) {
    // Attempt to read more data if we should.
    //
    // The conditions for reading more data are (one of):
    // - Not enough data buffered (state.length < state.highWaterMark). The loop
    //   is responsible for filling the buffer with enough data if such data
    //   is available. If highWaterMark is 0 and we are not in the flowing mode
    //   we should _not_ attempt to buffer any extra data. We'll get more data
    //   when the stream consumer calls read() instead.
    // - No data in the buffer, and the stream is in flowing mode. In this mode
    //   the loop below is responsible for ensuring read() is called. Failing to
    //   call read here would abort the flow and there's no other mechanism for
    //   continuing the flow if the stream consumer has just subscribed to the
    //   'data' event.
    //
    // In addition to the above conditions to keep reading data, the following
    // conditions prevent the data from being read:
    // - The stream has ended (state.ended).
    // - There is already a pending 'read' operation (state.reading). This is a
    //   case where the stream has called the implementation defined _read()
    //   method, but they are processing the call asynchronously and have _not_
    //   called push() with new data. In this case we skip performing more
    //   read()s. The execution ends in this method again after the _read() ends
    //   up calling push() with more data.
    while (
        !state.reading && !state.ended &&
        (state.length < state.highWaterMark ||
            (state.flowing && state.length === 0))
    ) {
        const len = state.length;
        debug("maybeReadMore read 0");
        stream.read(0);
        if (len === state.length) {
            // Didn't get any data, stop spinning.
            break;
        }
    }
    state.readingMore = false;
}

// Abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
    throw new ERR_METHOD_NOT_IMPLEMENTED("_read()");
};

Readable.prototype.pipe = function (dest, pipeOpts) {
    const src = this;
    const state = this._readableState;

    if (state.pipes.length === 1) {
        if (!state.multiAwaitDrain) {
            state.multiAwaitDrain = true;
            state.awaitDrainWriters = new Set(
                state.awaitDrainWriters ? [state.awaitDrainWriters] : [],
            );
        }
    }

    state.pipes.push(dest);
    debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts);

    const doEnd = (!pipeOpts || pipeOpts.end !== false)
    // &&
    // dest !== stdio.stdout &&
    // dest !== stdio.stderr;

    const endFn = doEnd ? onend : unpipe;
    if (state.endEmitted) {
        nextTick(endFn);
    } else {
        src.once("end", endFn);
    }

    dest.on("unpipe", onunpipe);
    function onunpipe(readable, unpipeInfo) {
        debug("onunpipe");
        if (readable === src) {
            if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
                unpipeInfo.hasUnpiped = true;
                cleanup();
            }
        }
    }

    function onend() {
        debug("onend");
        dest.end();
    }

    let ondrain;

    let cleanedUp = false;
    function cleanup() {
        debug("cleanup");
        // Cleanup event handlers once the pipe is broken.
        dest.removeListener("close", onclose);
        dest.removeListener("finish", onfinish);
        if (ondrain) {
            dest.removeListener("drain", ondrain);
        }
        dest.removeListener("error", onerror);
        dest.removeListener("unpipe", onunpipe);
        src.removeListener("end", onend);
        src.removeListener("end", unpipe);
        src.removeListener("data", ondata);

        cleanedUp = true;

        // If the reader is waiting for a drain event from this
        // specific writer, then it would cause it to never start
        // flowing again.
        // So, if this is awaiting a drain, then we just call it now.
        // If we don't know, then assume that we are waiting for one.
        if (
            ondrain && state.awaitDrainWriters &&
            (!dest._writableState || dest._writableState.needDrain)
        ) {
            ondrain();
        }
    }

    function pause() {
        // If the user unpiped during `dest.write()`, it is possible
        // to get stuck in a permanently paused state if that write
        // also returned false.
        // => Check whether `dest` is still a piping destination.
        if (!cleanedUp) {
            if (state.pipes.length === 1 && state.pipes[0] === dest) {
                debug("false write response, pause", 0);
                state.awaitDrainWriters = dest;
                state.multiAwaitDrain = false;
            } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {
                debug("false write response, pause", state.awaitDrainWriters.size);
                state.awaitDrainWriters.add(dest);
            }
            src.pause();
        }
        if (!ondrain) {
            // When the dest drains, it reduces the awaitDrain counter
            // on the source.  This would be more elegant with a .once()
            // handler in flow(), but adding and removing repeatedly is
            // too slow.
            ondrain = pipeOnDrain(src, dest);
            dest.on("drain", ondrain);
        }
    }

    src.on("data", ondata);
    function ondata(chunk) {
        debug("ondata");
        const ret = dest.write(chunk);
        debug("dest.write", ret);
        if (ret === false) {
            pause();
        }
    }

    // If the dest has an error, then stop piping into it.
    // However, don't suppress the throwing behavior for this.
    function onerror(er) {
        debug("onerror", er);
        unpipe();
        dest.removeListener("error", onerror);
        if (EventEmitter.listenerCount(dest, "error") === 0) {
            const s = dest._writableState || dest._readableState;
            if (s && !s.errorEmitted) {
                // User incorrectly emitted 'error' directly on the stream.
                errorOrDestroy(dest, er);
            } else {
                dest.emit("error", er);
            }
        }
    }

    // Make sure our error handler is attached before userland ones.
    prependListener(dest, "error", onerror);

    // Both close and finish should trigger unpipe, but only once.
    function onclose() {
        dest.removeListener("finish", onfinish);
        unpipe();
    }
    dest.once("close", onclose);
    function onfinish() {
        debug("onfinish");
        dest.removeListener("close", onclose);
        unpipe();
    }
    dest.once("finish", onfinish);

    function unpipe() {
        debug("unpipe");
        src.unpipe(dest);
    }

    // Tell the dest that it's being piped to.
    dest.emit("pipe", src);

    // Start the flow if it hasn't been started already.

    if (dest.writableNeedDrain === true) {
        pause();
    } else if (!state.flowing) {
        debug("pipe resume");
        src.resume();
    }

    return dest;
};

function pipeOnDrain(src, dest) {
    return function pipeOnDrainFunctionResult() {
        const state = src._readableState;

        // `ondrain` will call directly,
        // `this` maybe not a reference to dest,
        // so we use the real dest here.
        if (state.awaitDrainWriters === dest) {
            debug("pipeOnDrain", 1);
            state.awaitDrainWriters = null;
        } else if (state.multiAwaitDrain) {
            debug("pipeOnDrain", state.awaitDrainWriters.size);
            state.awaitDrainWriters.delete(dest);
        }

        if (
            (!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) &&
            EventEmitter.listenerCount(src, "data")
        ) {
            state.flowing = true;
            flow(src);
        }
    };
}


Readable.prototype.unpipe = function (dest) {
    const state = this._readableState;
    const unpipeInfo = { hasUnpiped: false };

    // If we're not piping anywhere, then do nothing.
    if (state.pipes.length === 0) {
        return this;
    }

    if (!dest) {
        // remove all.
        const dests = state.pipes;
        state.pipes = [];
        this.pause();

        for (let i = 0; i < dests.length; i++) {
            dests[i].emit("unpipe", this, { hasUnpiped: false });
        }
        return this;
    }

    // Try to find the right one.
    const index = state.pipes.indexOf(dest);
    if (index === -1) {
        return this;
    }

    state.pipes.splice(index, 1);
    if (state.pipes.length === 0) {
        this.pause();
    }

    dest.emit("unpipe", this, unpipeInfo);

    return this;
};

// Set up data events if they are asked for
// Ensure readable listeners eventually get something.
Readable.prototype.on = function (ev, fn) {
    const res = Stream.prototype.on.call(this, ev, fn);
    const state = this._readableState;

    if (ev === "data") {
        // Update readableListening so that resume() may be a no-op
        // a few lines down. This is needed to support once('readable').
        state.readableListening = this.listenerCount("readable") > 0;

        // Try start flowing on next tick if stream isn't explicitly paused.
        if (state.flowing !== false) {
            this.resume();
        }
    } else if (ev === "readable") {
        if (!state.endEmitted && !state.readableListening) {
            state.readableListening = state.needReadable = true;
            state.flowing = false;
            state.emittedReadable = false;
            debug("on readable", state.length, state.reading);
            if (state.length) {
                emitReadable(this);
            } else if (!state.reading) {
                nextTick(nReadingNextTick, this);
            }
        }
    }

    return res;
};
Readable.prototype.addListener = Readable.prototype.on;

Readable.prototype.once = function (ev, fn) {
    const onceWrapper = (...args) => {
        this.removeListener(ev, onceWrapper);
        fn.apply(this, args);
    };
    onceWrapper.listener = fn;
    return this.on(ev, onceWrapper);
};

Readable.prototype.removeListener = function (ev, fn) {
    const res = Stream.prototype.removeListener.call(this, ev, fn);

    if (ev === "readable") {
        // We need to check if there is someone still listening to
        // readable and reset the state. However this needs to happen
        // after readable has been emitted but before I/O (nextTick) to
        // support once('readable', fn) cycles. This means that calling
        // resume within the same tick will have no
        // effect.
        nextTick(updateReadableListening, this);
    }

    return res;
};
Readable.prototype.off = Readable.prototype.removeListener;

Readable.prototype.removeAllListeners = function (ev) {
    const res = Stream.prototype.removeAllListeners.apply(this, arguments);

    if (ev === "readable" || ev === undefined) {
        // We need to check if there is someone still listening to
        // readable and reset the state. However this needs to happen
        // after readable has been emitted but before I/O (nextTick) to
        // support once('readable', fn) cycles. This means that calling
        // resume within the same tick will have no
        // effect.
        nextTick(updateReadableListening, this);
    }

    return res;
};

function updateReadableListening(self) {
    const state = self._readableState;
    state.readableListening = self.listenerCount("readable") > 0;

    if (state.resumeScheduled && state[kPaused] === false) {
        // Flowing needs to be set to true now, otherwise
        // the upcoming resume will not flow.
        state.flowing = true;

        // Crude way to check if we should resume.
    } else if (self.listenerCount("data") > 0) {
        self.resume();
    } else if (!state.readableListening) {
        state.flowing = null;
    }
}

function nReadingNextTick(self) {
    debug("readable nexttick read 0");
    self.read(0);
}

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
    const state = this._readableState;
    if (!state.flowing) {
        debug("resume");
        // We flow only if there is no one listening
        // for readable, but we still have to call
        // resume().
        state.flowing = !state.readableListening;
        resume(this, state);
    }
    state[kPaused] = false;
    return this;
};

function resume(stream, state) {
    if (!state.resumeScheduled) {
        state.resumeScheduled = true;
        nextTick(resume_, stream, state);
    }
}

function resume_(stream, state) {
    debug("resume", state.reading);
    if (!state.reading) {
        stream.read(0);
    }

    state.resumeScheduled = false;
    stream.emit("resume");
    flow(stream);
    if (state.flowing && !state.reading) {
        stream.read(0);
    }
}

Readable.prototype.pause = function () {
    debug("call pause flowing=%j", this._readableState.flowing);
    if (this._readableState.flowing !== false) {
        debug("pause");
        this._readableState.flowing = false;
        this.emit("pause");
    }
    this._readableState[kPaused] = true;
    return this;
};

function flow(stream) {
    const state = stream._readableState;
    debug("flow", state.flowing);
    while (state.flowing && stream.read() !== null);
}

// Wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
    let paused = false;

    // TODO (ronag): Should this.destroy(err) emit
    // 'error' on the wrapped stream? Would require
    // a static factory method, e.g. Readable.wrap(stream).

    stream.on("data", (chunk) => {
        if (!this.push(chunk) && stream.pause) {
            paused = true;
            stream.pause();
        }
    });

    stream.on("end", () => {
        this.push(null);
    });

    stream.on("error", (err) => {
        errorOrDestroy(this, err);
    });

    stream.on("close", () => {
        this.destroy();
    });

    stream.on("destroy", () => {
        this.destroy();
    });

    this._read = () => {
        if (paused && stream.resume) {
            paused = false;
            stream.resume();
        }
    };

    // Proxy all the other methods. Important when wrapping filters and duplexes.
    const streamKeys = Object.keys(stream);
    for (let j = 1; j < streamKeys.length; j++) {
        const i = streamKeys[j];
        if (this[i] === undefined && typeof stream[i] === "function") {
            this[i] = stream[i].bind(stream);
        }
    }

    return this;
};

Readable.prototype[Symbol.asyncIterator] = function () {
    return streamToAsyncIterator(this);
};

Readable.prototype.iterator = function (options) {
    if (options !== undefined) {
        validateObject(options, "options");
    }
    return streamToAsyncIterator(this, options);
};

function streamToAsyncIterator(stream, options) {
    if (typeof stream.read !== "function") {
        stream = Readable.wrap(stream, { objectMode: true });
    }

    const opts = {
        destroyOnReturn: true,
        destroyOnError: true,
        ...options,
    };

    const gen = createAsyncIterator(stream, opts);

    // Wrap the async generator to perform synchronous cleanup in return().
    // QuickJS does not properly await async generator return() in
    // for-await-of when the loop body throws, so we mark the stream
    // as destroyed synchronously. The actual destroy() call still happens
    // in the generator's finally block to avoid triggering side effects
    // (like eos callbacks) before the error has propagated.
    const iter = {
        stream: stream,
        next: gen.next.bind(gen),
        return: function () {
            if (opts.destroyOnReturn) {
                const state = stream._readableState;
                if (state && !state.destroyed) {
                    if (state.autoDestroy || !state.endEmitted) {
                        state.destroyed = true;
                    }
                }
            }
            return gen.return();
        },
        throw: gen.throw.bind(gen),
        [Symbol.asyncIterator]() { return this; },
    };

    return iter;
}

async function* createAsyncIterator(stream, opts) {
    let callback = nop;

    function next(resolve) {
        if (this === stream) {
            callback();
            callback = nop;
        } else {
            callback = resolve;
        }
    }

    stream.on("readable", next);

    // Use eos (end-of-stream) to detect premature close.
    // When a stream is destroyed without emitting 'end', eos generates
    // ERR_STREAM_PREMATURE_CLOSE. The error variable uses three states:
    //   undefined = still waiting
    //   null      = clean end (stream ended normally)
    //   truthy    = error occurred (throw it)
    let error;
    const cleanup = eos(stream, { writable: false }, (err) => {
        error = err ? aggregateTwoErrors(error, err) : null;
        callback();
        callback = nop;
    });

    try {
        while (true) {
            const chunk = stream.destroyed ? null : stream.read();
            if (chunk !== null) {
                yield chunk;
            } else if (error) {
                throw error;
            } else if (error === null) {
                return;
            } else {
                await new Promise(next);
            }
        }
    } catch (err) {
        if (opts.destroyOnError) {
            destroyImpl.destroyer(stream, err);
        }
        error = aggregateTwoErrors(error, err);
        throw error;
    } finally {
        if (error === undefined && opts.destroyOnReturn) {
            const state = stream._readableState;
            if (state.autoDestroy || !state.endEmitted) {
                destroyImpl.destroyer(stream, null);
            }
        }
        stream.off("readable", next);
        cleanup();
    }
}

// Making it explicit these properties are not enumerable
// because otherwise some prototype manipulation in
// userland will fail.
Object.defineProperties(Readable.prototype, {
    readable: {
        get() {
            const r = this._readableState;
            // r.readable === false means that this is part of a Duplex stream
            // where the readable side was disabled upon construction.
            // Compat. The user might manually disable readable side through
            // deprecated setter.
            return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted &&
                !r.endEmitted;
        },
        set(val) {
            // Backwards compat.
            if (this._readableState) {
                this._readableState.readable = !!val;
            }
        },
    },

    readableDidRead: {
        enumerable: false,
        get: function () {
            return this._readableState.dataEmitted;
        },
    },

    readableAborted: {
        enumerable: false,
        get: function () {
            return !!(this._readableState.destroyed || this._readableState.errored) &&
                !this._readableState.endEmitted;
        },
    },

    readableHighWaterMark: {
        enumerable: false,
        get: function () {
            return this._readableState.highWaterMark;
        },
    },

    readableBuffer: {
        enumerable: false,
        get: function () {
            return this._readableState && this._readableState.buffer;
        },
    },

    readableFlowing: {
        enumerable: false,
        get: function () {
            return this._readableState.flowing;
        },
        set: function (state) {
            if (this._readableState) {
                this._readableState.flowing = state;
            }
        },
    },

    readableLength: {
        enumerable: false,
        get() {
            return this._readableState.length;
        },
    },

    readableObjectMode: {
        enumerable: false,
        get() {
            return this._readableState ? this._readableState.objectMode : false;
        },
    },

    readableEncoding: {
        enumerable: false,
        get() {
            return this._readableState ? this._readableState.encoding : null;
        },
    },

    destroyed: {
        enumerable: false,
        get() {
            if (this._readableState === undefined) {
                return false;
            }
            return this._readableState.destroyed;
        },
        set(value) {
            // We ignore the value if the stream
            // has not been initialized yet.
            if (!this._readableState) {
                return;
            }

            // Backward compatibility, the user is explicitly
            // managing destroyed.
            this._readableState.destroyed = value;
        },
    },

    readableEnded: {
        enumerable: false,
        get() {
            return this._readableState ? this._readableState.endEmitted : false;
        },
    },

    errored: {
        enumerable: false,
        get() {
            return this._readableState ? this._readableState.errored : null;
        },
    },

    closed: {
        get() {
            return this._readableState ? this._readableState.closed : false;
        },
    },
});

Object.defineProperties(ReadableState.prototype, {
    // Legacy getter for `pipesCount`.
    pipesCount: {
        get() {
            return this.pipes.length;
        },
    },

    // Legacy property for `paused`.
    paused: {
        get() {
            return this[kPaused] !== false;
        },
        set(value) {
            this[kPaused] = !!value;
        },
    },
});

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
    // nothing buffered.
    if (state.length === 0) {
        return null;
    }

    let ret;
    if (state.objectMode) {
        ret = state.buffer.shift();
    } else if (!n || n >= state.length) {
        // Read it all, truncate the list.
        if (state.decoder) {
            ret = state.buffer.join("");
        } else if (state.buffer.length === 1) {
            ret = state.buffer.first();
        } else {
            ret = state.buffer.concat(state.length);
        }
        state.buffer.clear();
    } else {
        // read part of list.
        ret = state.buffer.consume(n, state.decoder);
    }

    return ret;
}

function endReadable(stream) {
    const state = stream._readableState;

    debug("endReadable", state.endEmitted);
    if (!state.endEmitted) {
        state.ended = true;
        nextTick(endReadableNT, state, stream);
    }
}

function endReadableNT(state, stream) {
    debug("endReadableNT", state.endEmitted, state.length);

    // Check that we didn't get one last unshift.
    if (
        !state.errorEmitted && !state.closeEmitted &&
        !state.endEmitted && state.length === 0
    ) {
        state.endEmitted = true;
        stream.emit("end");

        if (stream.writable && stream.allowHalfOpen === false) {
            nextTick(endWritableNT, stream);
        } else if (state.autoDestroy) {
            // In case of duplex streams we need a way to detect
            // if the writable side is ready for autoDestroy as well.
            const wState = stream._writableState;
            const autoDestroy = !wState || (
                wState.autoDestroy &&
                // We don't expect the writable to ever 'finish'
                // if writable is explicitly set to false.
                (wState.finished || wState.writable === false)
            );

            if (autoDestroy) {
                stream.destroy();
            }
        }
    }
}

function endWritableNT(stream) {
    const writable = stream.writable && !stream.writableEnded &&
        !stream.destroyed;
    if (writable) {
        stream.end();
    }
}

function readableFrom(iterable, opts) {
    return _from(Readable, iterable, opts);
}

function wrap(src, options) {
    return new Readable({
        objectMode: src.readableObjectMode ?? src.objectMode ?? true,
        ...options,
        destroy(err, callback) {
            destroyImpl.destroyer(src, err);
            callback(err);
        },
    }).wrap(src);
}

function newStreamReadableFromReadableStream(readableStream, options = {}) {
    if (!(readableStream instanceof ReadableStream)) {
        throw new ERR_INVALID_ARG_TYPE(
            'readableStream',
            'ReadableStream',
            readableStream);
    }

    validateObject(options, 'options');
    const {
        highWaterMark,
        encoding,
        objectMode = false,
        signal,
    } = options;

    if (encoding !== undefined && !Buffer.isEncoding(encoding))
        throw new ERR_INVALID_ARG_VALUE('options.encoding', encoding);
    validateBoolean(objectMode, 'options.objectMode');

    const reader = readableStream.getReader();
    let closed = false;

    const readable = new Readable({
        objectMode,
        highWaterMark,
        encoding,
        signal,

        read() {
            reader.read().then(
                (chunk) => {
                    if (chunk.done) {
                        readable.push(null);
                    } else {
                        readable.push(chunk.value);
                    }
                },
                (error) => destroyImpl.destroyer(readable, error));
        },

        destroy(error, callback) {
            function done() {
                try {
                    callback(error);
                } catch (error) {
                    nextTick(() => { throw error; });
                }
            }

            if (!closed) {
                reader.cancel(error).then(done, done);
                return;
            }
            done();
        },
    });

    reader.closed.then(
        () => {
            closed = true;
        },
        (error) => {
            closed = true;
            destroyImpl.destroyer(readable, error);
        });

    return readable;
}


function newReadableStreamFromStreamReadable(streamReadable, options = {}) {
    if (typeof streamReadable?._readableState !== 'object') {
        throw new ERR_INVALID_ARG_TYPE(
            'streamReadable',
            'stream.Readable',
            streamReadable);
    }

    if (isDestroyed(streamReadable) || !isReadable(streamReadable)) {
        const readable = new ReadableStream();
        readable.cancel();
        return readable;
    }

    const objectMode = streamReadable.readableObjectMode;
    const highWaterMark = streamReadable.readableHighWaterMark;

    const strategy = objectMode
        ? new CountQueuingStrategy({ highWaterMark })
        : { highWaterMark };

    let controller;
    let wasCanceled = false;

    function onData(chunk) {
        if (Buffer.isBuffer(chunk) && !objectMode)
            chunk = new Uint8Array(chunk);
        controller.enqueue(chunk);
        if (controller.desiredSize <= 0)
            streamReadable.pause();
    }

    streamReadable.pause();

    const cleanup = eos(streamReadable, (error) => {
        cleanup();
        streamReadable.on('error', () => {});
        if (error)
            return controller.error(error);
        if (wasCanceled) {
            return;
        }
        controller.close();
    });

    streamReadable.on('data', onData);

    return new ReadableStream({
        start(c) { controller = c; },

        pull() { streamReadable.resume(); },

        cancel(reason) {
            wasCanceled = true;
            destroyImpl.destroyer(streamReadable, reason);
        },
    }, strategy);
}

// --- Readable helper methods (Node.js stream.Readable iterator helpers) ---

function throwIfAborted(signal) {
    if (signal?.aborted) throw new AbortError(signal.reason);
}

function validateConcurrency(options) {
    let concurrency = 1;
    if (options?.concurrency != null) {
        concurrency = Math.floor(options.concurrency);
    }
    validateInteger(concurrency, 'options.concurrency', 1);
    return concurrency;
}

Readable.prototype.map = function map(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    let outHWM = concurrency - 1;
    if (options?.highWaterMark != null) {
        outHWM = Math.floor(options.highWaterMark);
    }
    validateInteger(outHWM, 'options.highWaterMark', 0);
    const queueHWM = outHWM + concurrency;
    const src = this;

    return readableFrom((async function* () {
        throwIfAborted(signal);

        const ac = new AbortController();
        let cleanupSignal;
        if (signal) {
            const onAbort = () => { ac.abort(signal.reason); };
            if (signal.aborted) { ac.abort(signal.reason); }
            else {
                signal.addEventListener('abort', onAbort, { once: true });
                cleanupSignal = () => signal.removeEventListener('abort', onAbort);
            }
        }
        const combinedSignal = ac.signal;

        try {
            const queue = [];
            let sourceDone = false;
            let inFlight = 0;
            let errorOccurred = null;
            let resolveNext = null;
            let pumpScheduled = false;
            let pumping = false;
            let repumpRequested = false;

            const it = src[Symbol.asyncIterator]();

            function onSlotReady() {
                if (resolveNext) {
                    const r = resolveNext;
                    resolveNext = null;
                    r();
                }
            }

            function schedulePump() {
                if (pumping) {
                    repumpRequested = true;
                    return;
                }

                if (!pumpScheduled) {
                    pumpScheduled = true;
                    Promise.resolve().then(() => {
                        pumpScheduled = false;
                        pump();
                    });
                }
            }

            async function pump() {
                if (pumping) {
                    repumpRequested = true;
                    return;
                }

                pumping = true;
                try {
                    while (!sourceDone && !combinedSignal.aborted && !errorOccurred && inFlight < concurrency && queue.length < queueHWM) {
                        let step;
                        try {
                            step = await it.next();
                        } catch (e) {
                            errorOccurred = e;
                            onSlotReady();
                            return;
                        }

                        if (step.done) {
                            sourceDone = true;
                            onSlotReady();
                            return;
                        }

                        const slot = { resolved: false, value: undefined, error: null };
                        queue.push(slot);
                        inFlight++;
                        const chunk = step.value;

                        let mapped;
                        try {
                            if (combinedSignal.aborted) throw new AbortError(combinedSignal.reason);
                            mapped = Promise.resolve(fn(chunk, { signal: combinedSignal }));
                        } catch (e) {
                            mapped = Promise.reject(e);
                        }

                        mapped.then(
                            (result) => {
                                slot.value = result;
                            },
                            (e) => {
                                slot.error = e;
                                if (!errorOccurred) errorOccurred = e;
                            },
                        ).finally(() => {
                            slot.resolved = true;
                            inFlight--;
                            onSlotReady();
                            schedulePump();
                        });
                    }
                } finally {
                    pumping = false;
                    if (repumpRequested) {
                        repumpRequested = false;
                        schedulePump();
                    }
                }
            }

            schedulePump();

            while (true) {
                while (queue.length === 0 || !queue[0].resolved) {
                    if (errorOccurred) throw errorOccurred;
                    if (sourceDone && queue.length === 0) return;
                    if (combinedSignal.aborted) throw new AbortError(combinedSignal.reason);
                    await new Promise((r) => { resolveNext = r; });
                }

                const slot = queue.shift();
                if (slot.error) throw slot.error;
                yield slot.value;
                schedulePump();
            }
        } finally {
            if (cleanupSignal) cleanupSignal();
        }
    })(), { objectMode: true });
};

Readable.prototype.filter = function filter(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    const hwm = options?.highWaterMark;
    const outHWM = hwm != null ? hwm : concurrency - 1;
    const src = this;

    return readableFrom((async function* () {
        throwIfAborted(signal);

        const ac = new AbortController();
        let cleanupSignal;
        if (signal) {
            const onAbort = () => { ac.abort(signal.reason); };
            if (signal.aborted) { ac.abort(signal.reason); }
            else {
                signal.addEventListener('abort', onAbort, { once: true });
                cleanupSignal = () => signal.removeEventListener('abort', onAbort);
            }
        }
        const combinedSignal = ac.signal;

        try {
            const queue = [];
            let sourceDone = false;
            let inFlight = 0;
            let errorOccurred = null;
            let resolveNext = null;
            let pumpScheduled = false;

            const it = src[Symbol.asyncIterator]();

            function onSlotReady() {
                if (resolveNext) {
                    const r = resolveNext;
                    resolveNext = null;
                    r();
                }
            }

            function schedulePump() {
                if (!pumpScheduled) {
                    pumpScheduled = true;
                    Promise.resolve().then(() => {
                        pumpScheduled = false;
                        pump();
                    });
                }
            }

            async function pump() {
                while (!sourceDone && !ac.signal.aborted && !errorOccurred && inFlight < concurrency && queue.length < concurrency + outHWM) {
                    let step;
                    try {
                        step = await it.next();
                    } catch (e) {
                        errorOccurred = e;
                        onSlotReady();
                        return;
                    }

                    if (step.done) {
                        sourceDone = true;
                        onSlotReady();
                        return;
                    }

                    const slot = { resolved: false, include: false, chunk: step.value, error: null };
                    queue.push(slot);
                    inFlight++;
                    const chunk = step.value;

                    Promise.resolve().then(async () => {
                        try {
                            if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                            const result = await fn(chunk, { signal: combinedSignal });
                            slot.include = !!result;
                        } catch (e) {
                            slot.error = e;
                            if (!errorOccurred) errorOccurred = e;
                        } finally {
                            slot.resolved = true;
                            inFlight--;
                            onSlotReady();
                            schedulePump();
                        }
                    });
                }
            }

            pump();

            while (true) {
                while (queue.length === 0 || !queue[0].resolved) {
                    if (errorOccurred) throw errorOccurred;
                    if (sourceDone && queue.length === 0) return;
                    if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                    await new Promise(r => { resolveNext = r; });
                }

                const slot = queue.shift();
                if (slot.error) throw slot.error;
                if (slot.include) yield slot.chunk;
                schedulePump();
            }
        } finally {
            if (cleanupSignal) cleanupSignal();
        }
    })(), { objectMode: true, highWaterMark: outHWM });
};

Readable.prototype.flatMap = function flatMap(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    const hwm = options?.highWaterMark;
    const outHWM = hwm != null ? hwm : concurrency - 1;
    const src = this;

    return readableFrom((async function* () {
        throwIfAborted(signal);

        const ac = new AbortController();
        let cleanupSignal;
        if (signal) {
            const onAbort = () => { ac.abort(signal.reason); };
            if (signal.aborted) { ac.abort(signal.reason); }
            else {
                signal.addEventListener('abort', onAbort, { once: true });
                cleanupSignal = () => signal.removeEventListener('abort', onAbort);
            }
        }
        const combinedSignal = ac.signal;

        try {
            const queue = [];
            let sourceDone = false;
            let inFlight = 0;
            let errorOccurred = null;
            let resolveNext = null;
            let pumpScheduled = false;

            const it = src[Symbol.asyncIterator]();

            function onSlotReady() {
                if (resolveNext) {
                    const r = resolveNext;
                    resolveNext = null;
                    r();
                }
            }

            function schedulePump() {
                if (!pumpScheduled) {
                    pumpScheduled = true;
                    Promise.resolve().then(() => {
                        pumpScheduled = false;
                        pump();
                    });
                }
            }

            async function pump() {
                while (!sourceDone && !ac.signal.aborted && !errorOccurred && inFlight < concurrency && queue.length < concurrency + outHWM) {
                    let step;
                    try {
                        step = await it.next();
                    } catch (e) {
                        errorOccurred = e;
                        onSlotReady();
                        return;
                    }

                    if (step.done) {
                        sourceDone = true;
                        onSlotReady();
                        return;
                    }

                    const slot = { resolved: false, value: undefined, error: null };
                    queue.push(slot);
                    inFlight++;
                    const chunk = step.value;

                    Promise.resolve().then(async () => {
                        try {
                            if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                            const result = await fn(chunk, { signal: combinedSignal });
                            slot.value = result;
                        } catch (e) {
                            slot.error = e;
                            if (!errorOccurred) errorOccurred = e;
                        } finally {
                            slot.resolved = true;
                            inFlight--;
                            onSlotReady();
                            schedulePump();
                        }
                    });
                }
            }

            pump();

            while (true) {
                while (queue.length === 0 || !queue[0].resolved) {
                    if (errorOccurred) throw errorOccurred;
                    if (sourceDone && queue.length === 0) return;
                    if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                    await new Promise(r => { resolveNext = r; });
                }

                const slot = queue.shift();
                if (slot.error) throw slot.error;
                const out = slot.value;
                if (out && typeof out[Symbol.asyncIterator] === 'function') {
                    yield* out;
                } else if (out && typeof out[Symbol.iterator] === 'function') {
                    yield* out;
                } else {
                    yield out;
                }
                schedulePump();
            }
        } finally {
            if (cleanupSignal) cleanupSignal();
        }
    })(), { objectMode: true, highWaterMark: outHWM });
};

Readable.prototype.take = function take(n, options) {
    n = +n;
    if (n < 0 || n === -Infinity) {
        throw new ERR_OUT_OF_RANGE('number', '>= 0', n);
    }
    if (Number.isNaN(n)) n = 0;
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const signal = options?.signal;
    const src = this;

    return readableFrom((async function* () {
        throwIfAborted(signal);
        let i = 0;
        for await (const chunk of src) {
            throwIfAborted(signal);
            if (i++ >= n) break;
            yield chunk;
        }
    })(), { objectMode: true });
};

Readable.prototype.drop = function drop(n, options) {
    n = +n;
    if (n < 0 || n === -Infinity) {
        throw new ERR_OUT_OF_RANGE('number', '>= 0', n);
    }
    if (Number.isNaN(n)) n = 0;
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const signal = options?.signal;
    const src = this;

    return readableFrom((async function* () {
        throwIfAborted(signal);
        let i = 0;
        for await (const chunk of src) {
            throwIfAborted(signal);
            if (i++ < n) continue;
            yield chunk;
        }
    })(), { objectMode: true });
};

Readable.prototype.toArray = async function toArray(options) {
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const signal = options?.signal;
    throwIfAborted(signal);
    const out = [];
    for await (const chunk of this) {
        throwIfAborted(signal);
        out.push(chunk);
    }
    return out;
};

Readable.prototype.forEach = async function forEach(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    const src = this;

    const ac = new AbortController();
    let cleanupSignal;
    if (signal) {
        const onAbort = () => { ac.abort(signal.reason); };
        if (signal.aborted) { ac.abort(signal.reason); }
        else {
            signal.addEventListener('abort', onAbort, { once: true });
            cleanupSignal = () => signal.removeEventListener('abort', onAbort);
        }
    }
    const combinedSignal = ac.signal;

    try {
        throwIfAborted(signal);
        const queue = [];
        let sourceDone = false;
        let inFlight = 0;
        let errorOccurred = null;
        let resolveNext = null;
        let pumpScheduled = false;

        const it = src[Symbol.asyncIterator]();

        function onSlotReady() {
            if (resolveNext) {
                const r = resolveNext;
                resolveNext = null;
                r();
            }
        }

        function schedulePump() {
            if (!pumpScheduled) {
                pumpScheduled = true;
                Promise.resolve().then(() => {
                    pumpScheduled = false;
                    pump();
                });
            }
        }

        async function pump() {
            while (!sourceDone && !ac.signal.aborted && !errorOccurred && inFlight < concurrency && queue.length < concurrency) {
                let step;
                try {
                    step = await it.next();
                } catch (e) {
                    errorOccurred = e;
                    onSlotReady();
                    return;
                }

                if (step.done) {
                    sourceDone = true;
                    onSlotReady();
                    return;
                }

                const slot = { resolved: false, error: null };
                queue.push(slot);
                inFlight++;
                const chunk = step.value;

                Promise.resolve().then(async () => {
                    try {
                        if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                        await fn(chunk, { signal: combinedSignal });
                    } catch (e) {
                        slot.error = e;
                        if (!errorOccurred) errorOccurred = e;
                    } finally {
                        slot.resolved = true;
                        inFlight--;
                        onSlotReady();
                        schedulePump();
                    }
                });
            }
        }

        pump();

        while (true) {
            while (queue.length === 0 || !queue[0].resolved) {
                if (errorOccurred) throw errorOccurred;
                if (sourceDone && queue.length === 0) return;
                if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                await new Promise(r => { resolveNext = r; });
            }

            const slot = queue.shift();
            if (slot.error) throw slot.error;
            schedulePump();
        }
    } finally {
        if (cleanupSignal) cleanupSignal();
    }
};

Readable.prototype.reduce = async function reduce(fn, initialValue, options) {
    if (typeof fn !== 'function') {
        throw new TypeError('fn must be a function');
    }
    const hasInitial = arguments.length >= 2;
    if (typeof arguments[arguments.length - 1] === 'object' && arguments[arguments.length - 1] !== null) {
        options = arguments[arguments.length - 1];
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const signal = options?.signal;

    if (signal?.aborted) {
        this.destroy();
        throw new AbortError(signal.reason);
    }

    let acc;
    let started = hasInitial;
    if (started) acc = initialValue;

    let cleanupSignal;
    if (signal) {
        const onAbort = () => {
            this.destroy();
        };
        signal.addEventListener('abort', onAbort, { once: true });
        cleanupSignal = () => signal.removeEventListener('abort', onAbort);
    }

    try {
        for await (const chunk of this) {
            throwIfAborted(signal);
            if (!started) {
                acc = chunk;
                started = true;
                continue;
            }
            acc = await fn(acc, chunk, { signal });
        }
        throwIfAborted(signal);
    } finally {
        if (cleanupSignal) cleanupSignal();
    }

    if (!started) throw new TypeError('Reduce of empty stream with no initial value');
    return acc;
};

Readable.prototype.some = async function some(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    const src = this;

    const ac = new AbortController();
    let cleanupSignal;
    if (signal) {
        const onAbort = () => { ac.abort(signal.reason); };
        if (signal.aborted) { ac.abort(signal.reason); }
        else {
            signal.addEventListener('abort', onAbort, { once: true });
            cleanupSignal = () => signal.removeEventListener('abort', onAbort);
        }
    }
    const combinedSignal = ac.signal;

    try {
        throwIfAborted(signal);
        let found = false;
        const queue = [];
        let sourceDone = false;
        let inFlight = 0;
        let errorOccurred = null;
        let resolveNext = null;
        let pumpScheduled = false;

        const it = src[Symbol.asyncIterator]();

        function onSlotReady() {
            if (resolveNext) {
                const r = resolveNext;
                resolveNext = null;
                r();
            }
        }

        function schedulePump() {
            if (!pumpScheduled) {
                pumpScheduled = true;
                Promise.resolve().then(() => {
                    pumpScheduled = false;
                    pump();
                });
            }
        }

        async function pump() {
            while (!sourceDone && !found && !ac.signal.aborted && !errorOccurred && inFlight < concurrency) {
                let step;
                try {
                    step = await it.next();
                } catch (e) {
                    errorOccurred = e;
                    onSlotReady();
                    return;
                }

                if (step.done) {
                    sourceDone = true;
                    onSlotReady();
                    return;
                }

                const slot = { resolved: false, result: false, error: null };
                queue.push(slot);
                inFlight++;
                const chunk = step.value;

                Promise.resolve().then(async () => {
                    try {
                        if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                        slot.result = !!(await fn(chunk, { signal: combinedSignal }));
                        if (slot.result) found = true;
                    } catch (e) {
                        slot.error = e;
                        if (!errorOccurred) errorOccurred = e;
                    } finally {
                        slot.resolved = true;
                        inFlight--;
                        onSlotReady();
                        if (!found) schedulePump();
                    }
                });
            }
        }

        pump();

        while (true) {
            while (queue.length === 0 || !queue[0].resolved) {
                if (errorOccurred) throw errorOccurred;
                if (sourceDone && queue.length === 0) return false;
                if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                await new Promise(r => { resolveNext = r; });
            }

            const slot = queue.shift();
            if (slot.error) throw slot.error;
            if (slot.result) return true;
            schedulePump();
        }
    } finally {
        if (cleanupSignal) cleanupSignal();
    }
};

Readable.prototype.every = async function every(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    const src = this;

    const ac = new AbortController();
    let cleanupSignal;
    if (signal) {
        const onAbort = () => { ac.abort(signal.reason); };
        if (signal.aborted) { ac.abort(signal.reason); }
        else {
            signal.addEventListener('abort', onAbort, { once: true });
            cleanupSignal = () => signal.removeEventListener('abort', onAbort);
        }
    }
    const combinedSignal = ac.signal;

    try {
        throwIfAborted(signal);
        let failed = false;
        const queue = [];
        let sourceDone = false;
        let inFlight = 0;
        let errorOccurred = null;
        let resolveNext = null;
        let pumpScheduled = false;

        const it = src[Symbol.asyncIterator]();

        function onSlotReady() {
            if (resolveNext) {
                const r = resolveNext;
                resolveNext = null;
                r();
            }
        }

        function schedulePump() {
            if (!pumpScheduled) {
                pumpScheduled = true;
                Promise.resolve().then(() => {
                    pumpScheduled = false;
                    pump();
                });
            }
        }

        async function pump() {
            while (!sourceDone && !failed && !ac.signal.aborted && !errorOccurred && inFlight < concurrency) {
                let step;
                try {
                    step = await it.next();
                } catch (e) {
                    errorOccurred = e;
                    onSlotReady();
                    return;
                }

                if (step.done) {
                    sourceDone = true;
                    onSlotReady();
                    return;
                }

                const slot = { resolved: false, result: true, error: null };
                queue.push(slot);
                inFlight++;
                const chunk = step.value;

                Promise.resolve().then(async () => {
                    try {
                        if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                        slot.result = !!(await fn(chunk, { signal: combinedSignal }));
                        if (!slot.result) failed = true;
                    } catch (e) {
                        slot.error = e;
                        if (!errorOccurred) errorOccurred = e;
                    } finally {
                        slot.resolved = true;
                        inFlight--;
                        onSlotReady();
                        if (!failed) schedulePump();
                    }
                });
            }
        }

        pump();

        while (true) {
            while (queue.length === 0 || !queue[0].resolved) {
                if (errorOccurred) throw errorOccurred;
                if (sourceDone && queue.length === 0) return true;
                if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                await new Promise(r => { resolveNext = r; });
            }

            const slot = queue.shift();
            if (slot.error) throw slot.error;
            if (!slot.result) return false;
            schedulePump();
        }
    } finally {
        if (cleanupSignal) cleanupSignal();
    }
};

Readable.prototype.find = async function find(fn, options) {
    if (typeof fn !== 'function') {
        throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn);
    }
    if (options != null) validateObject(options, 'options');
    if (options?.signal != null) validateAbortSignal(options.signal, 'options.signal');
    const concurrency = validateConcurrency(options);
    const signal = options?.signal;
    const src = this;

    const ac = new AbortController();
    let cleanupSignal;
    if (signal) {
        const onAbort = () => { ac.abort(signal.reason); };
        if (signal.aborted) { ac.abort(signal.reason); }
        else {
            signal.addEventListener('abort', onAbort, { once: true });
            cleanupSignal = () => signal.removeEventListener('abort', onAbort);
        }
    }
    const combinedSignal = ac.signal;

    try {
        throwIfAborted(signal);
        let found = false;
        let foundChunk;
        const queue = [];
        let sourceDone = false;
        let inFlight = 0;
        let errorOccurred = null;
        let resolveNext = null;
        let pumpScheduled = false;

        const it = src[Symbol.asyncIterator]();

        function onSlotReady() {
            if (resolveNext) {
                const r = resolveNext;
                resolveNext = null;
                r();
            }
        }

        function schedulePump() {
            if (!pumpScheduled) {
                pumpScheduled = true;
                Promise.resolve().then(() => {
                    pumpScheduled = false;
                    pump();
                });
            }
        }

        async function pump() {
            while (!sourceDone && !found && !ac.signal.aborted && !errorOccurred && inFlight < concurrency) {
                let step;
                try {
                    step = await it.next();
                } catch (e) {
                    errorOccurred = e;
                    onSlotReady();
                    return;
                }

                if (step.done) {
                    sourceDone = true;
                    onSlotReady();
                    return;
                }

                const slot = { resolved: false, matched: false, chunk: step.value, error: null };
                queue.push(slot);
                inFlight++;
                const chunk = step.value;

                Promise.resolve().then(async () => {
                    try {
                        if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                        slot.matched = !!(await fn(chunk, { signal: combinedSignal }));
                        if (slot.matched) found = true;
                    } catch (e) {
                        slot.error = e;
                        if (!errorOccurred) errorOccurred = e;
                    } finally {
                        slot.resolved = true;
                        inFlight--;
                        onSlotReady();
                        if (!found) schedulePump();
                    }
                });
            }
        }

        pump();

        while (true) {
            while (queue.length === 0 || !queue[0].resolved) {
                if (errorOccurred) throw errorOccurred;
                if (sourceDone && queue.length === 0) return undefined;
                if (ac.signal.aborted) throw new AbortError(ac.signal.reason);
                await new Promise(r => { resolveNext = r; });
            }

            const slot = queue.shift();
            if (slot.error) throw slot.error;
            if (slot.matched) return slot.chunk;
            schedulePump();
        }
    } finally {
        if (cleanupSignal) cleanupSignal();
    }
};

// Readable.prototype.compose is set in stream.js to avoid circular dependency

// --- Symbol.asyncDispose support ---

if (typeof Symbol.asyncDispose !== 'undefined') {
    Readable.prototype[Symbol.asyncDispose] = async function() {
        let error;
        if (!this.destroyed) {
            error = this.readableEnded ? null : new AbortError();
            this.destroy(error);
        }
        await new Promise((resolve, reject) =>
            eos(this, (err) => (err && err.name !== 'AbortError' ? reject(err) : resolve(null))),
        );
    };
}

// Exposed for testing purposes only.
Readable._fromList = fromList;
Readable.ReadableState = ReadableState;
Readable.from = readableFrom;
Readable.wrap = wrap;

Readable.fromWeb = function(readableStream, options) {
    return newStreamReadableFromReadableStream(readableStream, options);
};

Readable.toWeb = function(streamReadable, options) {
    return newReadableStreamFromStreamReadable(streamReadable, options);
};

export default Readable;
export { fromList as _fromList, readableFrom as from, ReadableState, wrap, newStreamReadableFromReadableStream as fromWeb, newReadableStreamFromStreamReadable as toWeb };