rete-wasm 0.7.4

Browser/WASM bindings for querying Rete graph files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
//! Browser bindings: load a `.rete` file's bytes (e.g. from `fetch`) and query
//! it entirely in the browser — the same engine the native CLI uses, compiled
//! to wasm. Results come back as JSON strings.

use rete_core::{
    batch_reach_serial, build_adjacency, build_dendrogram, choose_round_for_budget, eval_query,
    eval_query_with_warnings, eval_select_communities, eval_sparql, project_graph, schema_classes,
    schema_summary, summary_query_shape, tile_by_community, validate_shacl, BlockCacheReader,
    ByteRange, CountingReader, DataGraph, Header, OffsetReader, QueryOpts, QueryOutput,
    RangeReader, Rete, ReteGraph, ShaclShapes, SliceReader, SummaryQueryShape, SummaryView,
    TermTriple, TripleProvenance, ValidationReport, DEFAULT_BLOCK, DEFAULT_TILE_BUDGET,
};
use std::rc::Rc;
use wasm_bindgen::prelude::*;

/// Version of Rete-owned JSON object envelopes exposed by the browser API.
pub const JSON_SCHEMA_VERSION: u8 = 1;

/// Module init: route Rust panics to `console.error` with their message and
/// location. In release wasm a panic otherwise aborts as a bare
/// `RuntimeError: unreachable` with no clue where — this turns that into a
/// `rete-wasm panic: panicked at '…', src/…:line` line in the devtools console,
/// so an intermittent first-query crash (e.g. a parser tripping on a flaky
/// range read) can actually be diagnosed.
#[wasm_bindgen(start)]
pub fn __start() {
    // The asyncify build must NOT format in the panic hook: the fmt machinery
    // is asyncify-instrumented (everything that can reach panic_fmt is), so a
    // panic raised while the instance is unwinding/rewinding recurses through
    // garbage-returning fmt calls forever (stack overflow / null-function).
    // Report the raw location pointers through a LEAF import instead — no
    // formatting, no instrumented calls — then let panic=abort trap cleanly.
    #[cfg(feature = "asyncify")]
    std::panic::set_hook(Box::new(|info| {
        if let Some(loc) = info.location() {
            let f = loc.file();
            unsafe { rete_panic_report(f.as_ptr(), f.len(), loc.line()) };
        } else {
            unsafe { rete_panic_report(std::ptr::null(), 0, 0) };
        }
    }));
    #[cfg(not(feature = "asyncify"))]
    std::panic::set_hook(Box::new(|info| {
        web_sys::console::error_1(&JsValue::from_str(&format!("rete-wasm panic: {info}")));
    }));
}

/// Header summary as JSON: `{ "quads": N, "terms": N, "pyramidLevels": N }`.
#[wasm_bindgen]
pub fn info(bytes: &[u8]) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let h = rete.header();
    Ok(format!(
        r#"{{"schemaVersion":1,"quads":{},"terms":{},"pyramidLevels":{},"namedGraphs":{}}}"#,
        h.quad_count,
        h.term_count,
        h.pyramid_levels,
        rete.named_graph_count()
    ))
}

/// The named-graph IRIs of a dataset, as a JSON array.
#[wasm_bindgen]
pub fn graph_names(bytes: &[u8]) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    serde_json::to_string(&rete.graph_names()).map_err(err)
}

/// Build a complete `.rete` file image from RDF text, entirely in the browser.
///
/// `format` is `"nt"` (N-Triples), `"nq"` (N-Quads; named graphs become a
/// dataset), or `"ttl"` (Turtle). Returns the file bytes (a `Uint8Array`),
/// ready to download or to hand straight back to the query functions. The wasm
/// build has no zstd *encoder*, so sections are written uncompressed (codec
/// `NONE`) — larger than a CLI build of the same data, but every reader
/// accepts it; rebuild with `rete build` for a compressed file.
#[wasm_bindgen]
pub fn build(text: &str, format: &str) -> Result<Vec<u8>, JsValue> {
    let quads = rete_core::ingest::parse_statements(text, format).map_err(err)?;
    if quads.is_empty() {
        return Err(js_error(
            "no statements parsed (empty input or only comments)",
        ));
    }
    let read = quads.len() as u64;
    let (bytes, stats) = rete_core::ingest::assemble_dataset_quad(quads, &[]);
    finish_build(
        bytes,
        "build",
        format,
        ("string", text.as_bytes()),
        &stats,
        read,
    )
}

/// The file every browser build returns: the in-RAM `0x05` image laid out as
/// `0x06` (the one step the CLI and every binding share,
/// [`rete_core::build_record::finish_in_ram`]), with the build record beside
/// the card: engine, options, the input (name, length, BLAKE3), counts, and
/// `front_end: "wasm"`. The browser's clock is the only one there is, so the
/// timestamp comes from it.
fn finish_build(
    bytes: Vec<u8>,
    command: &str,
    format: &str,
    input: (&str, &[u8]),
    stats: &rete_core::ingest::BuildStats,
    read: u64,
) -> Result<Vec<u8>, JsValue> {
    use rete_core::build_record as br;
    let built_at = js_sys::Date::new_0()
        .to_iso_string()
        .as_string()
        .filter(|s| s.len() >= 19)
        .map(|s| format!("{}Z", &s[..19]));
    let record = br::to_json(
        &br::Record {
            front_end: br::front_end::WASM.into(),
            front_end_version: env!("CARGO_PKG_VERSION").into(),
            built_at,
            options: br::Options {
                command: command.into(),
                format: Some(format.into()),
                pyramid_algo: Some("louvain".into()),
                ..Default::default()
            },
            inputs: vec![br::Input::from_bytes(input.0, format, input.1)],
            statements_read: Some(read),
        },
        Some(stats),
    );
    br::finish_in_ram(bytes, Some(&record)).map_err(err)
}

/// [`build`], but the file carries a **Dataset Card** written from
/// `card_json` — the same document `rete build --card-file` takes, validated
/// by the same rules ([`rete_core::card::validate_curated_card`]), so a card
/// authored in the browser is one the CLI would also have accepted.
///
/// What the browser can and cannot put in a card, stated plainly because the
/// difference matters to whoever reads the file afterwards:
///
/// - **Curated fields travel in full** — title, description, licence, source,
///   version, creators, publisher, DOI, citation, keywords, theme, the `extra`
///   bag, everything on [`rete_core::card::CURATED_CARD_FIELDS`].
/// - **The four counts are measured, not asserted**: `triple_count`,
///   `quad_count`, `named_graph_count` and `term_count` come from the build's
///   own [`BuildStats`](rete_core::ingest::BuildStats), and any values supplied
///   for them would be ignored (they are not curated fields, so supplying them
///   is already an error). `format_version` is stamped by the writer.
/// - **The derived profile is NOT written.** Predicates, classes,
///   vocabularies, datatypes, languages, class links, hubs, signals and the
///   tiered starter-query library are absent. Their absence is honest absence:
///   the card simply does not carry those keys, exactly as a `rete merge` card
///   does not. Call [`build_with_derived_card`] instead to compute them here —
///   this function stays curated-only so its bytes never change under a caller
///   who did not ask for the extra passes.
/// - **No build-info section** (kind 7) is written: its cost figures come from
///   measuring the starter queries, and there are none to measure.
///
/// Pass an empty string for no card — byte-identical to [`build`].
#[wasm_bindgen]
pub fn build_with_card(text: &str, format: &str, card_json: &str) -> Result<Vec<u8>, JsValue> {
    build_card_surface(
        text,
        format,
        card_json,
        rete_core::ingest::QuotedTripleSurface::default(),
    )
}

/// [`build_with_card`], reading Turtle/TriG `<< … >>` in the named surface —
/// the browser half of `rete build --quoted-triple-syntax`, same two values:
///
/// - `"rdf-star"` (or `""`): `<< s p o >>` is a quoted triple. Byte-identical
///   to [`build_with_card`].
/// - `"rdf12"`: the **RDF 1.2** reader. `<<( s p o )>>` is a triple term,
///   `<< s p o >>` a reifier (a blank node `rdf:reifies` the triple term),
///   `{| … |}` an annotation, `"…"@lang--dir` a directional literal.
///
/// The same Turtle file is two different graphs under the two values, and
/// nothing in the bytes says which was meant, so the caller chooses. N-Triples
/// and N-Quads ignore the choice (their reader takes both spellings). Anything
/// else is refused by name.
#[wasm_bindgen]
pub fn build_with_card_syntax(
    text: &str,
    format: &str,
    card_json: &str,
    quoted_triple_syntax: &str,
) -> Result<Vec<u8>, JsValue> {
    let surface = if quoted_triple_syntax.is_empty() {
        rete_core::ingest::QuotedTripleSurface::default()
    } else {
        rete_core::ingest::QuotedTripleSurface::parse(quoted_triple_syntax).ok_or_else(|| {
            js_error(format!(
                "unknown quoted-triple syntax {quoted_triple_syntax:?} (expected \"rdf-star\" or \"rdf12\")"
            ))
        })?
    };
    build_card_surface(text, format, card_json, surface)
}

fn build_card_surface(
    text: &str,
    format: &str,
    card_json: &str,
    surface: rete_core::ingest::QuotedTripleSurface,
) -> Result<Vec<u8>, JsValue> {
    let quads = rete_core::ingest::parse_statements_audited_surface(text, format, None, surface)
        .map_err(err)?;
    build_card_quads(quads, ("string", text.as_bytes()), format, card_json)
}

/// The tail of [`build_card_surface`], after the input is parsed: shared with
/// [`build_bytes`], whose Jelly input has no text form.
fn build_card_quads(
    quads: Vec<rete_core::ingest::RawQuad>,
    input: (&str, &[u8]),
    format: &str,
    card_json: &str,
) -> Result<Vec<u8>, JsValue> {
    if quads.is_empty() {
        return Err(js_error(
            "no statements parsed (empty input or only comments)",
        ));
    }
    if card_json.trim().is_empty() {
        let read = quads.len() as u64;
        let (bytes, stats) = rete_core::ingest::assemble_dataset_quad(quads, &[]);
        return finish_build(bytes, "build_with_card", format, input, &stats, read);
    }
    let curated = validated_card(card_json)?;
    let read = quads.len() as u64;
    // The counts are only known once the dictionary and indexes exist, so the
    // card is serialized from inside the writer rather than handed in whole.
    let (bytes, stats) = rete_core::ingest::assemble_dataset_with_quad(quads, move |stats, _| {
        let card = rete_core::card::compose_curated_card(
            curated,
            stats.default_triples as u64,
            stats.statements as u64,
            stats.named_graphs as u64,
            stats.terms as u64,
            rete_core::LEGACY_FORMAT_VERSION,
        );
        serde_json::to_vec(&card).expect("card serializes")
    });
    finish_build(bytes, "build_with_card", format, input, &stats, read)
}

/// [`build_with_card_syntax`] for input held as **bytes**: any text format
/// (UTF-8, as `text` would be) or `"jelly"`, the binary Jelly RDF stream
/// format, which has no text form and so cannot go through the `&str`
/// builders. Same card and quoted-triple rules, same file out. The Jelly
/// reader is the one `rete build` uses ([`rete_core::ingest::parse_jelly_bytes`]);
/// the whole file must be in memory, as every browser build is.
#[wasm_bindgen]
pub fn build_bytes(
    bytes: &[u8],
    format: &str,
    card_json: &str,
    quoted_triple_syntax: &str,
) -> Result<Vec<u8>, JsValue> {
    if format != "jelly" {
        let text = std::str::from_utf8(bytes)
            .map_err(|e| js_error(format!("input is not valid UTF-8 text: {e}")))?;
        return build_with_card_syntax(text, format, card_json, quoted_triple_syntax);
    }
    let quads = rete_core::ingest::parse_jelly_bytes(bytes).map_err(err)?;
    build_card_quads(quads, ("bytes", bytes), format, card_json)
}

/// [`build_with_card`], but the card also carries the **auto-derived profile**
/// — the half a browser build used to have to do without (#152).
///
/// Predicates, classes, vocabularies, datatypes, languages, the class-link
/// quotient, hubs, the affordance signals, and the tiered starter-query
/// library are all computed here, by exactly the code `rete build --card`
/// runs ([`rete_core::card::derive_card`]). On the same graph with the same
/// curated document, the metadata section this writes is **byte-identical** to
/// the CLI's.
///
/// Two honest differences remain, and neither is derivation:
///
/// - **Sections are uncompressed** (the wasm build has no zstd *encoder*), so
///   the file is larger than a CLI build of the same graph. Every reader
///   accepts it.
/// - **The build record has no starter-query costs**: they come from *running*
///   the starter queries, which is a benchmark, not a build. Everything else
///   in the record is there (see `finish_build`).
///
/// # Why this is a separate function
///
/// Derivation walks the graph twice more. In a browser, on a paste the user is
/// waiting on, that is a cost they should choose — so [`build_with_card`]
/// keeps writing exactly the bytes it always has, and this is the opt-in.
///
/// Pass an empty string for `card_json` to derive a profile-only card with no
/// curated fields (the equivalent of a bare `rete build --card`).
#[wasm_bindgen]
pub fn build_with_derived_card(
    text: &str,
    format: &str,
    card_json: &str,
) -> Result<Vec<u8>, JsValue> {
    let quads = rete_core::ingest::parse_statements(text, format).map_err(err)?;
    if quads.is_empty() {
        return Err(js_error(
            "no statements parsed (empty input or only comments)",
        ));
    }
    // The typed curated half, held to the same rules `--card-file` is held to.
    let curated = if card_json.trim().is_empty() {
        rete_core::card::CardInput::default()
    } else {
        // Validate through the document validator first, so the wording a
        // browser author sees is the wording `validate_card` shows them while
        // they type, not a raw serde message.
        validated_card(card_json)?;
        rete_core::card::CardInput::from_json_str(card_json).map_err(js_error)?
    };
    let read = quads.len() as u64;
    let (bytes, stats) =
        rete_core::ingest::assemble_dataset_with_quad(quads, move |stats, quads| {
            let card = rete_core::card::derive_card(
                quads,
                stats.terms as u64,
                stats.named_graphs as u64,
                curated,
            );
            // The counts the file actually holds are known only once the indexes
            // have deduplicated the input — the same two-stage stamp the CLI uses.
            rete_core::ingest::DeferredMetadata::new(move |counts| {
                card.with_final_counts(counts).to_json_bytes()
            })
        });
    finish_build(
        bytes,
        "build_with_derived_card",
        format,
        ("string", text.as_bytes()),
        &stats,
        read,
    )
}

/// Check a curated card document without building anything — so an editor can
/// report the **exact** error `rete build --card-file` would report, while the
/// author is still typing. Returns the empty string when the document is
/// valid, otherwise the error message.
///
/// Deliberately not a boolean: the wording is the useful part (a free-text
/// `theme` is told to use `keywords`; a stray top-level key is told about the
/// `extra` bag), and duplicating that wording in JavaScript is exactly how the
/// two writers would drift apart again.
#[wasm_bindgen]
pub fn validate_card(card_json: &str) -> String {
    check_card(card_json).err().unwrap_or_default()
}

/// Parse + validate a curated card document. The message stays a `String` all
/// the way through — wrapping it in a JS `Error` first and unwrapping it later
/// loses the wording, which is the part worth returning.
fn check_card(card_json: &str) -> Result<serde_json::Value, String> {
    let doc: serde_json::Value =
        serde_json::from_str(card_json).map_err(|e| format!("card is not JSON: {e}"))?;
    rete_core::card::validate_curated_card(&doc)
}

/// [`check_card`] as a JS exception, for the build path.
fn validated_card(card_json: &str) -> Result<serde_json::Value, JsValue> {
    check_card(card_json).map_err(js_error)
}

/// Evaluate a triple pattern; `null`/`undefined` positions are wildcards.
/// Returns a JSON array of `[subject, predicate, object]` triples.
#[wasm_bindgen]
pub fn query_triples(
    bytes: &[u8],
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let rows = rete.query(subject.as_deref(), predicate.as_deref(), object.as_deref());
    serde_json::to_string(&rows).map_err(err)
}

/// Explain why each triple-pattern match is present in the `.rete` file.
///
/// `null`/`undefined` positions are wildcards. The JSON uses browser-facing
/// camelCase fields:
/// `{ "pattern", "resultCount", "results": [{ "terms", "ids", "provenance" }] }`.
#[wasm_bindgen]
pub fn why_triples(
    bytes: &[u8],
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
) -> Result<String, JsValue> {
    why_triples_json(
        bytes,
        subject.as_deref(),
        predicate.as_deref(),
        object.as_deref(),
    )
    .map_err(js_error)
}

/// Native-testable implementation for [`why_triples`].
pub fn why_triples_json(
    bytes: &[u8],
    subject: Option<&str>,
    predicate: Option<&str>,
    object: Option<&str>,
) -> Result<String, String> {
    use serde_json::json;

    let rete = Rete::open(bytes).map_err(|e| e.to_string())?;
    let results = rete.query_with_provenance(subject, predicate, object);
    let out = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "pattern": {
            "subject": subject,
            "predicate": predicate,
            "object": object,
        },
        "resultCount": results.len(),
        "results": results.iter().map(provenance_json).collect::<Vec<_>>(),
    });
    serde_json::to_string(&out).map_err(|e| e.to_string())
}

/// Run a SPARQL SELECT; returns a JSON array of solution objects
/// (`{ "var": "value", ... }`).
#[wasm_bindgen]
pub fn query_sparql(bytes: &[u8], query: &str) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let (_vars, solutions) = eval_sparql(&rete, query).map_err(err)?;
    serde_json::to_string(&solutions).map_err(err)
}

/// The ontology profile (the semantic coarse graph), as JSON:
/// `{ "classes": [["<iri>", count], ...],
///    "relations": [["sClass","pred","oClass", count], ...] }`.
/// The "overview first" payload — render it before fetching any detail.
#[wasm_bindgen]
pub fn schema(bytes: &[u8]) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let classes = schema_classes(&rete);
    let relations = schema_summary(&rete);
    serde_json::to_string(&serde_json::json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "classes": classes,
        "relations": relations,
    }))
    .map_err(err)
}

/// Read the **baked** schema pyramid (classes + class-level relations) straight
/// from the file's schema block via a slice reader — no triple scan. The
/// in-memory twin of [`schema_url`]: a cached big graph gets its schema from a
/// few KB of the buffer instead of dumping every triple (seconds on a 150 MB
/// file). Errors when the file carries no schema pyramid, so callers fall back
/// to the scanning [`schema`].
#[wasm_bindgen]
pub fn schema_packed(bytes: &[u8]) -> Result<String, JsValue> {
    use serde_json::json;
    let (classes, relations) = rete_core::read_schema_summary_ranged(&SliceReader::new(bytes))
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    let classes: Vec<serde_json::Value> = classes.iter().map(|(c, n)| json!([c, n])).collect();
    let relations: Vec<serde_json::Value> = relations
        .iter()
        .map(|(s, p, o, n)| json!([s, p, o, n]))
        .collect();
    Ok(json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "classes": classes,
        "relations": relations,
    })
    .to_string())
}

/// The embedded **Dataset Card** — the file's own self-description (title,
/// description, license, provenance, counts, example queries) as the JSON text
/// it was written with, or `undefined` when the file carries none. Reads the
/// metadata section straight out of the buffer.
#[wasm_bindgen]
pub fn card(bytes: &[u8]) -> Result<Option<String>, JsValue> {
    let bytes = rete_core::read_metadata_ranged(&SliceReader::new(bytes)).map_err(err)?;
    Ok(bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
}

/// The embedded **Dataset Card of a remote `.rete`**, in **two small range
/// requests**: the header, then the metadata section it points at — never the
/// dictionary, index, or pyramid. This is the index-free CARD tier: a client
/// learns what a multi-gigabyte graph *is* for a few KB. `undefined` when the
/// file carries no card. Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn card_url(url: &str) -> Result<Option<String>, JsValue> {
    let reader = RemoteReader::open(url)?.view();
    let bytes = rete_core::read_metadata_ranged(&reader).map_err(err)?;
    Ok(bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
}

/// The Dataset Card **and the build record** of a remote `.rete`, in the same
/// budget as the card alone: one header read, then **one coalesced range**
/// covering both sections — the writer lays the kind-7 build-info immediately
/// after the metadata precisely so this holds
/// ([`rete_core::range::read_card_and_build_info_ranged`], pinned by a
/// `rete-core` test). Reading the two separately would have made the CARD tier
/// cost three requests instead of two, which is why there is one export rather
/// than a second `build_info_url`.
///
/// JSON envelope:
/// `{"schemaVersion":1,"card":<text|null>,"build":<text|null>,"text_index":{…}}`.
/// `card` and `build` are the sections' **own bytes** as text, not a
/// re-serialization — the card a client displays is the card the file holds.
/// `text_index` is the one thing the file does *not* store about itself and this
/// reader measures instead (see the private `text_index_json`). Worker-only
/// (synchronous XHR).
#[wasm_bindgen]
pub fn card_and_build_url(url: &str) -> Result<String, JsValue> {
    // The polyglot-aware view: base 0 for a plain .rete, shifted past the HTML
    // shell for a polyglot — so the card of an embedded graph is read with the
    // same two requests as a standalone file's.
    let reader = RemoteReader::open(url)?.view();
    card_build_from(&reader)
}

/// [`card_and_build_url`] for an image already in memory — no I/O at all.
#[wasm_bindgen]
pub fn card_and_build(bytes: &[u8]) -> Result<String, JsValue> {
    card_build_from(&SliceReader::new(bytes))
}

/// The shared body of the two: header (which the card read needs anyway), the
/// coalesced card + build-info range, and the measured text-index signal — so
/// the CARD tier stays at one header read plus one coalesced range, plus the
/// ≤10-byte probe only when there is an index to measure.
fn card_build_from<R: RangeReader>(reader: &R) -> Result<String, JsValue> {
    let (header, card, build) =
        rete_core::read_card_and_build_info_with_header(reader).map_err(err)?;
    let token_table = rete_core::read_text_index_token_table_len_ranged(reader, &header);
    Ok(card_build_envelope(
        card,
        build,
        text_index_json(&header, token_table),
    ))
}

/// Whether a `.rete` carries a **full-text (TEXT_INDEX) section**, measured from
/// the section directory in the 1 KiB header the caller has just read:
/// `{"present":bool,"bytes":N,"token_table_bytes":N}` (the last two only when
/// there is an index).
///
/// This is not in the card, and deliberately so. A file built with
/// `--text-index` answers `FILTER(CONTAINS(…))` by word lookup; one built
/// without it answers the *same query with the same rows* by full scan, so the
/// capability is invisible from the results — and a stored flag would be a claim
/// that can outlive the section it describes. Measuring costs the header (already
/// fetched) plus one ≤10-byte range read for the token-table length: the figure
/// a first search actually pays, several times smaller than the whole section.
///
/// `token_table_bytes` is omitted when it was not measured — absent means
/// "not measured here", never "zero".
fn text_index_json(header: &Header, token_table_bytes: Option<u64>) -> serde_json::Value {
    if header.text_index_len == 0 {
        return serde_json::json!({ "present": false });
    }
    let mut v = serde_json::json!({
        "present": true,
        "bytes": header.text_index_len,
    });
    if let Some(tt) = token_table_bytes {
        v.as_object_mut()
            .expect("an object")
            .insert("token_table_bytes".into(), serde_json::json!(tt));
    }
    v
}

/// The `{card, build, text_index}` envelope both readers return. Absent sections
/// are `null`, never `""` or `{}`: a file built before build-info existed has no
/// build record, and a reader must be able to tell that from one that recorded
/// nothing. `text_index` is always an object — it is measured, so there is
/// always an answer, including for a file with no card at all.
fn card_build_envelope(
    card: Option<Vec<u8>>,
    build: Option<Vec<u8>>,
    text_index: serde_json::Value,
) -> String {
    let text = |b: Option<Vec<u8>>| match b {
        Some(b) if !b.is_empty() => {
            serde_json::Value::String(String::from_utf8_lossy(&b).into_owned())
        }
        _ => serde_json::Value::Null,
    };
    serde_json::json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "card": text(card),
        "build": text(build),
        "text_index": text_index,
    })
    .to_string()
}

/// The **true byte length of a remote `.rete`**, in 1–2 tiny range requests —
/// derived from the file's *own* header (the issue-#95 probe: sections are
/// back-to-back and the file ends with the 4-byte `RETE` footer), never from
/// the transport's numbers, which may describe a compressed representation
/// (GitHub Pages HEADs a 71 MB file as its 58 MB gzip) or be hidden from
/// cross-origin JS entirely. This is how a UI can say what "download the whole
/// file" actually costs **before** committing to it.
/// JSON: `{ "schemaVersion": 1, "fileLength": <bytes> }`. Worker-only
/// (synchronous XHR in the sync build).
#[wasm_bindgen]
pub fn file_len_url(url: &str) -> Result<String, JsValue> {
    // The GRAPH's length: for a polyglot that is the appended `.rete`, not the
    // web page wrapped around it — "download the whole file" must quote the
    // bytes a `.rete` consumer would actually take.
    let reader = RemoteReader::open(url)?;
    Ok(format!(
        r#"{{"schemaVersion":{},"fileLength":{}}}"#,
        JSON_SCHEMA_VERSION,
        reader.len()
    ))
}

/// A `.rete` opened **once** and kept resident, so a client (the playground's
/// cached/in-memory mode) can run many queries on a big file without re-copying
/// the whole buffer into wasm and re-decoding its dictionary on every call. The
/// methods mirror the free functions above but operate on the already-open
/// [`Rete`]. The few index-free readers (`schema_packed`, `progressive_query`,
/// `check_schema`) stay free functions — they read small ranges from the buffer
/// and are called rarely (once at load / on demand), so a handle buys little.
#[wasm_bindgen]
pub struct Graph {
    rete: Rc<Rete>,
    file_len: usize,
    /// The kind-7 build record's own bytes, lifted at open time. `Rete` keeps
    /// the metadata section but not this one (it is outside the content hash
    /// and no query needs it), and the handle does not retain the buffer — so
    /// it is read once here rather than made unreachable.
    build_info: Option<String>,
}

#[wasm_bindgen]
impl Graph {
    /// Open a `.rete` image and keep it resident for repeated querying.
    #[wasm_bindgen(constructor)]
    pub fn new(bytes: &[u8]) -> Result<Graph, JsValue> {
        Ok(Graph {
            rete: Rc::new(open(bytes)?),
            file_len: bytes.len(),
            build_info: rete_core::read_build_info(bytes)
                .ok()
                .flatten()
                .filter(|b| !b.is_empty())
                .map(|b| String::from_utf8_lossy(&b).into_owned()),
        })
    }

    /// A **lazy, resumable cursor** over the quads of this graph — the streaming
    /// export path. See [`QuadCursor`]; `graph` selects one graph (`""` = the
    /// default graph), `None` streams the default graph followed by every named
    /// graph. `s` / `p` / `o` optionally restrict the dump to a triple pattern,
    /// which **prunes tiles** rather than filtering rows.
    pub fn quads(
        &self,
        graph: Option<String>,
        s: Option<String>,
        p: Option<String>,
        o: Option<String>,
    ) -> QuadCursor {
        QuadCursor::start(self.rete.clone(), graph, s, p, o)
    }

    /// See [`info`].
    pub fn info(&self) -> String {
        let h = self.rete.header();
        format!(
            r#"{{"schemaVersion":1,"quads":{},"terms":{},"pyramidLevels":{},"namedGraphs":{}}}"#,
            h.quad_count,
            h.term_count,
            h.pyramid_levels,
            self.rete.named_graph_count()
        )
    }

    /// See [`graph_names`].
    pub fn graph_names(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.rete.graph_names()).map_err(err)
    }

    /// See [`query`].
    pub fn query(&self, query: &str, format: &str) -> Result<String, JsValue> {
        query_json(&self.rete, query, format, "")
    }

    /// As [`query`], with OWL 2 QL entailment on (`rdfs:subClassOf` /
    /// `subPropertyOf` / `domain` / `range` reasoning by query rewriting).
    pub fn query_reasoned(&self, query: &str, format: &str) -> Result<String, JsValue> {
        query_json_reasoned(&self.rete, query, format, "")
    }

    /// As [`query`], with explicit opt-in toggles: `reason` (OWL 2 QL
    /// entailment) and `union_default` (union default graph — a pattern
    /// outside `GRAPH` matches the merge of the default graph and every named
    /// graph, the Virtuoso / GraphDB / Jena TDB mode; non-standard, so plain
    /// [`Graph::query`] never does this).
    pub fn query_opts(
        &self,
        query: &str,
        format: &str,
        reason: bool,
        union_default: bool,
    ) -> Result<String, JsValue> {
        query_json_with(&self.rete, query, format, "", reason, union_default)
    }

    /// Run a SELECT to a **result handle**: the rows stay dictionary ids and
    /// [`QueryRows::page`] decodes a window on demand. See [`QueryRows`].
    pub fn query_rows(
        &self,
        query: &str,
        reason: bool,
        union_default: bool,
    ) -> Result<QueryRows, JsValue> {
        QueryRows::run(&self.rete, query, reason, union_default, false)
    }

    /// Plan running `query` as chunks split by the values of `var` — see
    /// `rete_core::partition_plan`. JSON `{var, form, keys_query,
    /// keys_from_where, offset, limit, dedupe}`, or an error saying why the
    /// split would change the answer.
    pub fn partition_plan(&self, query: &str, var: &str) -> Result<String, JsValue> {
        partition_plan_json(&self.rete, query, var)
    }

    /// One chunk of a split query: the solutions whose `var` is one of `keys`
    /// (term tokens, as the plan's keys query returned them), without the
    /// query's top-level OFFSET/LIMIT. Same envelope as [`Graph::query`].
    pub fn query_partition(
        &self,
        query: &str,
        format: &str,
        reason: bool,
        var: &str,
        keys: Vec<String>,
    ) -> Result<String, JsValue> {
        query_partition_json(&self.rete, query, format, reason, var, &keys)
    }

    /// See [`query_triples`].
    pub fn query_triples(
        &self,
        subject: Option<String>,
        predicate: Option<String>,
        object: Option<String>,
    ) -> Result<String, JsValue> {
        let rows = self
            .rete
            .query(subject.as_deref(), predicate.as_deref(), object.as_deref());
        serde_json::to_string(&rows).map_err(err)
    }

    /// See [`prefix_search`].
    pub fn prefix_search(&self, prefix: &str, limit: usize) -> Result<String, JsValue> {
        prefix_search_json(&self.rete, prefix, limit)
    }

    /// See [`text_search`].
    pub fn text_search(
        &self,
        words: Vec<String>,
        contains_prefix: Option<String>,
        limit: usize,
    ) -> Result<String, JsValue> {
        text_search_json(&self.rete, &words, contains_prefix.as_deref(), limit)
    }

    /// Byte length of the TEXT_INDEX section, `0` when the file has none — a
    /// header read, never a fault. The UI asks this to decide whether to offer
    /// full-text search at all, and to state the cost before the first one.
    /// `f64` because the section outgrows `u32`: causenet's is 1.88 GB.
    pub fn text_index_len(&self) -> f64 {
        self.rete.header().text_index_len as f64
    }

    /// Byte length of the TEXT_INDEX's leading **token table** — what a first
    /// [`Graph::text_search_one`] actually faults, and therefore the only honest
    /// number to quote as its cost. [`Graph::text_index_len`] is the whole
    /// section, postings blob included, and overstates it 6.5× on
    /// `epfl-infoscience` (195 MB section, 29 MB token table); the postings are
    /// only ever fetched one list at a time. `0` when the file has no text index
    /// or the length could not be read — the caller must then say nothing about
    /// a token table rather than pass the section length off as one.
    /// `f64` for the same reason as the section length: causenet's table is
    /// 1.88 GB.
    pub fn text_index_token_table_len(&self) -> f64 {
        self.rete.text_index_token_table_len().unwrap_or(0) as f64
    }

    /// [`Graph::text_search`] from ONE phrase: whitespace splits it into words
    /// and **every** word must match (AND), like `rete search --contains a b`.
    /// One string in, one string out — that is what the remote twin's
    /// hand-marshaled asyncify path can carry (a JS array marshaled raw is what
    /// traps), and the UI is a single text box either way. Same JSON envelope.
    pub fn text_search_one(&self, phrase: &str, limit: usize) -> Result<String, JsValue> {
        let words: Vec<String> = phrase.split_whitespace().map(str::to_owned).collect();
        text_search_json(&self.rete, &words, None, limit)
    }

    /// See [`why_triples`].
    pub fn why_triples(
        &self,
        subject: Option<String>,
        predicate: Option<String>,
        object: Option<String>,
    ) -> Result<String, JsValue> {
        use serde_json::json;
        let results = self.rete.query_with_provenance(
            subject.as_deref(),
            predicate.as_deref(),
            object.as_deref(),
        );
        let out = json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "pattern": { "subject": subject, "predicate": predicate, "object": object },
            "resultCount": results.len(),
            "results": results.iter().map(provenance_json).collect::<Vec<_>>(),
        });
        serde_json::to_string(&out).map_err(err)
    }

    /// See [`schema`] — the live (scanning) profile; prefer `schema_packed` when
    /// the file carries a pyramid.
    pub fn schema(&self) -> Result<String, JsValue> {
        serde_json::to_string(&serde_json::json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "classes": schema_classes(&self.rete),
            "relations": schema_summary(&self.rete),
        }))
        .map_err(err)
    }

    /// The card's `signals.quoted_triples` for this file, from its header: does
    /// it hold quoted triples, and in which surfaces can an export write them.
    pub fn quoted_triples_signal(&self) -> String {
        quoted_triples_signal_json(self.rete.header())
    }

    /// See [`card`] — the Dataset Card of the resident file.
    pub fn card(&self) -> Option<String> {
        self.rete
            .metadata()
            .map(|b| String::from_utf8_lossy(b).into_owned())
    }

    /// See [`card_and_build`] — the card and the build record of the resident
    /// file, in the same envelope the remote path returns, so one caller
    /// handles both sources.
    pub fn card_and_build(&self) -> String {
        let card = self
            .rete
            .metadata()
            .filter(|b| !b.is_empty())
            .map(|b| b.to_vec());
        // A resident open already decoded the whole TEXT_INDEX section, so both
        // figures are free here.
        let text_index =
            text_index_json(self.rete.header(), self.rete.text_index_token_table_len());
        card_build_envelope(
            card,
            self.build_info.as_ref().map(|s| s.as_bytes().to_vec()),
            text_index,
        )
    }

    /// See [`query_communities`].
    pub fn query_communities(&self, query: &str, round: Option<usize>) -> Result<String, JsValue> {
        query_communities_value(&self.rete, query, round)
    }

    /// See [`reach`].
    pub fn reach(&self, predicate: &str, seeds: &str, reverse: bool) -> Result<String, JsValue> {
        reach_rete(&self.rete, predicate, seeds, reverse)
    }

    /// See [`shacl`].
    pub fn shacl(
        &self,
        shapes_turtle: &str,
        graph: Option<String>,
        format: &str,
    ) -> Result<String, JsValue> {
        shacl_rete(&self.rete, shapes_turtle, graph.as_deref(), format)
    }

    /// See [`reason`].
    pub fn reason(&self, graph: Option<String>) -> String {
        let base = self.rete.dump(graph.as_deref());
        reasoning_json(&rete_core::reason(&base), None)
    }

    /// See [`pyramid_tree`].
    pub fn pyramid_tree(&self) -> Result<String, JsValue> {
        pyramid_tree_value(&self.rete)
    }

    /// See [`file_layout`].
    pub fn file_layout(&self) -> Result<String, JsValue> {
        use serde_json::json;
        let segments: Vec<serde_json::Value> = self
            .rete
            .file_layout()
            .iter()
            .map(|s| json!({ "kind": s.kind, "label": s.label, "offset": s.offset, "len": s.len }))
            .collect();
        serde_json::to_string(&json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "fileLength": self.file_len,
            "segments": segments,
        }))
        .map_err(err)
    }
}

/// A **lazy, resumable cursor** over the quads of an open `.rete` — the engine
/// side of `for await (const [s, p, o, g] of graph.dump())` in the JS client.
///
/// # Why a cursor and not a callback
///
/// [`Rete::dump_each`] already streams in constant memory, but a Rust callback
/// cannot be *paused* to hand control back to JavaScript: to feed a JS iterator
/// it would have to buffer every quad first, which is exactly the `Vec` that
/// [`Rete::dump`] builds and that OOMs on a large file. This wraps
/// [`Rete::query_batch`] instead, so the scan can be suspended between calls and
/// resumed in place — the whole resume state is one opaque `u64`, never a
/// whole-graph materialization anywhere in the pipeline.
///
/// # Why batched (and not one call per quad)
///
/// Each wasm→JS call costs far more than decoding a triple, and every returned
/// `String` becomes a fresh JS string. Pulling one quad per call would make the
/// boundary the bottleneck; pulling *all* of them would reintroduce the `Vec`.
/// So the JS wrapper asks for `DUMP_BATCH` quads at a time and yields them one
/// by one — bounded, amortized, and lazy. Memory is O(batch), not O(graph).
///
/// # Cost model
///
/// The dictionary is **not** prefetched whole: each batch faults only the
/// chunks its own terms live in, so taking five quads off the front costs five
/// quads' worth of dictionary rather than all of it. Index tiles fault in as the
/// scan advances and stay resident, and so do dictionary chunks, so an
/// **unfiltered** dump driven to the end still ends up fetching essentially the
/// whole file — that is inherent in exporting a graph.
///
/// A **filtered** cursor (a bound `s` / `p` / `o`) is a different shape: the
/// scan routes to the one permutation that sorts on the bound prefix and drops
/// every tile whose synopsis proves it cannot match, from the tile directory,
/// *without fetching it*. On `cordis.rete` (801 MB, six named graphs) dumping
/// one predicate of one graph reads 16 MB where the unfiltered dump of that
/// graph reads 376 MB. Peak memory is O(faulted dictionary + index), never
/// O(quads), either way.
/// A SELECT answered to dictionary ids: the **result handle** of
/// [`Graph::query_rows`] and [`RemoteGraph::query_rows`].
///
/// `query` evaluates a SELECT and decodes every term of every row to JSON; a
/// page of 25 rows of a 650,000-row result still costs the whole result's
/// dictionary chunks (181 MB for a class of the nanopub dump). The handle keeps
/// the rows as ids, with the exact row count, and `page(offset, limit)` decodes
/// one window, as one batch of chunk reads. What the query itself needs is
/// decoded as before (the keys of an ORDER BY, the inputs of a FILTER); the
/// other columns wait for the page. `free()` it when done.
#[wasm_bindgen]
pub struct QueryRows {
    rete: Rc<Rete>,
    rows: rete_core::SelectRows,
    remote: bool,
}

impl QueryRows {
    fn run(
        rete: &Rc<Rete>,
        query: &str,
        reason: bool,
        union_default: bool,
        remote: bool,
    ) -> Result<QueryRows, JsValue> {
        let rows = rete_core::eval_select_rows(
            rete,
            query,
            QueryOpts {
                reason,
                union_default_graph: union_default,
            },
        )
        .map_err(err)?;
        Ok(QueryRows {
            rete: rete.clone(),
            rows,
            remote,
        })
    }
}

#[wasm_bindgen]
impl QueryRows {
    /// The projected variables, a JSON array (for `SELECT *`, the variables
    /// some row binds, in name order).
    pub fn vars(&self) -> String {
        serde_json::to_string(self.rows.vars()).unwrap_or_else(|_| "[]".to_string())
    }

    /// The exact number of rows.
    pub fn len(&self) -> f64 {
        self.rows.len() as f64
    }

    /// Rows `offset..offset + limit` (cut at the end), in the envelope of
    /// `query(..., "json")`: `{"kind":"select","vars":[…],"rows":[{var:term}]}`
    /// plus `"offset"` and `"total"`. Calling it again, or for another window,
    /// reuses the dictionary chunks already read.
    pub fn page(&self, offset: usize, limit: usize) -> Result<String, JsValue> {
        if self.remote {
            self.rete.reset_load_failures();
        }
        let page = self.rows.page(&self.rete, offset, limit);
        if self.remote {
            incomplete_guard(&self.rete, "query")?;
        }
        let start = offset.min(self.rows.len());
        let out = QueryOutput::Select(self.rows.vars().to_vec(), page);
        let mut extra = format!(
            r#","schemaVersion":{JSON_SCHEMA_VERSION},"offset":{start},"total":{}"#,
            self.rows.len()
        );
        // As `query`: a `warnings` member only when there is something to say.
        if !self.rows.warnings().is_empty() {
            extra.push_str(r#","warnings":"#);
            extra.push_str(&rete_core::warnings_json(self.rows.warnings()));
        }
        Ok(rete_core::results_envelope_json(&out, &extra))
    }
}

#[wasm_bindgen]
pub struct QuadCursor {
    /// Graph slots not yet streamed; `None` = the default graph.
    pending: std::vec::IntoIter<Option<String>>,
    /// The graph being streamed (`None` = the default graph), and how far into
    /// it we got. The resume state is one opaque `u64` — see `Rete::query_batch`.
    current: Option<Option<String>>,
    cursor: u64,
    /// The triple pattern this dump is restricted to; all-`None` = every quad.
    /// Held as owned tokens because the cursor outlives every call.
    s: Option<String>,
    p: Option<String>,
    o: Option<String>,
    /// Whether the live graph's last batch was its final one.
    slot_done: bool,
    /// Triples resolved by the last `query_batch` that the caller has not taken
    /// yet. A batch ends on a group boundary, so this drains before the next.
    buffered: std::vec::IntoIter<TermTriple>,
    rete: Rc<Rete>,
    /// `next_nquads` respells quoted triples into the RDF 1.2 triple-term
    /// surface `<<( s p o )>>`. Off until [`QuadCursor::set_quoted_triple_syntax`]
    /// asks for `"rdf12"`, and off whatever is asked when the header says the
    /// file holds no quoted triple — so such a dump is byte-for-byte unchanged.
    rdf12: bool,
}

/// Quads per `next_batch` / `next_nquads` call, and the JS wrapper's default.
///
/// 10 000 keeps the per-call boundary cost negligible (one call and ~40 000 JS
/// string allocations amortize a 10 000-triple decode) while bounding the
/// transient buffer at roughly 10 000 × ~120 B ≈ 1.2 MB — small next to the
/// dictionary any dump already needs resident, and flat no matter how many
/// billions of quads follow it.
const DUMP_BATCH: usize = 10_000;

impl QuadCursor {
    /// `graph`: `None` = the default graph followed by every named graph;
    /// `Some("")` = the default graph only; `Some(name)` = that named graph
    /// (bare IRI or `<iri>` token — both are accepted).
    ///
    /// `s` / `p` / `o` are canonical N-Triples term tokens; an empty string is
    /// treated as unbound, so a JS caller can pass `""` for "no filter" without
    /// a separate sentinel. A bound term the dictionary does not know yields an
    /// empty dump without touching the index.
    fn start(
        rete: Rc<Rete>,
        graph: Option<String>,
        s: Option<String>,
        p: Option<String>,
        o: Option<String>,
    ) -> QuadCursor {
        let slots: Vec<Option<String>> = match graph {
            None => std::iter::once(None)
                .chain(rete.graph_names().iter().map(|g| Some((*g).to_string())))
                .collect(),
            Some(g) if g.is_empty() => vec![None],
            Some(g) => vec![Some(canonical_graph_name(&rete, g))],
        };
        // The incompleteness verdict is PER DUMP: clear the sticky flags so a
        // failure from an earlier query does not condemn this one (and so
        // `finish()` reports only what happened while streaming).
        rete.reset_load_failures();
        let term = |t: Option<String>| t.filter(|t| !t.is_empty());
        QuadCursor {
            pending: slots.into_iter(),
            current: None,
            cursor: 0,
            s: term(s),
            p: term(p),
            o: term(o),
            slot_done: false,
            buffered: Vec::new().into_iter(),
            rete,
            rdf12: false,
        }
    }

    /// Pull at most `max` quads, handing each to `sink` as
    /// `(s, p, o, graph)` where `graph` is `None` for the default graph.
    /// Returns how many were emitted; fewer than `max` means the stream ended.
    ///
    /// The scan is resumable rather than held open: each refill calls
    /// `Rete::query_batch`, whose entire resume state is one opaque `u64`. That
    /// is what lets this struct be `'static` — required by `#[wasm_bindgen]` —
    /// without a self-referential iterator borrowing the `Rete` beside it.
    fn pull<F: FnMut(&str, &str, &str, Option<&str>)>(&mut self, max: usize, mut sink: F) -> usize {
        let mut emitted = 0;
        while emitted < max {
            // 1. Hand out what the last batch already resolved.
            if let Some((s, p, o)) = self.buffered.next() {
                let graph = self.current.as_ref().and_then(|g| g.as_deref());
                sink(&s, &p, &o, graph);
                emitted += 1;
                continue;
            }
            // 2. Buffer empty. Open the next graph slot if none is live…
            let Some(slot) = self.current.clone() else {
                match self.pending.next() {
                    Some(next) => {
                        self.current = Some(next);
                        self.cursor = 0;
                        self.slot_done = false;
                    }
                    None => break,
                }
                continue;
            };
            // 3. …or close the live one if its last batch is drained.
            if self.slot_done {
                self.current = None;
                continue;
            }
            // 4. Otherwise resume it. `query_batch` always advances the cursor
            //    or reports done, so this cannot spin.
            let want = (max - emitted).max(DUMP_BATCH);
            let (triples, next, done) = self.rete.query_batch(
                slot.as_deref(),
                self.s.as_deref(),
                self.p.as_deref(),
                self.o.as_deref(),
                self.cursor,
                want,
            );
            self.cursor = next;
            self.slot_done = done;
            self.buffered = triples.into_iter();
        }
        emitted
    }

    /// True once every selected graph has been streamed to its end.
    fn finished(&self) -> bool {
        self.current.is_none() && self.pending.len() == 0 && self.buffered.len() == 0
    }

    /// Refuse to end a dump that silently lost bytes to a failed range fetch —
    /// a truncated export is worse than a failed one.
    fn guard(&self) -> Result<(), JsValue> {
        if self.finished() {
            incomplete_guard(&self.rete, "dump")?;
        }
        Ok(())
    }
}

/// One statement's object token in the RDF 1.2 surface, or the reason it has
/// none — the same rule as `rete export --quoted-triple-syntax rdf12`
/// (`ttSubject ::= iri | BlankNode`: a triple term stands in object position
/// only), with the same hint.
fn rdf12_object<'a>(s: &str, p: &str, o: &'a str) -> Result<std::borrow::Cow<'a, str>, String> {
    use rete_core::terms::is_quoted_triple;
    if is_quoted_triple(s) || is_quoted_triple(p) {
        let slot = if is_quoted_triple(s) {
            "subject"
        } else {
            "predicate"
        };
        return Err(format!(
            "this graph has a quoted triple in the {slot} position of a statement, and RDF 1.2 \
             has no syntax for one there: a triple term may stand in OBJECT position only.\n\
             statement: {s} {p} {o} .\n\
             hint: quotedTripleSyntax \"rdf-star\" writes the RDF-star surface <<s p o>>, which \
             rete re-ingests losslessly"
        ));
    }
    rete_core::terms::rdf12_triple_term(o).ok_or_else(|| {
        format!(
            "this graph has a quoted triple nested in the SUBJECT of another quoted triple, and \
             RDF 1.2 has no syntax for one there.\n\
             statement: {s} {p} {o} .\n\
             hint: quotedTripleSyntax \"rdf-star\" writes the RDF-star surface <<s p o>>"
        )
    })
}

/// The card's `signals.quoted_triples`, measured from the header exactly as
/// `rete card` does: `{"present":bool,"export_surfaces":[…],"export_default":…}`.
fn quoted_triples_signal_json(header: &Header) -> String {
    serde_json::to_string(&rete_core::card::QuotedTriplesSignal::probe(header))
        .expect("the signal serializes")
}

#[wasm_bindgen]
impl QuadCursor {
    /// Up to `max` quads as a **flat** `string[]` of `[s, p, o, g, s, p, o, g, …]`
    /// N-Triples term tokens, `g` being `""` for the default graph. Flat because
    /// a nested array would allocate one JS array per quad for no gain — the
    /// caller slices it into tuples as it yields them.
    ///
    /// An empty array means the stream is finished; keep calling until you get
    /// one (that final call is what verifies no range fetch failed mid-dump).
    pub fn next_batch(&mut self, max: Option<usize>) -> Result<Vec<String>, JsValue> {
        let max = max.unwrap_or(DUMP_BATCH).max(1);
        let mut out: Vec<String> = Vec::with_capacity(max.min(DUMP_BATCH) * 4);
        self.pull(max, |s, p, o, g| {
            out.push(s.to_string());
            out.push(p.to_string());
            out.push(o.to_string());
            out.push(g.unwrap_or("").to_string());
        });
        self.guard()?;
        Ok(out)
    }

    /// Up to `max` quads already serialized as N-Quads lines in **one** string —
    /// the `.rete` → Oxigraph / N-Quads-file path. One string crossing per batch
    /// instead of four per quad: no per-term JS string, no re-serialization in
    /// JavaScript, and the terms are already canonical N-Triples tokens, so the
    /// lines are emitted verbatim.
    ///
    /// An empty string means the stream is finished.
    pub fn next_nquads(&mut self, max: Option<usize>) -> Result<String, JsValue> {
        let max = max.unwrap_or(DUMP_BATCH).max(1);
        // ~120 B/quad is a typical N-Quads line; the Vec grows if it is wrong.
        let mut out = String::with_capacity(max.min(DUMP_BATCH) * 120);
        let rdf12 = self.rdf12;
        let mut refused: Option<String> = None;
        self.pull(max, |s, p, o, g| {
            if refused.is_some() {
                return;
            }
            let o = if rdf12 {
                match rdf12_object(s, p, o) {
                    Ok(o) => o,
                    Err(e) => {
                        refused = Some(e);
                        return;
                    }
                }
            } else {
                std::borrow::Cow::Borrowed(o)
            };
            out.push_str(s);
            out.push(' ');
            out.push_str(p);
            out.push(' ');
            out.push_str(&o);
            if let Some(g) = g {
                out.push(' ');
                out.push_str(g);
            }
            out.push_str(" .\n");
        });
        if let Some(e) = refused {
            return Err(js_error(e));
        }
        self.guard()?;
        Ok(out)
    }

    /// How [`next_nquads`](Self::next_nquads) spells a quoted triple — the
    /// values of `rete export --quoted-triple-syntax`:
    ///
    /// - `"rdf-star"` (or `""`; the cursor's initial state): `<<s p o>>`, the
    ///   stored token, verbatim — what this cursor always wrote.
    /// - `"rdf12"`: the RDF 1.2 triple term `<<( s p o )>>`, nested terms too,
    ///   which current RDF 1.2 parsers (Oxigraph 0.5, Jena 5) load. RDF 1.2
    ///   admits a triple term in object position only, so a quoted triple in a
    ///   statement's subject/predicate (or in another's subject) makes the next
    ///   call fail by name instead of writing a line nothing parses.
    ///
    /// Anything else is refused. A file whose header records no quoted triple
    /// is written byte-for-byte the same under both.
    pub fn set_quoted_triple_syntax(&mut self, syntax: &str) -> Result<(), JsValue> {
        let surface = if syntax.is_empty() {
            rete_core::ingest::QuotedTripleSurface::RdfStar
        } else {
            rete_core::ingest::QuotedTripleSurface::parse(syntax).ok_or_else(|| {
                js_error(format!(
                    "unknown quoted-triple syntax {syntax:?} (expected \"rdf12\" or \"rdf-star\")"
                ))
            })?
        };
        self.rdf12 = surface == rete_core::ingest::QuotedTripleSurface::Rdf12
            && self.rete.header().has_quoted_triples();
        Ok(())
    }

    /// Whether every selected graph has been streamed to its end.
    pub fn done(&self) -> bool {
        self.finished()
    }
}

/// Resolve a caller-supplied graph name to the token the file stores. Graph
/// names are canonical N-Triples terms (`<iri>`), but the JS client hands out
/// bare IRIs, so accept either and prefer an exact match.
fn canonical_graph_name(rete: &Rete, name: String) -> String {
    if rete.graph_names().iter().any(|g| *g == name) {
        return name;
    }
    if name.starts_with('<') || name.starts_with("_:") {
        return name;
    }
    format!("<{name}>")
}

/// The wasm linear memory's current size in bytes — the engine's high-water
/// mark, since wasm memory grows but never shrinks. Exposed so a host can
/// *measure* the streaming-dump memory claim instead of trusting it: sample it
/// before and after a full [`QuadCursor`] drain and the growth stays flat
/// however many quads went by, where materializing them all does not.
#[wasm_bindgen]
pub fn heap_bytes() -> f64 {
    #[cfg(target_arch = "wasm32")]
    {
        (core::arch::wasm32::memory_size(0) as f64) * 65536.0
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        0.0
    }
}

/// A remote `.rete` opened **once over HTTP range** and kept resident in the
/// worker, so repeated queries on the same URL reuse (a) the block cache — any
/// 64 KiB block fetched once is served from memory by [`BlockCacheReader`] — and
/// (b) the lazily faulted index tiles + decoded dictionary chunks that live
/// inside the resident [`Rete`]. The free [`sparql_url`] re-opens the file on
/// every call, so its block cache dies after one query; this handle keeps it.
/// The counting reader stays reachable so the worker can read cumulative
/// bytes/requests and show how little a cache-hit query actually fetched.
/// **Worker-only** (synchronous range-read XHR).
#[wasm_bindgen]
pub struct RemoteGraph {
    reader: RemoteReader,
    rete: Rc<Rete>,
}

#[wasm_bindgen]
impl RemoteGraph {
    /// Open a remote `.rete` over HTTP range and keep it resident for repeated
    /// querying. The first query faults in the dictionary chunks + index tiles it
    /// needs; later queries on this handle reuse them and the block cache.
    #[wasm_bindgen(constructor)]
    pub fn new(url: &str) -> Result<RemoteGraph, JsValue> {
        let (reader, rete) = open_url(url)?;
        Ok(RemoteGraph {
            reader,
            rete: Rc::new(rete),
        })
    }

    /// See [`Graph::quads`] — the SAME lazy cursor, over the lazily range-read
    /// remote handle.
    ///
    /// An **unfiltered** dump is not network-lazy and cannot be: it resolves
    /// every term and visits every tile, so it ends up fetching essentially the
    /// whole file (and what it faults stays resident). A **filtered** one is:
    /// pass `s` / `p` / `o` and the scan routes to one permutation, keeps only
    /// the tiles whose synopsis admits the bound components, and fetches those.
    /// On `cordis.rete` (801 MB) one predicate of one named graph costs 16 MB
    /// instead of 376 MB. To peek at an unfiltered graph, still prefer a `LIMIT`
    /// query. Worker-only in the browser, like every other read here.
    pub fn quads(
        &self,
        graph: Option<String>,
        s: Option<String>,
        p: Option<String>,
        o: Option<String>,
    ) -> QuadCursor {
        QuadCursor::start(self.rete.clone(), graph, s, p, o)
    }

    /// `{ fileLength, bytes, requests, base }` — CUMULATIVE physical fetches
    /// since this session opened. The worker diffs successive calls to report a
    /// single query's traffic (a fully cached re-run adds ~0). `fileLength` is
    /// the **graph's** length and `base` the byte offset it starts at: `0` for an
    /// ordinary `.rete`, and the size of the HTML shell for a polyglot file.
    pub fn stats(&self) -> String {
        format!(
            r#"{{"schemaVersion":1,"fileLength":{},"bytes":{},"requests":{},"base":{}}}"#,
            self.reader.len(),
            self.reader.bytes_read(),
            self.reader.requests(),
            self.reader.base
        )
    }

    /// The file's content hash (blake3-16, hex). The worker keys its session
    /// cache by this rather than the URL, so two URLs of the same file share the
    /// cache — and it's the stable key a future IndexedDB block store (L3) needs
    /// to survive page reloads.
    pub fn content_hash(&self) -> String {
        self.rete
            .header()
            .content_hash
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect()
    }

    /// See [`sparql_url`] — same query, but over the resident, cached handle.
    /// The incompleteness verdict is PER QUERY: reset the sticky failure flags
    /// first, so one transient fetch failure fails only the query it happened
    /// in — not every later query on this session (failed tiles/chunks are
    /// never cached, so they retry here).
    pub fn query(&self, query: &str, format: &str) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = query_json(&self.rete, query, format, "")?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// As [`query`], with OWL 2 QL entailment on (reason over the ontology while
    /// reading only the bytes the rewritten query touches).
    pub fn query_reasoned(&self, query: &str, format: &str) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = query_json_reasoned(&self.rete, query, format, "")?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// As [`query`], with explicit opt-in toggles — see [`Graph::query_opts`].
    /// With `union_default` on, a lazy remote read may fault the index tiles of
    /// every named graph the union touches (the merge is strictly opt-in).
    pub fn query_opts(
        &self,
        query: &str,
        format: &str,
        reason: bool,
        union_default: bool,
    ) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = query_json_with(&self.rete, query, format, "", reason, union_default)?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// See [`Graph::query_rows`]. The query's reads happen here; each
    /// [`QueryRows::page`] then reads the dictionary chunks of its own terms.
    pub fn query_rows(
        &self,
        query: &str,
        reason: bool,
        union_default: bool,
    ) -> Result<QueryRows, JsValue> {
        self.rete.reset_load_failures();
        let rows = QueryRows::run(&self.rete, query, reason, union_default, true)?;
        incomplete_guard(&self.rete, "query")?;
        Ok(rows)
    }

    /// See [`Graph::partition_plan`]. Reads the dictionary entries of the
    /// query's constants and the resident tile directory — no tile data.
    pub fn partition_plan(&self, query: &str, var: &str) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = partition_plan_json(&self.rete, query, var)?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// See [`Graph::query_partition`].
    pub fn query_partition(
        &self,
        query: &str,
        format: &str,
        reason: bool,
        var: &str,
        keys: Vec<String>,
    ) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let s = query_partition_json(&self.rete, query, format, reason, var, &keys)?;
        incomplete_guard(&self.rete, "query")?;
        Ok(s)
    }

    /// See [`prefix_search`] — over the resident, cached remote handle. Faults the
    /// pyramid (where the label index lives) on the first call, then serves the
    /// search from memory.
    pub fn prefix_search(&self, prefix: &str, limit: usize) -> Result<String, JsValue> {
        prefix_search_json(&self.rete, prefix, limit)
    }

    /// See [`text_search`] — over the resident remote handle. Faults the TEXT_INDEX
    /// token table on the first call, then fetches only the queried posting lists
    /// (never the whole postings blob), serving repeat searches from memory.
    pub fn text_search(
        &self,
        words: Vec<String>,
        contains_prefix: Option<String>,
        limit: usize,
    ) -> Result<String, JsValue> {
        text_search_json(&self.rete, &words, contains_prefix.as_deref(), limit)
    }

    /// See [`Graph::text_index_len`] — read from the resident header, so it
    /// costs no fetch at all. Worth asking before [`RemoteGraph::text_search`]:
    /// it is the size of the section the first search starts pulling over the
    /// wire, so the UI can warn instead of surprising the user.
    pub fn text_index_len(&self) -> f64 {
        self.rete.header().text_index_len as f64
    }

    /// See [`Graph::text_index_token_table_len`] — the figure to quote before
    /// [`RemoteGraph::text_search`], because it is what that first search pulls
    /// over the wire; the section length would promise the user several times
    /// the real bill.
    ///
    /// Unlike [`RemoteGraph::text_index_len`] this is not free: the token
    /// table's length lives in the section's first bytes, not the header, so it
    /// costs ONE ≤10-byte range read (memoized). Trivial next to the table it
    /// measures — but it *is* IO, so the asyncify path must drive this call
    /// rather than treat it as a header field.
    pub fn text_index_token_table_len(&self) -> f64 {
        self.rete.text_index_token_table_len().unwrap_or(0) as f64
    }

    /// See [`Graph::text_search_one`] — over the resident remote handle, with
    /// the same token-table-then-posting-lists fault pattern as
    /// [`RemoteGraph::text_search`]. This is the shape the playground's raw
    /// asyncify glue drives: one string in, one string out, marshaled once.
    pub fn text_search_one(&self, phrase: &str, limit: usize) -> Result<String, JsValue> {
        let words: Vec<String> = phrase.split_whitespace().map(str::to_owned).collect();
        text_search_json(&self.rete, &words, None, limit)
    }

    /// See [`Graph::quoted_triples_signal`] — from the header the open already
    /// holds, so no range read at all.
    pub fn quoted_triples_signal(&self) -> String {
        quoted_triples_signal_json(self.rete.header())
    }

    /// See [`card_url`] — the Dataset Card, over the resident handle's reader
    /// (so the header range it already fetched is served from the block cache).
    pub fn card(&self) -> Result<Option<String>, JsValue> {
        let bytes = rete_core::read_metadata_ranged(&self.reader.view()).map_err(err)?;
        Ok(bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
    }

    /// See [`card_and_build_url`] — card + build record over the resident
    /// handle's reader, still one coalesced range (and served from the block
    /// cache when the header range is already there).
    pub fn card_and_build(&self) -> Result<String, JsValue> {
        let (card, build) =
            rete_core::read_card_and_build_info_ranged(&self.reader.view()).map_err(err)?;
        // Header-only, deliberately: `token_table_bytes` would cost a range read
        // (see [`RemoteGraph::text_index_token_table_len`]), and this call must
        // stay IO-free beyond the card range so the asyncify driver does not
        // have to suspend inside it. A caller that wants the figure asks for it
        // through that export, which the glue does drive.
        let text_index = text_index_json(self.rete.header(), None);
        Ok(card_build_envelope(card, build, text_index))
    }

    /// See [`schema_url`] — the **baked** schema pyramid over the resident
    /// handle. Deliberately never falls back to the scanning [`schema`]: that
    /// would drag the whole remote file across the wire.
    pub fn schema(&self) -> Result<String, JsValue> {
        use serde_json::json;
        let (classes, relations) = rete_core::read_schema_summary_ranged(&self.reader.view())
            .map_err(err)?
            .ok_or_else(|| js_error("file has no schema pyramid"))?;
        let classes: Vec<serde_json::Value> = classes.iter().map(|(c, n)| json!([c, n])).collect();
        let relations: Vec<serde_json::Value> = relations
            .iter()
            .map(|(s, p, o, n)| json!([s, p, o, n]))
            .collect();
        Ok(json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "kind": "schema",
            "classes": classes,
            "relations": relations,
        })
        .to_string())
    }

    /// See [`info`] — read from the resident header, no extra fetch.
    pub fn info(&self) -> String {
        let h = self.rete.header();
        format!(
            r#"{{"schemaVersion":1,"quads":{},"terms":{},"pyramidLevels":{},"namedGraphs":{}}}"#,
            h.quad_count,
            h.term_count,
            h.pyramid_levels,
            // The cheap count (the section's leading varint) — listing every
            // IRI would walk the whole named-graphs directory over the wire.
            self.rete.named_graph_count()
        )
    }

    /// See [`graph_names`].
    pub fn graph_names(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.rete.graph_names()).map_err(err)
    }

    /// See [`shacl_url`] — validate over the resident handle. The default graph
    /// validates lazily against the index (only the shapes' targets are
    /// fetched), so a shape over a huge remote file stays cheap.
    pub fn shacl(
        &self,
        shapes_turtle: &str,
        graph: Option<String>,
        format: &str,
    ) -> Result<String, JsValue> {
        self.rete.reset_load_failures();
        let out = shacl_rete(&self.rete, shapes_turtle, graph.as_deref(), format)?;
        incomplete_guard(&self.rete, "validation")?;
        Ok(out)
    }
}

/// Serialize a label prefix search as `[{"label":…,"subject":…}]`.
fn prefix_search_json(rete: &Rete, prefix: &str, limit: usize) -> Result<String, JsValue> {
    use serde_json::json;
    let hits: Vec<serde_json::Value> = rete
        .prefix_search(prefix, limit)
        .into_iter()
        .map(|(label, subject)| json!({ "label": label, "subject": subject }))
        .collect();
    serde_json::to_string(&hits).map_err(err)
}

/// Serialize a full-text (word/CONTAINS) search as `[{"subject":…}]`.
fn text_search_json(
    rete: &Rete,
    words: &[String],
    contains_prefix: Option<&str>,
    limit: usize,
) -> Result<String, JsValue> {
    use serde_json::json;
    let word_refs: Vec<&str> = words.iter().map(String::as_str).collect();
    let hits: Vec<serde_json::Value> = rete
        .text_search(&word_refs, contains_prefix, limit)
        .into_iter()
        .map(|subject| json!({ "subject": subject }))
        .collect();
    serde_json::to_string(&hits).map_err(err)
}

/// Parse the fixed-size header and report the byte ranges a *progressive*
/// client needs for the overview — the dictionary and the pyramid summary — plus
/// the (large) index range it can skip, and the metadata (Dataset Card) range.
/// JSON: `{ "dictOffset","dictLen","pyramidOffset","pyramidLen","indexOffset",
/// "indexLen","metadataOffset","metadataLen" }`.
/// The browser fetches bytes `0..HEADER_LEN`, calls this, then range-fetches only the
/// dict + pyramid — never the index. A host with its own byte reader (Node over a
/// local file, say) can use `metadataOffset`/`metadataLen` to read just the card.
#[wasm_bindgen]
pub fn header_ranges(head: &[u8]) -> Result<String, JsValue> {
    let h = Header::from_bytes(head).map_err(err)?;
    Ok(format!(
        r#"{{"schemaVersion":1,"dictOffset":{},"dictLen":{},"pyramidOffset":{},"pyramidLen":{},"indexOffset":{},"indexLen":{},"metadataOffset":{},"metadataLen":{}}}"#,
        h.dictionary_offset,
        h.dictionary_len,
        h.pyramid_meta_offset,
        h.pyramid_meta_len,
        h.root_dir_offset,
        h.root_dir_len,
        h.metadata_offset,
        h.metadata_len,
    ))
}

/// Build the coarse-graph overview from a buffer in which only the header,
/// dictionary, and pyramid-summary ranges are populated — the index region may be
/// absent (zero-filled), because the summary path provably never reads it (see
/// the `ranged` test in rete-core). Returns JSON:
/// `{ "round", "communities", "predicateTotals": [["<iri>", count], ...] }`.
/// This is the "overview first, drill down later" payload, fetched in ~3 ranges.
#[wasm_bindgen]
pub fn summary_overview(bytes: &[u8]) -> Result<String, JsValue> {
    let view = SummaryView::open_ranged(&SliceReader::new(bytes))
        .map_err(err)?
        .ok_or_else(|| js_error("file has no pyramid summary"))?;
    serde_json::to_string(&serde_json::json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "round": view.round,
        "communities": view.community_count(),
        "predicateTotals": view.predicate_totals(),
    }))
    .map_err(err)
}

/// Answer a conservative subset of SPARQL exactly from the pyramid summary,
/// without opening the triple index. Unsupported query shapes return an error
/// instead of silently falling back to a full scan.
#[wasm_bindgen]
pub fn progressive_query(bytes: &[u8], query: &str) -> Result<String, JsValue> {
    progressive_query_json(bytes, query).map_err(js_error)
}

/// Native-testable implementation for [`progressive_query`].
pub fn progressive_query_json(bytes: &[u8], query: &str) -> Result<String, String> {
    use serde_json::json;

    let shape = summary_query_shape(query)
        .map_err(|e| e.to_string())?
        .ok_or_else(|| "query is not exactly answerable from the summary".to_string())?;

    let reader = CountingReader::new(SliceReader::new(bytes));
    let file_bytes = reader.len();
    let view = SummaryView::open_ranged(&reader)
        .map_err(|e| e.to_string())?
        .ok_or_else(|| "file has no pyramid summary".to_string())?;

    let value = match shape {
        SummaryQueryShape::PredicateCount {
            predicate,
            variable,
        } => {
            let count = u64::from(view.predicate_total(&predicate));
            select_count_response(
                &variable,
                count,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_count",
                    Some(&predicate),
                    json!(count),
                ),
            )
        }
        SummaryQueryShape::TripleCount { variable } => {
            let count = summary_total(&view);
            select_count_response(
                &variable,
                count,
                progressive_meta(&reader, file_bytes, "triple_count", None, json!(count)),
            )
        }
        SummaryQueryShape::PredicateTotals {
            predicate_variable,
            count_variable,
        } => {
            let totals = view.predicate_totals();
            select_predicate_totals_response(
                &predicate_variable,
                &count_variable,
                &totals,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_totals",
                    None,
                    json!(&totals),
                ),
            )
        }
        SummaryQueryShape::PredicateList { variable } => {
            let predicates = predicate_list(&view);
            select_predicate_list_response(
                &variable,
                &predicates,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_list",
                    None,
                    json!(&predicates),
                ),
            )
        }
        SummaryQueryShape::PredicateDistinctCount { variable } => {
            let count = predicate_count(&view);
            select_count_response(
                &variable,
                count,
                progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_distinct_count",
                    None,
                    json!(count),
                ),
            )
        }
        SummaryQueryShape::TripleExists => {
            let exists = summary_total(&view) > 0;
            json!({
                "schemaVersion": JSON_SCHEMA_VERSION,
                "kind": "ask",
                "boolean": exists,
                "progressive": progressive_meta(
                    &reader,
                    file_bytes,
                    "triple_exists",
                    None,
                    json!(exists),
                ),
            })
        }
        SummaryQueryShape::PredicateExists { predicate } => {
            let exists = view.predicate_total(&predicate) > 0;
            json!({
                "schemaVersion": JSON_SCHEMA_VERSION,
                "kind": "ask",
                "boolean": exists,
                "progressive": progressive_meta(
                    &reader,
                    file_bytes,
                    "predicate_exists",
                    Some(&predicate),
                    json!(exists),
                ),
            })
        }
        _ => return Err("summary query shape is not supported by this WASM build".to_string()),
    };

    serde_json::to_string(&value).map_err(|e| e.to_string())
}

/// Run any SPARQL form (SELECT / ASK / CONSTRUCT / DESCRIBE) and serialize the
/// result for the playground. Returns a JSON string the page parses; a `"kind"`
/// field (`"select"|"ask"|"construct"`) tells the UI how to render it.
///
/// `format` controls the construct serialization and the select fallback:
/// - SELECT → `{ "kind":"select", "vars":[...], "rows":[ {var:value,...} ] }`
///   (`format` is ignored for SELECT — the table view is always available).
/// - ASK → `{ "kind":"ask", "boolean": true|false }`.
/// - CONSTRUCT/DESCRIBE →
///   - `format=="ttl"`    → `{ "kind":"construct", "format":"ttl",    "text": "<turtle>" }`
///   - `format=="jsonld"` → `{ "kind":"construct", "format":"jsonld", "text": "<json-ld>" }`
///   - otherwise (`table`/`json`) → `{ "kind":"construct", "triples": [[s,p,o], ...] }`.
#[wasm_bindgen]
pub fn query(bytes: &[u8], query: &str, format: &str) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    query_json(&rete, query, format, "")
}

/// Prefix-search the label index of an embedded `.rete` image: the subjects whose
/// label starts with `prefix` (case-insensitive), as `[{"label":…,"subject":…}]`,
/// capped at `limit`. Answers from the LABEL_INDEX section, else from an older
/// file's pyramid-meta label block, with no literal scan. Empty array without one.
#[wasm_bindgen]
pub fn prefix_search(bytes: &[u8], prefix: &str, limit: usize) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    prefix_search_json(&rete, prefix, limit)
}

/// Full-text (word/CONTAINS) search over an embedded `.rete` image: the subjects
/// whose literals contain **every** word in `words` (whole-word, case-insensitive
/// — AND), optionally also a word starting with `contains_prefix`, as
/// `[{"subject":…}]`, capped at `limit`. Answers from the TEXT_INDEX section.
/// Empty array when the file has none (`build --text-index`).
#[wasm_bindgen]
pub fn text_search(
    bytes: &[u8],
    words: Vec<String>,
    contains_prefix: Option<String>,
    limit: usize,
) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    text_search_json(&rete, &words, contains_prefix.as_deref(), limit)
}

/// Evaluate any SPARQL form against an open [`Rete`] and serialize the playground
/// JSON envelope (shared by [`query`] and [`sparql_url`]). `extra` is a raw JSON
/// fragment of additional object members appended before the closing brace (e.g.
/// `,"remote":{…}` for [`sparql_url`]); pass `""` for none.
///
/// This writes the JSON **directly into a `String`** rather than building an
/// intermediate `serde_json::Value` tree and stringifying it: on a large SELECT
/// the tree path allocates ~25× the payload (a `BTreeMap` per row + two String
/// clones per cell) and costs more than the query itself; writing direct cuts the
/// serialization peak heap ~13× and the time ~10× (see `rete-bench --query-mem`).
fn query_json(rete: &Rete, query: &str, format: &str, extra: &str) -> Result<String, JsValue> {
    query_json_opt(rete, query, format, extra, false)
}

/// As [`query_json`], but with OWL 2 QL entailment on (the query is rewritten so
/// the answer includes ontology-entailed solutions, computed over the raw data).
fn query_json_reasoned(
    rete: &Rete,
    query: &str,
    format: &str,
    extra: &str,
) -> Result<String, JsValue> {
    query_json_opt(rete, query, format, extra, true)
}

fn query_json_opt(
    rete: &Rete,
    query: &str,
    format: &str,
    extra: &str,
    reason: bool,
) -> Result<String, JsValue> {
    query_json_with(rete, query, format, extra, reason, false)
}

/// The full-options variant: `reason` (OWL 2 QL) and `union_default` (the
/// opt-in union-default-graph mode — a pattern outside GRAPH matches the merge
/// of the default graph and every named graph; see `QueryOpts`).
fn query_json_with(
    rete: &Rete,
    query: &str,
    format: &str,
    extra: &str,
    reason: bool,
    union_default: bool,
) -> Result<String, JsValue> {
    let (out, warnings) = eval_query_with_warnings(
        rete,
        query,
        QueryOpts {
            reason,
            union_default_graph: union_default,
        },
    )
    .map_err(err)?;
    write_with_warnings(&out, &warnings, format, extra)
}

/// The envelope plus, when there are any, the expression type errors FILTER
/// absorbed (CONTAINS on an IRI, …): an optional `warnings` member, present
/// only when there is one, so an envelope without diagnostics is
/// byte-identical to before.
fn write_with_warnings(
    out: &QueryOutput,
    warnings: &[rete_core::QueryWarning],
    format: &str,
    extra: &str,
) -> Result<String, JsValue> {
    if warnings.is_empty() {
        return write_query_json(out, format, extra).map_err(js_error);
    }
    let mut extra = extra.to_string();
    extra.push_str(r#","warnings":"#);
    extra.push_str(&rete_core::warnings_json(warnings));
    write_query_json(out, format, &extra).map_err(js_error)
}

/// [`rete_core::partition_plan`] as JSON.
fn partition_plan_json(rete: &Rete, query: &str, var: &str) -> Result<String, JsValue> {
    let plan = rete_core::partition_plan(rete, query, var).map_err(err)?;
    serde_json::to_string(&plan).map_err(err)
}

/// One chunk of a split query ([`rete_core::eval_query_partitioned`]), as the
/// envelope [`query_json_with`] writes.
fn query_partition_json(
    rete: &Rete,
    query: &str,
    format: &str,
    reason: bool,
    var: &str,
    keys: &[String],
) -> Result<String, JsValue> {
    let opts = QueryOpts {
        reason,
        union_default_graph: false,
    };
    let (out, warnings) =
        rete_core::eval_query_partitioned(rete, query, opts, var, keys).map_err(err)?;
    write_with_warnings(&out, &warnings, format, "")
}

/// Serialize an already-evaluated [`QueryOutput`] into the playground JSON
/// envelope. SELECT / ASK / `CONSTRUCT`-as-triples go through the shared,
/// host-tested `rete_core::results_envelope_json` (the allocation-lean direct
/// writer); a `CONSTRUCT` requested as Turtle / JSON-LD wraps the rendered text
/// (those serializers live here).
///
/// `format` may carry the quoted-triple surface the way `rete export` takes
/// `--quoted-triple-syntax`: `"ttl"` writes RDF 1.2 triple terms
/// `<<( s p o )>>` (the default, as on the CLI), and
/// `"ttl;quotedTripleSyntax=rdf-star"` the RDF-star surface `<<s p o>>`. An
/// `Err` is a refusal or a bad format, never a partly-written document.
fn write_query_json(out: &QueryOutput, format: &str, extra: &str) -> Result<String, String> {
    let mut versioned_extra = format!(r#","schemaVersion":{JSON_SCHEMA_VERSION}"#);
    versioned_extra.push_str(extra);
    if let QueryOutput::Construct(triples) = out {
        let (base, syntax) = construct_format(format)?;
        let text = match base {
            "ttl" => Some(("ttl", to_turtle(triples, syntax)?)),
            "jsonld" => Some(("jsonld", to_jsonld(triples)?)),
            _ => None,
        };
        if let Some((fmt, text)) = text {
            let mut s = String::from(r#"{"kind":"construct","format":""#);
            s.push_str(fmt);
            s.push_str(r#"","text":"#);
            rete_core::push_json_string(&mut s, &text);
            s.push_str(&versioned_extra);
            s.push('}');
            return Ok(s);
        }
    }
    Ok(rete_core::results_envelope_json(out, &versioned_extra))
}

/// Split a CONSTRUCT `format` into its base (`ttl`, `jsonld`, …) and the
/// quoted-triple surface named by an optional `;quotedTripleSyntax=<value>`
/// parameter — the values of `rete export --quoted-triple-syntax`, with the
/// same default, `rdf12`. A parameter rete does not know is refused rather
/// than ignored, so a misspelling cannot silently write the other surface.
fn construct_format(
    format: &str,
) -> Result<(&str, rete_core::ingest::QuotedTripleSurface), String> {
    use rete_core::ingest::QuotedTripleSurface;
    let mut parts = format.split(';');
    let base = parts.next().unwrap_or("").trim();
    let mut syntax = QuotedTripleSurface::Rdf12;
    for param in parts {
        let (key, value) = param.split_once('=').unwrap_or((param, ""));
        match key.trim() {
            "quotedTripleSyntax" => {
                syntax = QuotedTripleSurface::parse(value.trim()).ok_or_else(|| {
                    format!(
                        "unknown quotedTripleSyntax {:?} in format {format:?} (expected \"rdf12\" \
                         or \"rdf-star\")",
                        value.trim()
                    )
                })?;
            }
            other => {
                return Err(format!(
                    "unknown format parameter {other:?} in {format:?} (the one parameter is \
                     quotedTripleSyntax=rdf12|rdf-star)"
                ))
            }
        }
    }
    Ok((base, syntax))
}

/// URL scheme naming a `.rete` that is **already in the page** — a `File` the
/// user picked, or any `Blob` — instead of one on a server.
///
/// A local open used to be `file.arrayBuffer()`: the whole file into a JS
/// `ArrayBuffer`, copied again into wasm linear memory, then `Rete::open`
/// decoding every dictionary chunk up front. That is ~6× the file size resident
/// before a single row is answered, which on wasm32 is a hard wall — so a user
/// could query a 16.8 GB graph over HTTP and not open their own 500 MB file
/// from disk (issue #102).
///
/// The fix is not a second reader. [`XhrRangeReader`] already *is* the lazy
/// reader — length, header-window cache, batching, block cache, polyglot base,
/// progress reporting — and only its bottom transport was HTTP-shaped. A URL
/// with this scheme swaps that transport for `Blob.slice()` +
/// [`web_sys::FileReaderSync`], so every `*_url` entry point ([`sparql_url`],
/// [`card_url`], [`schema_url`], [`RemoteGraph`], …) reads a local file exactly
/// as lazily as a remote one, over the same code.
///
/// `FileReaderSync` is genuinely synchronous and exists **only in workers** —
/// the same constraint sync XHR already imposes on this reader, so it fits the
/// contract with no new suspension points. That is also why the **asyncify**
/// build needs nothing extra: a local read never suspends, so it never reaches
/// `env.rete_fetch_ranges`.
///
/// The blob is registered by JS through [`register_local_file`], which owns the
/// URL→`Blob` map for this wasm instance.
const LOCAL_SCHEME: &str = "rete-local:";

fn is_local_url(url: &str) -> bool {
    url.starts_with(LOCAL_SCHEME)
}

thread_local! {
    /// URL → `Blob` for this wasm instance. Thread-local because a `Blob` is a
    /// JS handle and wasm32 is single-threaded here; the experimental `threads`
    /// build would simply not find a blob registered on another thread, and the
    /// read fails with the message below rather than silently reading nothing.
    static LOCAL_BLOBS: std::cell::RefCell<std::collections::HashMap<String, web_sys::Blob>> =
        std::cell::RefCell::new(std::collections::HashMap::new());
}

/// Register a local `File`/`Blob` under a `rete-local:…` URL, so every `*_url`
/// entry point can range-read it.
///
/// **Worker-only** (the read uses `FileReaderSync`), and the caller mints the
/// URL: a worker can be torn down and rebuilt — the playground does that on a
/// wasm trap, an engine switch, or a phone memory reclaim — and the page must be
/// able to re-register the same file under the same URL so a resident session
/// key stays stable. Re-registering an existing URL replaces the blob.
#[wasm_bindgen]
pub fn register_local_file(url: &str, blob: &web_sys::Blob) -> Result<(), JsValue> {
    if !is_local_url(url) {
        return Err(js_error(format!(
            "a local file URL must start with `{LOCAL_SCHEME}` (got {url})"
        )));
    }
    LOCAL_BLOBS.with(|map| map.borrow_mut().insert(url.to_string(), blob.clone()));
    Ok(())
}

/// Drop a registration made by [`register_local_file`]. Releases this wasm
/// instance's reference to the `Blob`; any open handle over it stops working.
#[wasm_bindgen]
pub fn forget_local_file(url: &str) -> bool {
    LOCAL_BLOBS.with(|map| map.borrow_mut().remove(url).is_some())
}

fn local_blob(url: &str) -> std::io::Result<web_sys::Blob> {
    LOCAL_BLOBS
        .with(|map| map.borrow().get(url).cloned())
        .ok_or_else(|| {
            std::io::Error::other(format!(
                "no local file is registered as {url} — the page must call \
                 register_local_file(url, file) in THIS worker before opening it"
            ))
        })
}

/// The local transport: one `Blob.slice()` per range, read synchronously.
///
/// Batched like the HTTP one (the engine coalesces ranges before it gets here),
/// but with no round trip to pay for — a slice is a view over bytes the browser
/// already has on disk, so the only real cost is the copy of what was asked for.
fn read_local_ranges(url: &str, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
    let (offsets, lens, total) = checked_async_layout(ranges)?;
    if total == 0 {
        return Ok(ranges.iter().map(|_| Vec::new()).collect());
    }
    let blob = local_blob(url)?;
    let size = blob.size();
    let reader = web_sys::FileReaderSync::new().map_err(|e| {
        std::io::Error::other(format!(
            "FileReaderSync is unavailable ({e:?}) — a local .rete is read from a Web Worker only, \
             never the main thread"
        ))
    })?;
    let mut out = Vec::with_capacity(ranges.len());
    for (&offset, &len) in offsets.iter().zip(&lens) {
        let start = offset as f64;
        let end = start + f64::from(len);
        if end > size {
            return Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                format!("range {offset}..{end} is past the end of {url} ({size} bytes)"),
            ));
        }
        let slice = blob
            .slice_with_f64_and_f64(start, end)
            .map_err(|e| std::io::Error::other(format!("Blob.slice failed on {url}: {e:?}")))?;
        let buffer = reader
            .read_as_array_buffer(&slice)
            .map_err(|e| std::io::Error::other(format!("FileReaderSync failed on {url}: {e:?}")))?;
        let bytes = js_sys::Uint8Array::new(&buffer).to_vec();
        if bytes.len() != len as usize {
            return Err(std::io::Error::other(format!(
                "short local read: got {} of {len} bytes at offset {offset} from {url}",
                bytes.len()
            )));
        }
        out.push(bytes);
    }
    // One batch is one "request" to the UI, matching what the asyncify HTTP
    // reader reports for its concurrent batch — so the playground's range
    // inspector and `stats()` describe local and remote reads on one scale.
    report_progress(total, ranges);
    Ok(out)
}

/// HTTP `Range` reader over **synchronous** XMLHttpRequest — the bridge that
/// lets the lazily-faulting `Rete::open_ranged_lazy` run in the browser with
/// the synchronous engine untouched. Browsers permit sync XHR with a binary
/// response **only inside Web Workers**: call [`sparql_url`] from a worker,
/// never the main thread (where the browser throws).
///
/// Also the **local** reader: a `rete-local:` URL (see [`LOCAL_SCHEME`]) swaps
/// the transport for `Blob.slice()` + `FileReaderSync` and changes nothing else.
struct XhrRangeReader {
    url: String,
    len: u64,
    /// The resource's first [`rete_core::HEADER_LEN`] bytes, cached once.
    ///
    /// Opening a `.rete` reads this window several times over — the sync length
    /// probe reads it, [`polyglot_base`](Self::polyglot_base) needs it, and every
    /// `read_*_ranged` helper starts by reading the header — and the bytes cannot
    /// change under us: the file is immutable for the session, and a host that
    /// served different bytes for the same range would already have broken every
    /// other read. So the first reader to pay for it fills this in and the rest
    /// are served from memory, which is what keeps the CARD tier at its
    /// advertised two requests.
    head: std::sync::OnceLock<Vec<u8>>,
    /// The **whole** resource, when the host answered a range request with
    /// `200` and the full body: it ignores `Range` (no `Accept-Ranges`, a proxy
    /// that strips it, a CDN that serves a cached full object). That body has
    /// already crossed the network by the time we see it, and every later range
    /// request would download it again, so it is kept and every read is served
    /// from it — the file then behaves like an in-memory one. Only bodies up to
    /// [`WHOLE_BODY_CAP`] are kept; a larger one is refused with the reason.
    whole: std::sync::OnceLock<Vec<u8>>,
}

/// The largest full-body answer to a range request that [`XhrRangeReader`]
/// keeps and serves reads from. The playground loads a local file whole below
/// 128 MiB; past this cap a range-ignoring host is refused by name rather than
/// risking the wasm32 heap on a body the reader never asked for.
const WHOLE_BODY_CAP: u64 = 256 << 20;

/// The largest remote file [`XhrRangeReader`] reads whole at open, the same
/// 8 MiB as the native reader's `RETE_HTTP_WHOLE_MB` default.
const WHOLE_FILE_MAX: u64 = 8 << 20;

/// One read served from a whole-resource body (see [`XhrRangeReader::whole`]),
/// bounds-checked: the body is whatever the host sent, so a read past its end
/// is a clean error, never a panic.
fn slice_whole(whole: &[u8], offset: u64, len: u64, url: &str) -> std::io::Result<Vec<u8>> {
    let end = offset
        .checked_add(len)
        .filter(|&end| end <= whole.len() as u64)
        .ok_or_else(|| {
            std::io::Error::other(format!(
                "range {offset}+{len} is past the end of the {} bytes {url} sent",
                whole.len()
            ))
        })?;
    Ok(whole[offset as usize..end as usize].to_vec())
}

/// Whether a `200` full body to a range request can stand in for the file:
/// not empty, within [`WHOLE_BODY_CAP`], and — when its first KiB is a `.rete`
/// header — exactly the length that header derives (anything else is a
/// truncated file or a representation whose bytes are not the file's).
#[cfg_attr(feature = "asyncify", allow(dead_code))] // the async build keeps whole bodies on the JS side
fn accept_whole_body(body_len: u64, derived: Option<u64>, url: &str) -> Result<(), String> {
    if body_len == 0 {
        return Err(format!("probe {url}: 200 with an empty body"));
    }
    if body_len > WHOLE_BODY_CAP {
        return Err(format!(
            "the host ignored the Range header and sent all {body_len} bytes of {url} \
             (status 200 instead of 206 Partial Content); a full body over {} MiB is \
             not kept in memory — host the file where HTTP range requests work",
            WHOLE_BODY_CAP >> 20
        ));
    }
    match derived {
        Some(d) if d != body_len => Err(format!(
            "the host ignored the Range header and sent {body_len} bytes of {url}, \
             but the file's own header says it is {d} bytes — the file is truncated, \
             or the host sends a different representation"
        )),
        _ => Ok(()),
    }
}

// Asyncify variant only (feature = "asyncify"): one dedicated async import in
// module "env". The worker provides it as a `Promise.all` of `fetch` over the N
// ranges, writing the spans concatenated into `dst` and returning the total
// bytes. `wasm-opt --asyncify --pass-arg=asyncify-imports@env.rete_fetch_ranges`
// instruments every fn that can reach it to SUSPEND the wasm while the worker
// awaits the fetches, then RESUME — concurrent reads with no SAB / cross-origin
// isolation. Proven in dev/asyncify-wbg-probe (wasm-bindgen × Asyncify).
#[cfg(feature = "asyncify")]
#[link(wasm_import_module = "env")]
extern "C" {
    fn rete_fetch_ranges(
        url_ptr: *const u8,
        url_len: usize,
        offs_ptr: *const u64,
        lens_ptr: *const u32,
        n: usize,
        dst_ptr: *mut u8,
    ) -> usize;
    /// Async length probe (a `bytes=0-0` fetch; reads the total from
    /// `Content-Range`). Writes the u64 length to `out_ptr`, returns 1 on
    /// success. Lets the asyncify build open a file with NO sync XHR at all.
    fn rete_file_len(url_ptr: *const u8, url_len: usize, out_ptr: *mut u64) -> usize;
    /// LEAF panic reporter (deliberately NOT in asyncify-imports): the panic
    /// hook passes the raw `Location` pointers so the host can log file:line
    /// without any formatting — see `__start`.
    fn rete_panic_report(file_ptr: *const u8, file_len: usize, line: u32);
}

fn checked_async_layout(ranges: &[(u64, u64)]) -> std::io::Result<(Vec<u64>, Vec<u32>, usize)> {
    let offs: Vec<u64> = ranges.iter().map(|&(offset, _)| offset).collect();
    let lens: Vec<u32> = ranges
        .iter()
        .map(|&(_, len)| {
            u32::try_from(len).map_err(|_| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("range length {len} exceeds the wasm32 u32 length type"),
                )
            })
        })
        .collect::<std::io::Result<_>>()?;
    let total = lens.iter().try_fold(0usize, |sum, &len| {
        sum.checked_add(len as usize).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "range length sum overflow",
            )
        })
    })?;
    let _total_u32 = u32::try_from(total).map_err(|_| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "range response exceeds the wasm32 address space",
        )
    })?;
    Ok((offs, lens, total))
}

fn split_range_response(
    ranges: &[(u64, u64)],
    dst: Vec<u8>,
    got: usize,
    source: &str,
) -> std::io::Result<Vec<Vec<u8>>> {
    let (_, lens, total) = checked_async_layout(ranges)?;
    if dst.len() != total {
        return Err(std::io::Error::other(format!(
            "async fetch destination has {} bytes, expected {total} for {source}",
            dst.len()
        )));
    }
    if got != total {
        return Err(std::io::Error::other(format!(
            "async fetch returned {got} of {total} bytes for {source}"
        )));
    }

    let mut out = Vec::with_capacity(ranges.len());
    let mut pos = 0usize;
    for len in lens {
        let end = pos + len as usize;
        out.push(dst[pos..end].to_vec());
        pos = end;
    }
    Ok(out)
}

#[cfg(test)]
mod async_range_tests {
    use super::{checked_async_layout, split_range_response};

    #[test]
    fn rejects_a_range_larger_than_the_wasm32_length_type() {
        let error = checked_async_layout(&[(0, u64::from(u32::MAX) + 1)]).unwrap_err();
        assert!(error.to_string().contains("u32"));
    }

    #[test]
    fn rejects_a_total_larger_than_the_wasm32_address_space() {
        let error = checked_async_layout(&[(0, u64::from(u32::MAX)), (0, 1)]).unwrap_err();
        assert!(error.to_string().contains("address space"));
    }

    #[test]
    fn accepts_no_ranges_and_preserves_zero_length_ranges() {
        let (offs, lens, total) = checked_async_layout(&[]).unwrap();
        assert!(offs.is_empty());
        assert!(lens.is_empty());
        assert_eq!(total, 0);

        let (_, lens, total) = checked_async_layout(&[(7, 0), (9, 0)]).unwrap();
        assert_eq!(lens, vec![0, 0]);
        assert_eq!(total, 0);
    }

    #[test]
    fn rejects_a_short_javascript_response() {
        let error = split_range_response(&[(0, 4)], vec![1, 2, 3, 4], 3, "fixture").unwrap_err();
        assert!(error.to_string().contains("returned 3 of 4 bytes"));
    }

    #[test]
    fn only_the_local_scheme_routes_to_the_blob_transport() {
        use super::is_local_url;
        assert!(is_local_url("rete-local:1/mirbase.rete"));
        // Everything the reader has ever been given before must stay on HTTP —
        // a URL that merely CONTAINS the token is not a local file.
        assert!(!is_local_url("https://example.org/rete-local:1/x.rete"));
        assert!(!is_local_url(
            "https://data.graphplaza.com/mirbase/mirbase.rete"
        ));
        assert!(!is_local_url("file:///tmp/x.rete"));
        assert!(!is_local_url(""));
    }

    // A host that ignores Range sends the whole file with a 200. The reader keeps
    // that body and serves reads as slices of it; these pin the two decisions
    // that have no browser in them: which bodies are kept, and the slicing.
    #[test]
    fn a_whole_body_is_kept_only_when_it_can_be_the_file() {
        use super::{accept_whole_body, WHOLE_BODY_CAP};
        let url = "https://host/f.rete";
        assert!(accept_whole_body(4096, Some(4096), url).is_ok());
        // Not a .rete header (a polyglot, say): its own length is all there is.
        assert!(accept_whole_body(4096, None, url).is_ok());
        assert!(accept_whole_body(WHOLE_BODY_CAP, None, url).is_ok());
        let empty = accept_whole_body(0, None, url).unwrap_err();
        assert!(empty.contains("empty body"), "{empty}");
        // Too big to hold: refused by name, with the cap, not kept.
        let big = accept_whole_body(WHOLE_BODY_CAP + 1, Some(WHOLE_BODY_CAP + 1), url).unwrap_err();
        assert!(
            big.contains("ignored the Range header") && big.contains("256 MiB"),
            "{big}"
        );
        // A body that is not the length the file's header derives is not the file.
        let short = accept_whole_body(4000, Some(4096), url).unwrap_err();
        assert!(short.contains("header says it is 4096 bytes"), "{short}");
    }

    #[test]
    fn reads_from_a_whole_body_are_bounds_checked_slices() {
        use super::slice_whole;
        let body: Vec<u8> = (0..=255u8).collect();
        assert_eq!(slice_whole(&body, 10, 3, "u").unwrap(), vec![10, 11, 12]);
        assert_eq!(
            slice_whole(&body, 250, 6, "u").unwrap(),
            vec![250, 251, 252, 253, 254, 255]
        );
        assert!(slice_whole(&body, 0, 0, "u").unwrap().is_empty());
        let past = slice_whole(&body, 250, 7, "u").unwrap_err();
        assert!(
            past.to_string().contains("past the end of the 256 bytes"),
            "{past}"
        );
        // An overflowing offset is an error, never a wrapped index.
        assert!(slice_whole(&body, u64::MAX, 2, "u").is_err());
    }
}

#[cfg(feature = "asyncify")]
impl XhrRangeReader {
    /// Fetch all `ranges` through the async import in one suspend/resume, then
    /// split the concatenated bytes back into per-range buffers.
    fn read_ranges_async(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
        let (offs, lens, total) = checked_async_layout(ranges)?;
        if total == 0 {
            return Ok(ranges.iter().map(|_| Vec::new()).collect());
        }
        let mut dst = vec![0u8; total];
        if offs.len() != ranges.len() || lens.len() != ranges.len() || dst.len() != total {
            return Err(std::io::Error::other(
                "async range layout does not match its allocated buffers",
            ));
        }
        // SAFETY: self.url, offs, and lens own their pointer/length pairs for
        // this call; dst owns exactly total writable bytes. The imported
        // function contract writes at most that concatenated length and returns
        // before any of these allocations leave scope.
        let got = unsafe {
            rete_fetch_ranges(
                self.url.as_ptr(),
                self.url.len(),
                offs.as_ptr(),
                lens.as_ptr(),
                ranges.len(),
                dst.as_mut_ptr(),
            )
        };
        let out = split_range_response(ranges, dst, got, &self.url)?;
        report_progress(total, ranges);
        Ok(out)
    }
}

impl XhrRangeReader {
    /// Probe the resource length. HTTP's own signals are unreliable
    /// cross-origin — a host may advertise the size of a **compressed**
    /// representation in `Content-Length` (GitHub Pages HEADs a 71 MB `.rete`
    /// as its 58 MB gzip; `Content-Encoding` is not CORS-safelisted, so JS
    /// cannot even see the lie) while range requests address the identity
    /// bytes, and may hide `Content-Range` by omitting
    /// `Access-Control-Expose-Headers` (GitHub Pages, Zenodo). So the probe
    /// reads the file's OWN first KiB — the `.rete` header, whose section
    /// directory pins the exact length (issue #95) — and only falls back to
    /// the transport's numbers for a resource that isn't a `.rete`.
    fn open(url: &str) -> Result<Self, JsValue> {
        let r = Self::open_probe(url)?;
        r.fetch_small_whole();
        Ok(r)
    }

    /// A remote file of at most [`WHOLE_FILE_MAX`] is read whole right after
    /// the length probe: one more request, and no later read leaves memory
    /// (2 round trips per query on a 7 MB catalog file, instead of 11–33). A
    /// failure leaves the reader ranged. Local files are never read whole here.
    fn fetch_small_whole(&self) {
        if is_local_url(&self.url) || self.whole.get().is_some() || self.len == 0 {
            return;
        }
        if self.len > WHOLE_FILE_MAX {
            return;
        }
        // The probe's window already holds a file this small: no request.
        if let Some(h) = self.head.get().filter(|h| h.len() as u64 >= self.len) {
            let _ = self.whole.set(h[..self.len as usize].to_vec());
            return;
        }
        if let Ok(body) = self.fetch_at(0, self.len) {
            if body.len() as u64 == self.len {
                let _ = self.whole.set(body);
            }
        }
    }

    fn open_probe(url: &str) -> Result<Self, JsValue> {
        // A LOCAL blob needs no probe at all: its length is a property, not a
        // network fact, and none of the reasons the HTTP probe exists (a
        // compressing host, a hidden Content-Range, a 405 on HEAD) can apply.
        // The header window is faulted on first use like any other range, so
        // opening a local file costs exactly ONE read before the engine starts.
        // Placed above both build variants because it is the same either way.
        if is_local_url(url) {
            // `Blob.size` is an f64: reject NaN/∞/0 explicitly rather than
            // letting `as u64` saturate one of them into a plausible length.
            let len = local_blob(url).map_err(|e| js_error(e.to_string()))?.size();
            if !len.is_finite() || len < 1.0 {
                return Err(js_error(format!("{url} is an empty local file")));
            }
            return Ok(Self {
                url: url.to_string(),
                len: len as u64,
                head: std::sync::OnceLock::new(),
                whole: std::sync::OnceLock::new(),
            });
        }
        // Asyncify build: probe the length via the async import — no sync XHR.
        // The JS side (`__reteDoLen` in scripts/build_playground.py) applies
        // this same derive-from-the-header-then-validate-the-footer strategy.
        #[cfg(feature = "asyncify")]
        {
            let mut len: u64 = 0;
            // SAFETY: url owns url.as_ptr() for exactly url.len() bytes and len
            // owns one writable u64. The import writes only that value and
            // returns before either borrowed allocation leaves scope.
            let ok = unsafe { rete_file_len(url.as_ptr(), url.len(), &mut len as *mut u64) };
            if ok == 0 || len == 0 {
                return Err(js_error(format!("could not determine length of {url}")));
            }
            // The async length probe reads the window on the JS side and only
            // hands back the length, so the first `head_window()` pays for it.
            // (A range-ignoring host's full body is kept on the JS side too:
            // `__reteDoLen` stores it and `__reteDoFetch` slices from it.)
            Ok(Self {
                url: url.to_string(),
                len,
                head: std::sync::OnceLock::new(),
                whole: std::sync::OnceLock::new(),
            })
        }
        #[cfg(not(feature = "asyncify"))]
        {
            // Hugging Face's Space gateway is intermittently flaky on the length
            // probe (a 200 with no Content-Length, a chunked response with neither
            // header, …). A fresh attempt usually lands on a healthy response,
            // so retry a few times before surfacing the error.
            let mut last = format!("could not determine length of {url}");
            for _ in 0..4 {
                match Self::probe_len(url) {
                    Ok(probe) => {
                        // The probe is the open's first read (64 KiB, or the
                        // whole of a small file): report it like any other, so a
                        // query over a file that small still shows its read.
                        let got = probe.whole.as_ref().map_or(probe.head.len(), Vec::len);
                        if got > 0 {
                            report_progress(got, &[(0, got as u64)]);
                        }
                        let cached = std::sync::OnceLock::new();
                        if !probe.head.is_empty() {
                            let _ = cached.set(probe.head);
                        }
                        let whole = std::sync::OnceLock::new();
                        if let Some(body) = probe.whole {
                            let _ = whole.set(body);
                        }
                        return Ok(Self {
                            url: url.to_string(),
                            len: probe.len,
                            head: cached,
                            whole,
                        });
                    }
                    // A refusal that a retry would only repeat — at the cost of
                    // downloading a whole body again — is final.
                    Err(e) if !e.retry => return Err(js_error(e.msg)),
                    Err(e) => last = e.msg,
                }
            }
            Err(js_error(last))
        }
    }

    /// The cached first [`rete_core::HEADER_LEN`] bytes, fetching them once if
    /// nobody has yet. `None` only when the resource cannot be read at all — the
    /// open that follows reports the real error.
    fn head_window(&self) -> Option<&[u8]> {
        if let Some(head) = self.head.get() {
            return Some(head);
        }
        let head = self
            .fetch_at(0, rete_core::v06::FIRST_READ.min(self.len))
            .ok()?;
        let _ = self.head.set(head);
        self.head.get().map(Vec::as_slice)
    }

    /// Where the `.rete` starts inside this resource: `0` for an ordinary file,
    /// and the size of the HTML shell for a **polyglot** — a file that is both a
    /// web page and a graph, whose first bytes carry a `RETE-BASE:` marker naming
    /// the offset. Reads only the header window, which the open that follows
    /// needs anyway and now gets from [`head_window`](Self::head_window).
    fn polyglot_base(&self) -> u64 {
        let Some(head) = self.head_window() else {
            return 0;
        };
        if head.starts_with(&rete_core::MAGIC) {
            return 0;
        }
        rete_core::detect_polyglot_base(head).unwrap_or(0)
    }

    /// A HEAD length probe: `Content-Length` is CORS-safelisted (readable
    /// cross-origin with no `access-control-expose-headers` entry needed).
    /// **Last-resort fallback only**: on a transparently-compressing host this
    /// is the size of the gzip representation, not the file (issue #95), which
    /// is exactly why [`probe_len`](Self::probe_len) prefers the file's own
    /// header. Returns `None` on a non-2xx (some hosts 405 HEAD) or a
    /// missing/zero length.
    #[cfg(not(feature = "asyncify"))]
    fn head_len(url: &str) -> Option<u64> {
        let xhr = web_sys::XmlHttpRequest::new().ok()?;
        xhr.open_with_async("HEAD", url, false).ok()?;
        xhr.send().ok()?;
        let status = xhr.status().ok()?;
        if !(200..300).contains(&status) {
            return None;
        }
        xhr.get_response_header("Content-Length")
            .ok()
            .flatten()
            .and_then(|v| v.parse::<u64>().ok())
            .filter(|&n| n > 0)
    }

    /// One ranged `GET bytes=first-last`. The total is `None` when
    /// `Content-Range` is absent, hidden by CORS (no
    /// `Access-Control-Expose-Headers` entry: GitHub Pages, Zenodo), or
    /// `bytes a-b/*`.
    ///
    /// A `200` is a host that ignored `Range` and sent the whole resource. Its
    /// size is read from the response itself, and the body is copied into wasm
    /// memory only when it is small enough to keep ([`WHOLE_BODY_CAP`]): a
    /// multi-GB body must not be pulled across into the wasm32 heap just to be
    /// refused.
    #[cfg(not(feature = "asyncify"))]
    fn ranged_get(url: &str, first: u64, last: u64) -> Result<Ranged, String> {
        let err = |m: &str| m.to_string();
        let xhr = web_sys::XmlHttpRequest::new().map_err(|_| err("xhr"))?;
        xhr.open_with_async("GET", url, false)
            .map_err(|_| err("open"))?;
        xhr.set_response_type(web_sys::XmlHttpRequestResponseType::Arraybuffer);
        xhr.set_request_header("Range", &format!("bytes={first}-{last}"))
            .map_err(|_| err("range header"))?;
        xhr.send()
            .map_err(|_| format!("probe {url}: network error"))?;
        let status = xhr.status().map_err(|_| err("status"))?;
        // `Content-Range: bytes 0-1023/12345` — the part after `/` is the total.
        let total = xhr
            .get_response_header("Content-Range")
            .ok()
            .flatten()
            .and_then(|v| {
                v.rsplit('/')
                    .next()
                    .and_then(|t| t.trim().parse::<u64>().ok())
            });
        let array = xhr.response().ok().map(|r| js_sys::Uint8Array::new(&r));
        let full_len = array.as_ref().map(|a| u64::from(a.length())).unwrap_or(0);
        if status == 200 && full_len > WHOLE_BODY_CAP {
            // Keep only the requested window (the header parse still wants it).
            let end = (last.saturating_add(1)).min(full_len) as u32;
            let body = array
                .map(|a| a.subarray(first.min(full_len) as u32, end).to_vec())
                .unwrap_or_default();
            return Ok(Ranged {
                status,
                total: None,
                body,
                full_len,
            });
        }
        let body = array.map(|a| a.to_vec()).unwrap_or_default();
        Ok(Ranged {
            status,
            total,
            body,
            full_len,
        })
    }

    /// One length probe. Reads the resource's first KiB over a ranged `GET`;
    /// if that is a `.rete` header, the length is **derived from the file
    /// itself** (`Header::expected_file_len`: sections are back-to-back and
    /// the file ends with the 4-byte `RETE` footer) and, unless a visible
    /// `Content-Range` already confirms it, **validated** by reading those 4
    /// footer bytes — one extra tiny request, only on hosts whose headers are
    /// unusable. Non-`.rete` resources fall back to `Content-Range`, then to
    /// HEAD's `Content-Length` (CORS-safelisted, so readable on a host that
    /// hides `Content-Range`). A 206's `Content-Length` is never believed (it
    /// is the size of the partial body, and taking it as the file size made
    /// every later read "range out of bounds").
    ///
    /// A host that ignores `Range` answers with `200` and the whole file. That
    /// body is kept (up to [`WHOLE_BODY_CAP`]) and the reader serves every read
    /// from it; a larger one is refused, finally, so the open does not retry
    /// and download it again.
    ///
    /// Returns the length **and the head window it read** — the caller keeps it
    /// so polyglot detection costs no second request.
    #[cfg(not(feature = "asyncify"))]
    fn probe_len(url: &str) -> Result<Probe, ProbeFail> {
        let Ranged {
            status,
            total: cr_total,
            body,
            full_len,
        } = Self::ranged_get(url, 0, rete_core::v06::FIRST_READ - 1).map_err(ProbeFail::retry)?;
        // The probe IS the first read: 64 KiB, the header plus — on a 0x06 file
        // — the root, the card and, on a small file, every leaf directory. Kept
        // whole, so every later read inside it costs nothing. (A Range-ignoring
        // host may have sent the whole file here.)
        let head =
            |body: &[u8]| body[..body.len().min(rete_core::v06::FIRST_READ as usize)].to_vec();
        let derived_of = |body: &[u8]| {
            rete_core::Header::from_bytes(body)
                .ok()
                .and_then(|h| h.expected_file_len())
        };
        if status == 200 {
            accept_whole_body(full_len, derived_of(&body), url).map_err(ProbeFail::final_)?;
            // The whole file crossed the network: say so, or the open's byte
            // count would claim a bounded read (docs/architecture.md).
            report_progress(body.len(), &[(0, full_len)]);
            return Ok(Probe {
                len: full_len,
                head: head(&body),
                whole: Some(body),
            });
        }
        if status != 206 {
            return Err(ProbeFail::retry(format!("probe {url}: status {status}")));
        }

        // A `.rete` self-describes its length; that is the only signal a
        // compressing/CORS-hiding host cannot skew (issue #95).
        if let Some(derived) = derived_of(&body) {
            if cr_total == Some(derived) {
                // transport agrees — no extra request
                return Ok(Probe {
                    len: derived,
                    head: head(&body),
                    whole: None,
                });
            }
            // Ask the file: its last 4 bytes are the `RETE` footer. A 206
            // with exactly those bytes proves `derived` addresses real
            // identity bytes; anything else means the file is truncated
            // or the host's ranges don't address the file's bytes.
            let tail = Self::ranged_get(url, derived - 4, derived - 1).map_err(ProbeFail::retry)?;
            if tail.status == 206 && tail.body == rete_core::MAGIC {
                return Ok(Probe {
                    len: derived,
                    head: head(&body),
                    whole: None,
                });
            }
            if tail.status == 200 {
                // Ranges honoured for the head, ignored for the tail: the
                // body is the whole file, so keep it like any other 200.
                accept_whole_body(tail.full_len, Some(derived), url).map_err(ProbeFail::final_)?;
                if tail.body.ends_with(&rete_core::MAGIC) {
                    report_progress(tail.body.len(), &[(0, tail.full_len)]);
                    return Ok(Probe {
                        len: derived,
                        head: head(&body),
                        whole: Some(tail.body),
                    });
                }
            }
            return Err(ProbeFail::retry(format!(
                "length probe disagrees with the file: its header derives \
                 {derived} bytes but the host{} has no RETE footer at \
                 {}..{} (tail probe: status {}) — the file is truncated, \
                 or the host serves ranges over a compressed representation",
                match cr_total {
                    Some(t) => format!(" reports {t} bytes and"),
                    None => String::from(" hides Content-Range and"),
                },
                derived - 4,
                derived,
                tail.status,
            )));
        }
        if body.starts_with(&[0x1f, 0x8b]) {
            // The ranged body is a slice of a GZIP stream: the host applied
            // `Content-Encoding` to the range response, so byte offsets do not
            // address the file's bytes at all. No length can fix that.
            return Err(ProbeFail::retry(format!(
                "the host serves HTTP ranges over a gzip-compressed representation \
                 of {url}; range offsets cannot address the file's bytes"
            )));
        }

        // Not a `.rete` header: fall back to the transport's signals. A POLYGLOT
        // lands here — its byte 0 is `<`, so the header parse above failed — and the
        // head we keep is exactly what `polyglot_base` needs to find the graph.
        if let Some(total) = cr_total {
            return Ok(Probe {
                len: total,
                head: head(&body),
                whole: None,
            });
        }
        if let Some(len) = Self::head_len(url) {
            return Ok(Probe {
                len,
                head: head(&body),
                whole: None,
            });
        }
        Err(ProbeFail::retry(format!(
            "could not determine length of {url}"
        )))
    }
}

/// One ranged response (see [`XhrRangeReader::ranged_get`]).
#[cfg(not(feature = "asyncify"))]
struct Ranged {
    status: u16,
    /// From a readable `Content-Range`; `None` when hidden or absent.
    total: Option<u64>,
    /// The body — for a `200` over [`WHOLE_BODY_CAP`], only the requested window.
    body: Vec<u8>,
    /// The byte length of the whole response body as the browser received it.
    full_len: u64,
}

/// What a length probe learnt: the length, the header window, and — when the
/// host ignored `Range` — the whole file.
#[cfg(not(feature = "asyncify"))]
struct Probe {
    len: u64,
    head: Vec<u8>,
    whole: Option<Vec<u8>>,
}

/// A failed probe, and whether another attempt could change the answer.
#[cfg(not(feature = "asyncify"))]
struct ProbeFail {
    msg: String,
    retry: bool,
}

#[cfg(not(feature = "asyncify"))]
impl ProbeFail {
    fn retry(msg: String) -> Self {
        Self { msg, retry: true }
    }
    fn final_(msg: String) -> Self {
        Self { msg, retry: false }
    }
}

impl RangeReader for XhrRangeReader {
    fn len(&self) -> u64 {
        self.len
    }

    /// The asyncify build fires its batched ranges as one concurrent
    /// `Promise.all` of fetches; the sync build is serial XHR unless the
    /// opt-in COI fetch-worker pool (`globalThis.reteReadMany`) is installed.
    /// 16 matches the pool size and the CLI's thread fan-out.
    fn concurrency(&self) -> usize {
        // A local blob has no round trip to hide, so the planner may probe as
        // freely as the concurrent HTTP readers do — and a wider batch means
        // fewer crossings of the wasm↔JS boundary, which is the only real cost
        // here. Same number as the asyncify reader and the CLI's fan-out.
        // A range-ignoring host's whole body is memory now, the same case.
        if is_local_url(&self.url) || self.whole.get().is_some() {
            return 16;
        }
        #[cfg(feature = "asyncify")]
        {
            16
        }
        #[cfg(not(feature = "asyncify"))]
        {
            let has_pool =
                js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("reteReadMany"))
                    .map(|h| h.is_function())
                    .unwrap_or(false);
            if has_pool {
                16
            } else {
                1
            }
        }
    }

    /// The cached header window (or a whole body) is in memory: a block cache
    /// above this reader serves reads inside it without a fetch.
    fn resident_prefix(&self) -> u64 {
        if self.whole.get().is_some() {
            return self.len;
        }
        self.head.get().map_or(0, |h| h.len() as u64)
    }

    /// Reads that land entirely inside the cached header window are answered
    /// from memory: opening a file re-reads those bytes several times (length
    /// probe, polyglot marker, then every `read_*_ranged` helper's own header
    /// read) and they are immutable for the session, so paying for them once is
    /// the difference between the CARD tier costing two requests and four.
    fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
        if len == 0 {
            return Ok(Vec::new());
        }
        if let Some(whole) = self.whole.get() {
            return slice_whole(whole, offset, len, &self.url);
        }
        if let Some(head) = self.head.get() {
            if let Some(end) = offset.checked_add(len) {
                if end <= head.len() as u64 {
                    return Ok(head[offset as usize..end as usize].to_vec());
                }
            }
        }
        self.fetch_at(offset, len)
    }

    /// Synchronous XHR can't run two requests at once on one thread, so the
    /// engine's sequential faults serialize their round trips. If the page
    /// installs `globalThis.reteReadMany(url, offsets, lens)` — a fetch-worker
    /// pool that fetches the ranges in parallel and blocks (via SAB/Atomics)
    /// until done — use it; it returns one buffer with the spans concatenated
    /// in order, or `null`/throws if it can't (no cross-origin isolation, a
    /// non-206, a short read). On `null` we fall back to the sequential reads
    /// below, which keep the rigorous per-range validation.
    fn read_many(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
        // Local: the whole batch is sliced in one call, in either build.
        if is_local_url(&self.url) {
            return read_local_ranges(&self.url, ranges);
        }
        // Asyncify build: fetch the whole batch concurrently in one suspend.
        #[cfg(feature = "asyncify")]
        {
            self.read_ranges_async(ranges)
        }
        #[cfg(not(feature = "asyncify"))]
        {
            let (_, _, total) = checked_async_layout(ranges)?;
            // The host ignored Range and its whole body is in memory: every
            // range is a slice of it, and the pool would only download it again.
            if self.whole.get().is_some() {
                return ranges.iter().map(|&(o, l)| self.read_at(o, l)).collect();
            }
            if ranges.len() > 1 {
                if let Some(buf) = self.read_many_via_pool(ranges) {
                    if buf.len() == total {
                        return split_range_response(ranges, buf, total, "globalThis.reteReadMany");
                    }
                }
            }
            ranges.iter().map(|&(o, l)| self.read_at(o, l)).collect()
        }
    }
}

/// The raw transport, below the header cache in [`RangeReader::read_at`].
impl XhrRangeReader {
    /// One real range request. Never consults the cached header window — this is
    /// what fills it.
    fn fetch_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
        // Local: one `Blob.slice()` + `FileReaderSync`, in either build.
        if is_local_url(&self.url) {
            return read_local_ranges(&self.url, &[(offset, len)])?
                .pop()
                .ok_or_else(|| std::io::Error::other("local read returned no range"));
        }
        // Asyncify build: a single read is a 1-range async fetch (suspends).
        #[cfg(feature = "asyncify")]
        {
            Ok(self
                .read_ranges_async(&[(offset, len)])?
                .into_iter()
                .next()
                .unwrap())
        }
        #[cfg(not(feature = "asyncify"))]
        {
            let js = |e: JsValue| std::io::Error::other(format!("XHR error: {e:?}"));
            let xhr = web_sys::XmlHttpRequest::new().map_err(js)?;
            xhr.open_with_async("GET", &self.url, false).map_err(js)?;
            xhr.set_response_type(web_sys::XmlHttpRequestResponseType::Arraybuffer);
            let end = offset
                .checked_add(len - 1)
                .ok_or_else(|| std::io::Error::other("HTTP range end overflow"))?;
            xhr.set_request_header("Range", &format!("bytes={offset}-{end}"))
                .map_err(js)?;
            xhr.send().map_err(js)?;
            let status = xhr.status().map_err(js)?;
            // A 200 means the server ignored Range and sent the whole body. It is
            // never mis-sliced as if it were the range: when it is exactly the
            // file (the length the probe established) and small enough to keep,
            // it is kept and this and every later read become slices of it;
            // otherwise it is refused loudly, as the CLI's HttpRangeReader does.
            if status == 200 {
                let array = js_sys::Uint8Array::new(&xhr.response().map_err(js)?);
                let got = u64::from(array.length());
                if got == self.len && accept_whole_body(got, None, &self.url).is_ok() {
                    let whole = array.to_vec();
                    let out = slice_whole(&whole, offset, len, &self.url)?;
                    // Report the whole body: it is what crossed the network.
                    report_progress(whole.len(), &[(0, got)]);
                    let _ = self.whole.set(whole);
                    return Ok(out);
                }
                return Err(std::io::Error::other(format!(
                    "server ignored Range (status 200 with {got} bytes, expected 206 Partial \
                     Content) for {}; the host must support HTTP range requests",
                    self.url
                )));
            }
            if status != 206 {
                return Err(std::io::Error::other(format!(
                    "server ignored Range (status {status}, expected 206 Partial Content) for {}; \
                 the host must support HTTP range requests",
                    self.url
                )));
            }
            let resp = xhr.response().map_err(js)?;
            let mut buf = js_sys::Uint8Array::new(&resp).to_vec();
            if (buf.len() as u64) < len {
                return Err(std::io::Error::other(format!(
                    "short range response: got {} of {len} bytes at offset {offset} from {}",
                    buf.len(),
                    self.url
                )));
            }
            let requested = usize::try_from(len)
                .map_err(|_| std::io::Error::other("range exceeds wasm32 memory"))?;
            buf.truncate(requested);
            // Report this fetch to an optional progress hook so a worker can stream
            // live "N requests · M bytes" updates to the UI *during* the otherwise
            // opaque synchronous query (postMessage works mid-sync-call).
            report_progress(buf.len(), &[(offset, len)]);
            Ok(buf)
        }
    }
}

/// Notify an optional `globalThis.reteProgress(bytes, spans, n)` hook of one
/// completed fetch (the worker forwards it to the UI and keeps a per-query
/// log). `spans` is a JS array of `"start-end"` byte-offset strings — capped at
/// [`PROGRESS_SPAN_CAP`] entries so a huge coalesced batch doesn't build a huge
/// array — and `n` is the TRUE span count. The offsets used to be dropped here
/// (only the byte count was forwarded), which left the playground's
/// "Range requests" inspector promising a `start-end` column it could never
/// fill. A no-op when unset.
const PROGRESS_SPAN_CAP: usize = 256;

fn report_progress(bytes: usize, ranges: &[(u64, u64)]) {
    let g = js_sys::global();
    if let Ok(f) = js_sys::Reflect::get(&g, &JsValue::from_str("reteProgress")) {
        if let Ok(f) = f.dyn_into::<js_sys::Function>() {
            let spans = js_sys::Array::new();
            for &(offset, len) in ranges.iter().take(PROGRESS_SPAN_CAP) {
                let end = offset + len.saturating_sub(1);
                spans.push(&JsValue::from_str(&format!("{offset}-{end}")));
            }
            let _ = f.call3(
                &JsValue::NULL,
                &JsValue::from_f64(bytes as f64),
                &spans.into(),
                &JsValue::from_f64(ranges.len() as f64),
            );
        }
    }
}

#[cfg(not(feature = "asyncify"))]
impl XhrRangeReader {
    /// Call the optional JS parallel-fetch hook. Returns the concatenated span
    /// bytes on full success, or `None` if the hook is absent, threw, or
    /// returned anything other than a `Uint8Array` (→ sequential fallback).
    fn read_many_via_pool(&self, ranges: &[(u64, u64)]) -> Option<Vec<u8>> {
        let global = js_sys::global();
        let hook = js_sys::Reflect::get(&global, &JsValue::from_str("reteReadMany")).ok()?;
        if !hook.is_function() {
            return None;
        }
        let hook = hook.dyn_into::<js_sys::Function>().ok()?;
        let (_, checked_lens, _) = checked_async_layout(ranges).ok()?;
        let count = u32::try_from(ranges.len()).ok()?;
        let offs = js_sys::Float64Array::new_with_length(count);
        let lens = js_sys::Float64Array::new_with_length(count);
        const MAX_SAFE_JS_INTEGER: u64 = (1_u64 << 53) - 1;
        for (i, (&(offset, _), &len)) in ranges.iter().zip(&checked_lens).enumerate() {
            if offset > MAX_SAFE_JS_INTEGER {
                return None;
            }
            let index = u32::try_from(i).ok()?;
            offs.set_index(index, offset as f64);
            lens.set_index(index, f64::from(len));
        }
        let res = hook
            .call3(&JsValue::NULL, &JsValue::from_str(&self.url), &offs, &lens)
            .ok()?;
        if res.is_null() || res.is_undefined() {
            return None;
        }
        Some(js_sys::Uint8Array::new(&res).to_vec())
    }
}

/// The browser's [`rete_core::ServiceClient`]: a `SERVICE <endpoint> { … }`
/// block POSTs its sub-query to the endpoint over synchronous XHR (worker-only,
/// like every other read here — the engine is synchronous) and rete-core parses
/// the SPARQL JSON results. The endpoint must send CORS headers (the public
/// ones — Wikidata, DBpedia — do).
struct XhrServiceClient;

impl rete_core::ServiceClient for XhrServiceClient {
    fn query(&self, endpoint: &str, query: &str) -> Result<Vec<rete_core::Binding>, String> {
        let e = |m: &str| format!("{endpoint}: {m}");
        let xhr = web_sys::XmlHttpRequest::new().map_err(|_| e("xhr"))?;
        xhr.open_with_async("POST", endpoint, false)
            .map_err(|_| e("open"))?;
        xhr.set_request_header("Content-Type", "application/x-www-form-urlencoded")
            .map_err(|_| e("header"))?;
        xhr.set_request_header("Accept", "application/sparql-results+json")
            .map_err(|_| e("header"))?;
        let body = format!(
            "query={}",
            String::from(js_sys::encode_uri_component(query))
        );
        xhr.send_with_opt_str(Some(&body))
            .map_err(|_| e("network error (endpoint down or no CORS)"))?;
        let status = xhr.status().map_err(|_| e("status"))?;
        if !(200..300).contains(&status) {
            return Err(e(&format!("HTTP {status}")));
        }
        let text = xhr
            .response_text()
            .map_err(|_| e("read"))?
            .unwrap_or_default();
        rete_core::parse_sparql_json_results(&text).map_err(|m| e(&m))
    }
}

/// Run a SPARQL query against a **remote `.rete` URL**, fetching only the
/// byte ranges the query needs: header, dictionary chunk directories, tile
/// directories, then just the touched chunks and tiles (full scans coalesce
/// adjacent tiles into batched range reads). Returns the same JSON envelope
/// as [`query`], plus `"remote": { "fileLength", "bytes", "requests" }` —
/// how little of the file the query actually pulled.
///
/// **Worker-only.** This uses synchronous XHR (the engine is synchronous and
/// wasm cannot block on `fetch`); browsers allow that off the main thread
/// only, so call it from a Web Worker. A failed range fetch mid-query is an
/// error, never a silently incomplete result. The host must answer `Range`
/// requests with `206` (and send CORS headers if cross-origin).
/// Open a remote `.rete` lazily over HTTP range reads, returning the counting
/// reader (for byte/request stats) and the `Rete`. The seam every `*_url`
/// task shares with [`sparql_url`].
/// Auto-tune the block-cache size from the FILE SIZE — known for free at open
/// from the `Content-Range` of the single `bytes=0-0` request (one byte, no
/// download; it's what `stats().fileLength` reports). Remote reads are
/// round-trip-bound, so a bigger block means far fewer requests; benchmarked on
/// wikidata-1GB: 64 KiB = 262 reqs / 63 s, 256 KiB = 83 / 27 s, 512 KiB = 51 / 19 s.
/// Bigger files (bigger working sets + dictionaries) get bigger blocks as
/// multiples of the 64 KiB `DEFAULT_BLOCK`; small files keep over-fetch modest.
/// Per-query override comes via `RemoteGraph::with_block` (the Settings control).
fn auto_block(len: u64) -> u64 {
    const MB: u64 = 1 << 20;
    let mult: u64 = if len > 100 * MB {
        8 // 512 KiB — chebi, wikidata-100mb, ohm-full, wikidata-1GB, causenet
    } else if len > 10 * MB {
        4 // 256 KiB
    } else {
        2 // 128 KiB — small remotes (chemotion, getty-ulan)
    };
    mult * DEFAULT_BLOCK
}

/// The physical range reader behind a remote open, plus the **base offset** of
/// the `.rete` inside the resource.
///
/// For an ordinary `.rete` the base is `0` and every method is a pass-through.
/// For a **polyglot** — one object that is simultaneously an HTML page and a
/// graph, byte 0 being `<` — the base is where the appended `.rete` starts, read
/// from the `RETE-BASE:` marker the page carries in its first
/// [`rete_core::HEADER_LEN`] bytes (written by
/// `experiments/polyglot/build_polyglot.py`). Every graph read then goes through
/// [`RemoteReader::view`], an [`OffsetReader`] that makes the embedded graph read
/// as if it began at byte 0 — so a polyglot is range-read exactly as lazily as a
/// plain file instead of being downloaded whole.
///
/// [`len`](Self::len) reports the **graph's** length (the shell excluded), while
/// `bytes_read`/`requests` stay the true wire cost, shell probe included.
#[derive(Clone)]
struct RemoteReader {
    counting: std::sync::Arc<CountingReader<XhrRangeReader>>,
    base: u64,
}

impl RemoteReader {
    /// Open `url` and resolve its polyglot base — free on the sync build, where
    /// the length probe has already read the header window.
    fn open(url: &str) -> Result<Self, JsValue> {
        let xhr = XhrRangeReader::open(url)?;
        let base = xhr.polyglot_base();
        Ok(Self {
            counting: std::sync::Arc::new(CountingReader::new(xhr)),
            base,
        })
    }

    /// The graph-relative reader: absolute for a plain `.rete`, shifted past the
    /// HTML shell for a polyglot.
    fn view(&self) -> OffsetReader<std::sync::Arc<CountingReader<XhrRangeReader>>> {
        OffsetReader::new(self.counting.clone(), self.base)
    }

    /// Byte length of the embedded `.rete` (not of the enclosing resource).
    fn len(&self) -> u64 {
        self.counting.len().saturating_sub(self.base)
    }

    fn bytes_read(&self) -> u64 {
        self.counting.bytes_read()
    }

    fn requests(&self) -> u64 {
        self.counting.requests()
    }
}

/// The default memory budget of a lazily opened file, in MiB.
const DEFAULT_MEMORY_BUDGET_MB: u32 = 1024;

/// The memory budget of the files opened from now on, in MiB; 0 = no cap.
static MEMORY_BUDGET_MB: std::sync::atomic::AtomicU32 =
    std::sync::atomic::AtomicU32::new(DEFAULT_MEMORY_BUDGET_MB);

/// Set the memory budget of every remote (lazily read) file opened from now
/// on, in MiB. It caps the caches of decoded dictionary chunks, decoded index
/// tiles and raw file blocks; what is evicted is read again when a query
/// touches it, so the budget trades speed for memory and never changes an
/// answer. `0` removes the cap. The default is 1024.
///
/// A wasm32 heap ends at 4 GiB and never shrinks. Without a cap a query over
/// ten million rows of a 2.5 GB file kept 2.3 GB of decoded chunks and tiles,
/// the next one added 1.7 GB of its own, and the engine trapped
/// (`unreachable`) at the ceiling. The cap does not cover a query's own
/// working state (a hash join's build side, `GROUP BY` groups).
#[wasm_bindgen]
pub fn set_memory_budget_mb(mb: u32) {
    MEMORY_BUDGET_MB.store(mb, std::sync::atomic::Ordering::Relaxed);
}

/// The memory budget files are opened with, in MiB (0 = no cap): see
/// [`set_memory_budget_mb`].
#[wasm_bindgen]
pub fn memory_budget_mb() -> u32 {
    MEMORY_BUDGET_MB.load(std::sync::atomic::Ordering::Relaxed)
}

/// The budget in bytes, `None` when there is no cap.
fn memory_budget() -> Option<u64> {
    match memory_budget_mb() {
        0 => None,
        mb => Some(u64::from(mb) << 20),
    }
}

fn open_url(url: &str) -> Result<(RemoteReader, Rete), JsValue> {
    // `reader` counts the PHYSICAL fetches; a read-through block cache above it
    // turns the query's scattered range reads into a few aligned block fetches
    // (and reuses them) — working over any single-range backend (S3, a CDN),
    // not just a multi-range gateway. The block fetches still go through
    // `read_many`, so a multi-range host coalesces them further. The block size
    // is auto-tuned from the file size (known at open, no download).
    let reader = RemoteReader::open(url)?;
    let budget = memory_budget();
    let split = rete_core::split_memory_budget(budget.unwrap_or(u64::MAX));
    let cached = std::sync::Arc::new(
        BlockCacheReader::new(reader.counting.clone(), auto_block(reader.len()))
            .with_cache_cap(split.block_cache.min(rete_core::DEFAULT_CACHE_CAP)),
    );
    // The offset shim sits ABOVE the cache so blocks stay aligned to the
    // resource's absolute offsets (a plain file's base is 0 — a no-op).
    let mut rete = Rete::open_ranged_lazy(OffsetReader::new(cached, reader.base)).map_err(err)?;
    // The caches of decoded chunks and tiles get their share of the budget.
    // There is no disk to spill a `COUNT(DISTINCT)` to here: that stays in
    // memory whatever the budget.
    rete.set_memory_budget(budget);
    rete.set_spill_threshold(None);
    // SERVICE blocks federate to remote SPARQL endpoints over sync XHR.
    rete.set_service_client(Box::new(XhrServiceClient));
    Ok((reader, rete))
}

/// Turn a partial lazy fetch into a hard error: a `*_url` task must never
/// return a result computed over silently-incomplete data.
fn incomplete_guard(rete: &Rete, what: &str) -> Result<(), JsValue> {
    if rete.index_incomplete() {
        return Err(js_error(format!(
            "a range fetch failed mid-{what}; refusing to return incomplete results"
        )));
    }
    Ok(())
}

/// Triple-pattern provenance over a **remote** `.rete` URL (lazy range reads):
/// which permutation/section/byte-ranges answer the pattern. Worker-only.
#[wasm_bindgen]
pub fn why_url(
    url: &str,
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let out = why_triples_rete(
        &rete,
        subject.as_deref(),
        predicate.as_deref(),
        object.as_deref(),
    )
    .map_err(js_error)?;
    incomplete_guard(&rete, "query")?;
    let _ = reader;
    Ok(out)
}

/// Provenance over an already-open `Rete` (shared by [`why_triples`] in-memory
/// and [`why_url`] remote).
fn why_triples_rete(
    rete: &Rete,
    subject: Option<&str>,
    predicate: Option<&str>,
    object: Option<&str>,
) -> Result<String, String> {
    use serde_json::json;
    let results = rete.query_with_provenance(subject, predicate, object);
    let out = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "pattern": { "subject": subject, "predicate": predicate, "object": object },
        "resultCount": results.len(),
        "results": results.iter().map(provenance_json).collect::<Vec<_>>(),
    });
    serde_json::to_string(&out).map_err(|e| e.to_string())
}

#[wasm_bindgen]
pub fn sparql_url(url: &str, query: &str, format: &str) -> Result<String, JsValue> {
    // Use the block-caching `open_url` seam so scattered range reads within this
    // one query that land in the same 64 KiB block fetch it once. (The resident
    // `RemoteGraph` extends this reuse across queries.)
    let (reader, rete) = open_url(url)?;
    let file_length = reader.len();
    // Evaluate first (this is what faults tiles), then refuse incomplete results.
    let out = eval_query(&rete, query).map_err(err)?;
    if rete.index_incomplete() {
        return Err(js_error(
            "a range fetch failed mid-query; refusing to return incomplete results",
        ));
    }
    // The `remote` member's values are plain numbers — no escaping needed.
    let extra = format!(
        r#","remote":{{"fileLength":{},"bytes":{},"requests":{}}}"#,
        file_length,
        reader.bytes_read(),
        reader.requests(),
    );
    write_query_json(&out, format, &extra).map_err(js_error)
}

/// Evaluate a SELECT with the **community-split strategy**: every basic graph
/// pattern is decomposed into subject stars, each star is evaluated per
/// pyramid community (the members pushed in as a VALUES binding), and the
/// stars are recombined with global hash joins — so multi-hop joins work and
/// cross-community solutions survive. FILTER / UNION / OPTIONAL / MINUS
/// recurse; paths and GRAPH blocks evaluate globally inside the split; GROUP
/// BY / ORDER BY / LIMIT / DISTINCT run once on the merged rows. Answers are
/// identical to [`query`]'s. Refused only when nothing in the query can
/// split (no BGP with a variable subject) or for FROM / FROM NAMED. JSON:
/// the SELECT envelope plus `"communities": [{ "community", "subjects",
/// "rows" }, …]` (rows contributed per community across all split stars).
#[wasm_bindgen]
pub fn query_communities(
    bytes: &[u8],
    query: &str,
    round: Option<usize>,
) -> Result<String, JsValue> {
    query_communities_value(&open(bytes)?, query, round)
}

/// [`query_communities`] against an already-open [`Rete`] (shared with [`Graph`]).
fn query_communities_value(
    rete: &Rete,
    query: &str,
    round: Option<usize>,
) -> Result<String, JsValue> {
    use serde_json::{json, Map, Value};
    let (mut vars, solutions, partials) =
        eval_select_communities(rete, query, round).map_err(err)?;
    if vars.is_empty() {
        let mut seen = std::collections::BTreeSet::new();
        for s in &solutions {
            for k in s.keys() {
                if seen.insert(k.clone()) {
                    vars.push(k.clone());
                }
            }
        }
    }
    let rows: Vec<Value> = solutions
        .iter()
        .map(|s| {
            let mut obj = Map::new();
            for var in &vars {
                if let Some(term) = s.get(var) {
                    obj.insert(var.clone(), Value::String(term.clone()));
                }
            }
            Value::Object(obj)
        })
        .collect();
    let communities: Vec<Value> = partials
        .iter()
        .map(|p| json!({ "community": p.community, "subjects": p.subjects, "rows": p.rows }))
        .collect();
    serde_json::to_string(&json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": vars,
        "rows": rows,
        "communities": communities,
    }))
    .map_err(err)
}

/// The file's byte layout, for the playground's byte-map view. JSON:
/// `{ "fileLength": N, "segments": [ { "kind", "label", "offset", "len" } ] }`
/// — segments sorted by offset; uncovered bytes are container framing.
#[wasm_bindgen]
pub fn file_layout(bytes: &[u8]) -> Result<String, JsValue> {
    use serde_json::json;
    let rete = open(bytes)?;
    let segments: Vec<serde_json::Value> = rete
        .file_layout()
        .iter()
        .map(|s| json!({ "kind": s.kind, "label": s.label, "offset": s.offset, "len": s.len }))
        .collect();
    serde_json::to_string(&json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "fileLength": bytes.len(),
        "segments": segments,
    }))
    .map_err(err)
}

/// The full community pyramid as a tree — the "cluster of clusters" view.
/// Per dendrogram round (index 0 = finest, last = coarsest), every community
/// with its member-node count, triple count (triples whose subject belongs to
/// it), and its parent community at the next-coarser round (`null` at the
/// top). JSON:
/// `{ "rounds": N, "levels": [ [ { "id", "nodes", "triples", "parent" } ] ] }`.
#[wasm_bindgen]
pub fn pyramid_tree(bytes: &[u8]) -> Result<String, JsValue> {
    pyramid_tree_value(&open(bytes)?)
}

/// [`pyramid_tree`] against an already-open [`Rete`] (shared with [`Graph`]).
fn pyramid_tree_value(rete: &Rete) -> Result<String, JsValue> {
    use serde_json::json;
    use std::collections::BTreeMap;
    let dict = rete.dictionary();
    let ids = rete.match_ids((None, None, None));
    let g = project_graph(dict, &ids);
    let dend = build_dendrogram(&g);
    let rounds = dend.rounds();
    if rounds == 0 {
        return serde_json::to_string(&json!({
            "schemaVersion": JSON_SCHEMA_VERSION,
            "rounds": 0,
            "levels": [],
        }))
        .map_err(err);
    }
    let n = g.node_count();
    let mut levels = Vec::with_capacity(rounds);
    for r in 0..rounds {
        let mut nodes_per: BTreeMap<usize, usize> = BTreeMap::new();
        let mut rep: BTreeMap<usize, usize> = BTreeMap::new();
        for node in 0..n {
            let c = dend.base_community(node, r);
            *nodes_per.entry(c).or_default() += 1;
            rep.entry(c).or_insert(node);
        }
        let mut triples_per: BTreeMap<usize, usize> = BTreeMap::new();
        for &(s, _, _) in &ids {
            let c = dend.base_community(dict.subject_node(s) as usize, r);
            *triples_per.entry(c).or_default() += 1;
        }
        let level: Vec<serde_json::Value> = nodes_per
            .iter()
            .map(|(&c, &nodes)| {
                let parent = if r + 1 < rounds {
                    json!(dend.base_community(rep[&c], r + 1))
                } else {
                    json!(null)
                };
                json!({
                    "id": c,
                    "nodes": nodes,
                    "triples": triples_per.get(&c).copied().unwrap_or(0),
                    "parent": parent,
                })
            })
            .collect();
        levels.push(level);
    }
    serde_json::to_string(&json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "rounds": rounds,
        "levels": levels,
    }))
    .map_err(err)
}

/// Recompute the Louvain community decomposition and report, per community, its
/// member-subject count and triple count. Powers the "split by community"
/// strategy view in the playground. JSON:
/// `[{ "community": N, "size": M, "triples": K }, ...]`, ordered by community id.
///
/// `round` selects the dendrogram granularity; `None` chooses the round for the
/// default tile budget (the same choice the native build makes).
#[wasm_bindgen]
pub fn communities(bytes: &[u8], round: Option<usize>) -> Result<String, JsValue> {
    use std::collections::HashSet;
    let rete = open(bytes)?;
    let dict = rete.dictionary();
    let ids = rete.match_ids((None, None, None));
    let g = project_graph(dict, &ids);
    let dend = build_dendrogram(&g);
    let round =
        round.unwrap_or_else(|| choose_round_for_budget(dict, &ids, &dend, DEFAULT_TILE_BUDGET));
    let tiles = tile_by_community(dict, &ids, &dend, round);
    let arr: Vec<serde_json::Value> = tiles
        .iter()
        .map(|t| {
            let members: HashSet<u32> = t.triples.iter().map(|&(s, _, _)| s).collect();
            serde_json::json!({
                "community": t.community,
                "size": members.len(),
                "triples": t.triples.len(),
            })
        })
        .collect();
    serde_json::to_string(&arr).map_err(err)
}

/// Multi-source transitive reachability over one relation, run **serially**
/// (the browser engine is single-threaded — the native CLI's
/// `rete reach --parallel` fans one task per seed). For each seed, the set of
/// nodes it transitively reaches; with `reverse`, the set that reaches it
/// (impact analysis).
///
/// - `predicate` — the relation IRI token, e.g. `<http://ex/dependsOn>`.
/// - `seeds` — a JSON array of seed IRI tokens (e.g. `["<http://ex/app>"]`); a
///   bare single IRI string is also accepted.
/// - `reverse` — traverse edges backward ("who reaches the seed?").
///
/// Returns a JSON array, one entry per seed in input order:
/// `[{ "seed":"<iri>", "reached":["<iri>",...], "count":N }, ...]`.
/// A seed not present in the graph yields `{ "seed":"...", "error":"not in graph" }`
/// instead of failing the whole call.
#[wasm_bindgen]
pub fn reach(bytes: &[u8], predicate: &str, seeds: &str, reverse: bool) -> Result<String, JsValue> {
    reach_rete(&open(bytes)?, predicate, seeds, reverse)
}

/// Multi-source reachability over a **remote** `.rete` URL (lazy HTTP range
/// reads): builds adjacency for `predicate` by faulting only that predicate's
/// tiles, then BFS from each seed. Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn reach_url(
    url: &str,
    predicate: &str,
    seeds: &str,
    reverse: bool,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let out = reach_rete(&rete, predicate, seeds, reverse)?;
    incomplete_guard(&rete, "reach")?;
    let _ = reader;
    Ok(out)
}

fn reach_rete(rete: &Rete, predicate: &str, seeds: &str, reverse: bool) -> Result<String, JsValue> {
    use std::collections::HashMap;
    let dict = rete.dictionary();

    // Accept either a JSON array of IRIs or a single bare IRI string.
    let seed_iris: Vec<String> = match serde_json::from_str::<Vec<String>>(seeds) {
        Ok(v) => v,
        Err(_) => match serde_json::from_str::<String>(seeds) {
            Ok(s) => vec![s],
            Err(_) => vec![seeds.to_string()],
        },
    };

    // Adjacency in unified node space for the chosen direction.
    let adj: HashMap<u32, Vec<u32>> = if reverse {
        let mut m: HashMap<u32, Vec<u32>> = HashMap::new();
        for (s, o) in rete.predicate_pairs(predicate) {
            m.entry(o).or_default().push(s); // who points at o
        }
        m
    } else {
        build_adjacency(rete, predicate)
    };

    // Resolve known seeds to node ids; remember unknowns to report inline.
    let mut known_idx: Vec<usize> = Vec::new();
    let mut seed_nodes: Vec<u32> = Vec::new();
    for (i, iri) in seed_iris.iter().enumerate() {
        if let Some(n) = dict.node_of_term(iri) {
            known_idx.push(i);
            seed_nodes.push(n);
        }
    }

    let sets = batch_reach_serial(&adj, &seed_nodes);

    // Map known-seed position -> its reach set, then assemble in input order.
    let mut by_input: HashMap<usize, &std::collections::BTreeSet<u32>> = HashMap::new();
    for (k, &i) in known_idx.iter().enumerate() {
        by_input.insert(i, &sets[k]);
    }

    let arr: Vec<serde_json::Value> = seed_iris
        .iter()
        .enumerate()
        .map(|(i, iri)| match by_input.get(&i) {
            Some(set) => {
                let reached: Vec<String> = set.iter().filter_map(|&n| dict.node_term(n)).collect();
                serde_json::json!({
                    "seed": iri,
                    "count": reached.len(),
                    "reached": reached,
                })
            }
            None => serde_json::json!({ "seed": iri, "error": "not in graph" }),
        })
        .collect();

    serde_json::to_string(&arr).map_err(err)
}

/// Validate a `.rete` graph against SHACL Core shapes written in Turtle.
///
/// The default graph is validated unless `graph` names a dataset graph IRI.
/// `format` is one of:
/// - `"json"`: structured validation report from rete-core
/// - `"ttl"`: Turtle validation report
/// - anything else: compact text report
///
/// A non-conformant graph returns a report; it is not a JS exception. Exceptions
/// are reserved for parse/open errors.
#[wasm_bindgen]
pub fn shacl(
    bytes: &[u8],
    shapes_turtle: &str,
    graph: Option<String>,
    format: &str,
) -> Result<String, JsValue> {
    shacl_rete(&open(bytes)?, shapes_turtle, graph.as_deref(), format)
}

/// Validate a **remote** `.rete` graph (lazy HTTP range reads) against SHACL
/// Core shapes written in Turtle. Validating the **default** graph routes every
/// lookup as a range read ([`ReteGraph`]), so a targeted shape faults only the
/// tiles holding its targets — not the whole graph. A named graph (`graph`) still
/// materializes (the routed view is default-graph only). Worker-only (sync XHR).
#[wasm_bindgen]
pub fn shacl_url(
    url: &str,
    shapes_turtle: &str,
    graph: Option<String>,
    format: &str,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let out = shacl_rete(&rete, shapes_turtle, graph.as_deref(), format)?;
    incomplete_guard(&rete, "validation")?;
    let _ = reader;
    Ok(out)
}

fn shacl_rete(
    rete: &Rete,
    shapes_turtle: &str,
    graph: Option<&str>,
    format: &str,
) -> Result<String, JsValue> {
    let shapes = ShaclShapes::parse_turtle(shapes_turtle).map_err(err)?;
    // Default graph: validate over the index directly (lazy — fetch only targets).
    // A named graph still materializes (ReteGraph views the default graph only).
    let report = match graph {
        None => validate_shacl(&ReteGraph::new(rete), &shapes),
        Some(g) => validate_shacl(&DataGraph::from_rete(rete, Some(g)), &shapes),
    };
    Ok(format_report(&report, format))
}

fn shacl_over(data: DataGraph, shapes_turtle: &str, format: &str) -> Result<String, JsValue> {
    let shapes = ShaclShapes::parse_turtle(shapes_turtle).map_err(err)?;
    Ok(format_report(&validate_shacl(&data, &shapes), format))
}

fn format_report(report: &ValidationReport, format: &str) -> String {
    match format {
        "json" => report.to_json(),
        "ttl" => report.to_turtle(),
        _ => format_shacl_text(report),
    }
}

/// **Chain a SPARQL subset, then SHACL over it.** Evaluates a `CONSTRUCT` over
/// the remote `.rete` (touching only the tiles its patterns need), then validates
/// the resulting subgraph against the Turtle `shapes`. Where [`shacl_url`] selects
/// by *shape target* (validate every Person…), this selects by an explicit
/// `CONSTRUCT` — "validate just the slice this query carves out, in place".
/// Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn shacl_construct_url(
    url: &str,
    construct: &str,
    shapes_turtle: &str,
    format: &str,
) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let triples = match eval_query(&rete, construct).map_err(err)? {
        QueryOutput::Construct(t) => t,
        _ => {
            return Err(js_error(
                "the subset query must be a CONSTRUCT — it builds the subgraph SHACL validates",
            ))
        }
    };
    incomplete_guard(&rete, "query")?;
    let out = shacl_over(DataGraph::from_triples(triples), shapes_turtle, format)?;
    let _ = reader;
    Ok(out)
}

// --- OWL RL / RDFS coherence checking ----------------------------------------
//
// The reasoner (`rete_core::reason`) is already slice-shaped, so these are near
// twins of the SHACL functions above: `reason`/`reason_url` materialize the whole
// graph (Tier-2, the complete check), while `reason_construct_url` validates only
// the slice a CONSTRUCT selects (Tier-1, selective range reads).

/// The fixed, **selective** coherence subgraph for [`reason_construct_url`]
/// (Tier-1). A UNION of constant-predicate branches: each routes to exactly one
/// predicate's index tiles, so the client faults only `rdf:type` + the class/
/// equality T-Box predicates over one warm lazy cache — not the whole graph.
///
/// The T-Box branches are MANDATORY: the reasoner finds disjoint-class clashes
/// only *after* `subClassOf` type-propagation, so omitting `subClassOf`/
/// `disjointWith`/`sameAs` would silently miss propagation-dependent
/// contradictions. Property-characteristic axioms (Functional/Symmetric/
/// Transitive) ride inside the `rdf:type` slice. Instance-level
/// FunctionalProperty / domain / range clashes need the property's own
/// assertions — use [`reason_url`] (Tier-2) for those.
pub const COHERENCE_CONSTRUCT: &str = r#"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
CONSTRUCT {
  ?x rdf:type ?c .
  ?sub rdfs:subClassOf ?sup .
  ?c1 owl:disjointWith ?c2 .
  ?s1 owl:sameAs ?s2 .
  ?f1 owl:differentFrom ?f2 .
}
WHERE {
  { ?x rdf:type ?c }
  UNION { ?sub rdfs:subClassOf ?sup }
  UNION { ?c1 owl:disjointWith ?c2 }
  UNION { ?s1 owl:sameAs ?s2 }
  UNION { ?f1 owl:differentFrom ?f2 }
}
"#;

/// Build the playground JSON envelope for a [`rete_core::Reasoning`] result,
/// shared by the in-memory and remote entrypoints. `remote` is
/// `(fileLength, bytes, requests)` for the `*_url` variants, `None` in-memory.
/// JSON: `{ "kind":"reasoning", "coherent":bool, "inferredCount":N,
/// "inconsistencies":[{"kind","detail"}], ["remote":{...}] }`.
fn reasoning_json(r: &rete_core::Reasoning, remote: Option<(u64, u64, u64)>) -> String {
    use serde_json::json;
    let inconsistencies: Vec<serde_json::Value> = r
        .inconsistencies
        .iter()
        .map(|i| json!({ "kind": i.kind, "detail": i.detail }))
        .collect();
    let mut v = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "reasoning",
        "coherent": r.inconsistencies.is_empty(),
        "inferredCount": r.inferred.len(),
        "inconsistencies": inconsistencies,
    });
    if let (Some(obj), Some((file_length, bytes, requests))) = (v.as_object_mut(), remote) {
        obj.insert(
            "remote".to_string(),
            json!({ "fileLength": file_length, "bytes": bytes, "requests": requests }),
        );
    }
    v.to_string()
}

/// Run the OWL RL / RDFS reasoner over an **in-memory** `.rete` and report the
/// inferred-triple count plus any incoherent points (logical contradictions).
/// `graph` selects a named graph; the default graph is used when omitted. This is
/// the complete (Tier-2) check — it materializes the whole graph. Returns the
/// `reasoning_json` envelope (no `remote` block).
#[wasm_bindgen]
pub fn reason(bytes: &[u8], graph: Option<String>) -> Result<String, JsValue> {
    let rete = open(bytes)?;
    let base = rete.dump(graph.as_deref());
    let result = rete_core::reason(&base);
    Ok(reasoning_json(&result, None))
}

/// Run the reasoner over a **remote** `.rete` URL — the complete (Tier-2) check.
/// It materializes the whole graph, so this faults in the dataset's chunks/tiles
/// as it reads (≈ the whole file); use [`reason_construct_url`] for the cheaper
/// selective check. Worker-only (synchronous XHR). A failed range fetch mid-read
/// is an error, never a silently-incomplete (and thus possibly false "coherent")
/// result. JSON adds `"remote": { fileLength, bytes, requests }`.
#[wasm_bindgen]
pub fn reason_url(url: &str, graph: Option<String>) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let base = rete.dump(graph.as_deref());
    let result = rete_core::reason(&base);
    incomplete_guard(&rete, "reasoning")?;
    let out = reasoning_json(
        &result,
        Some((reader.len(), reader.bytes_read(), reader.requests())),
    );
    let _ = reader;
    Ok(out)
}

/// **Selective (Tier-1) coherence check** over a remote `.rete`: evaluate a
/// CONSTRUCT (touching only the tiles its constant-predicate patterns need), then
/// reason over just that subgraph. Pass [`COHERENCE_CONSTRUCT`] for the standard
/// class/equality coherence slice, or a custom CONSTRUCT to scope the check
/// further. Unlike [`reason_url`] (which materializes the whole graph), this
/// fetches only the slice the CONSTRUCT selects. Worker-only (synchronous XHR).
#[wasm_bindgen]
pub fn reason_construct_url(url: &str, construct: &str) -> Result<String, JsValue> {
    let (reader, rete) = open_url(url)?;
    let triples =
        match eval_query(&rete, construct).map_err(err)? {
            QueryOutput::Construct(t) => t,
            _ => return Err(js_error(
                "the subset query must be a CONSTRUCT — it builds the subgraph the reasoner checks",
            )),
        };
    incomplete_guard(&rete, "query")?;
    let result = rete_core::reason(&triples);
    let out = reasoning_json(
        &result,
        Some((reader.len(), reader.bytes_read(), reader.requests())),
    );
    let _ = reader;
    Ok(out)
}

/// Build the Tier-0 schema-coherence JSON envelope from the incoherent points.
/// `remote` is `(fileLength, bytes, requests)` for the `*_url` variant.
fn schema_coherence_json(
    points: &[rete_core::Inconsistency],
    remote: Option<(u64, u64, u64)>,
) -> String {
    use serde_json::json;
    let schema_points: Vec<serde_json::Value> = points
        .iter()
        .map(|i| json!({ "kind": i.kind, "detail": i.detail }))
        .collect();
    let mut v = json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "schemaCoherence",
        "coherent": points.is_empty(),
        "schemaPoints": schema_points,
        // The defining property: this answer never touched the index OR dictionary.
        "readsIndex": false,
    });
    if let (Some(obj), Some((file_length, bytes, requests))) = (v.as_object_mut(), remote) {
        obj.insert(
            "remote".to_string(),
            json!({ "fileLength": file_length, "bytes": bytes, "requests": requests }),
        );
    }
    v.to_string()
}

/// **Index-free schema coherence (Tier-0)** over an in-memory `.rete`: read only
/// the header + pyramid-meta (never the dictionary or the triple index) and report
/// schema-level incoherent points (subClassOf cycles, unsatisfiable classes).
/// Errors if the file ships no schema pyramid.
#[wasm_bindgen]
pub fn check_schema(bytes: &[u8]) -> Result<String, JsValue> {
    let points = rete_core::read_schema_coherence_ranged(&SliceReader::new(bytes))
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    Ok(schema_coherence_json(&points, None))
}

/// **Index-free schema coherence (Tier-0) over a remote `.rete` URL.** Reads only
/// TWO ranges — the header and the trailing schema block (the header records its
/// length) — never the dictionary, the community summary, or the triple index. So
/// it's a flat **~1–8 KB at any graph size** (8.1 KB of a 48.8 MB file; see
/// docs/BENCHMARK.md), making it the cheap "is the ontology coherent?" gate.
/// Worker-only (synchronous XHR); a failed range fetch is an error, never a false
/// "coherent".
#[wasm_bindgen]
pub fn check_schema_url(url: &str) -> Result<String, JsValue> {
    let reader = RemoteReader::open(url)?;
    let points = rete_core::read_schema_coherence_ranged(&reader.view())
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    Ok(schema_coherence_json(
        &points,
        Some((reader.len(), reader.bytes_read(), reader.requests())),
    ))
}

/// The schema summary (classes + relations) read from the schema pyramid over
/// HTTP range — a Schema view of a remote graph without downloading it.
/// Worker-only (synchronous XHR). JSON:
/// `{ "kind":"schema", "classes":[[iri,count]], "relations":[[s,p,o,count]], "remote":{…} }`.
#[wasm_bindgen]
pub fn schema_url(url: &str) -> Result<String, JsValue> {
    use serde_json::json;
    let reader = RemoteReader::open(url)?;
    let (classes, relations) = rete_core::read_schema_summary_ranged(&reader.view())
        .map_err(err)?
        .ok_or_else(|| js_error("file has no schema pyramid"))?;
    let classes: Vec<serde_json::Value> = classes.iter().map(|(c, n)| json!([c, n])).collect();
    let relations: Vec<serde_json::Value> = relations
        .iter()
        .map(|(s, p, o, n)| json!([s, p, o, n]))
        .collect();
    Ok(json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "schema",
        "classes": classes,
        "relations": relations,
        "remote": { "fileLength": reader.len(), "bytes": reader.bytes_read(), "requests": reader.requests() },
    })
    .to_string())
}

fn format_shacl_text(report: &ValidationReport) -> String {
    if report.conforms {
        return "conforms: true\n".to_string();
    }
    let mut out = format!("conforms: false\nresults: {}\n", report.results.len());
    for result in &report.results {
        out.push_str("\n- focus: ");
        out.push_str(&result.focus_node);
        if let Some(value) = &result.value_node {
            out.push_str("\n  value: ");
            out.push_str(value);
        }
        if let Some(path) = &result.result_path {
            out.push_str("\n  path: ");
            out.push_str(path);
        }
        out.push_str("\n  component: ");
        out.push_str(&result.source_constraint_component);
        out.push_str("\n  severity: ");
        out.push_str(&result.severity.iri());
        for message in &result.messages {
            out.push_str("\n  message: ");
            out.push_str(message);
        }
        out.push('\n');
    }
    out
}

// --- EXPERIMENTAL: real browser-thread parallelism (feature = "threads") ------
//
// Only compiled when the `threads` feature is on (a nightly + build-std wasm
// build, served cross-origin-isolated). The default build never sees any of
// this, so it stays single-threaded and `file://`-able.

/// Re-export wasm-bindgen-rayon's thread-pool initializer. JS MUST
/// `await initThreadPool(n)` once (after the module `init()`) before calling
/// [`reach_parallel`], or any rayon use will panic. Backed by Web Workers +
/// `SharedArrayBuffer`, so the page must be cross-origin isolated (COOP/COEP).
#[cfg(feature = "threads")]
pub use wasm_bindgen_rayon::init_thread_pool;

/// Multi-source transitive reachability run on **real browser threads** via
/// `wasm-bindgen-rayon` — the threaded twin of [`reach`]. Same arguments, same
/// JSON result shape; the only difference is it calls
/// [`rete_core::parallel::batch_reach_parallel`] (one rayon task per seed)
/// instead of the serial loop. Use it to benchmark the 14× batch-reachability
/// workload against [`reach`] in the browser.
///
/// Requires `await initThreadPool(navigator.hardwareConcurrency)` first.
#[cfg(feature = "threads")]
#[wasm_bindgen]
pub fn reach_parallel(
    bytes: &[u8],
    predicate: &str,
    seeds: &str,
    reverse: bool,
) -> Result<String, JsValue> {
    use std::collections::HashMap;
    let rete = open(bytes)?;
    let dict = rete.dictionary();

    // Accept either a JSON array of IRIs or a single bare IRI string (mirrors `reach`).
    let seed_iris: Vec<String> = match serde_json::from_str::<Vec<String>>(seeds) {
        Ok(v) => v,
        Err(_) => match serde_json::from_str::<String>(seeds) {
            Ok(s) => vec![s],
            Err(_) => vec![seeds.to_string()],
        },
    };

    // Adjacency in unified node space for the chosen direction.
    let adj: HashMap<u32, Vec<u32>> = if reverse {
        let mut m: HashMap<u32, Vec<u32>> = HashMap::new();
        for (s, o) in rete.predicate_pairs(predicate) {
            m.entry(o).or_default().push(s); // who points at o
        }
        m
    } else {
        build_adjacency(&rete, predicate)
    };

    // Resolve known seeds to node ids; remember unknowns to report inline.
    let mut known_idx: Vec<usize> = Vec::new();
    let mut seed_nodes: Vec<u32> = Vec::new();
    for (i, iri) in seed_iris.iter().enumerate() {
        if let Some(n) = dict.node_of_term(iri) {
            known_idx.push(i);
            seed_nodes.push(n);
        }
    }

    // The one line that differs from serial `reach`: real-thread fan-out.
    let sets = rete_core::parallel::batch_reach_parallel(&adj, &seed_nodes);

    // Map known-seed position -> its reach set, then assemble in input order.
    let mut by_input: HashMap<usize, &std::collections::BTreeSet<u32>> = HashMap::new();
    for (k, &i) in known_idx.iter().enumerate() {
        by_input.insert(i, &sets[k]);
    }

    let arr: Vec<serde_json::Value> = seed_iris
        .iter()
        .enumerate()
        .map(|(i, iri)| match by_input.get(&i) {
            Some(set) => {
                let reached: Vec<String> = set.iter().filter_map(|&n| dict.node_term(n)).collect();
                serde_json::json!({
                    "seed": iri,
                    "count": reached.len(),
                    "reached": reached,
                })
            }
            None => serde_json::json!({ "seed": iri, "error": "not in graph" }),
        })
        .collect();

    serde_json::to_string(&arr).map_err(err)
}

// --- CONSTRUCT serializers (mirrored from rete-cli, kept minimal) ------------

const RDF_TYPE_IRI: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
const XSD_INTEGER_IRI: &str = "http://www.w3.org/2001/XMLSchema#integer";

fn summary_total(view: &SummaryView) -> u64 {
    view.summary.iter().map(|edge| u64::from(edge.count)).sum()
}

fn predicate_list(view: &SummaryView) -> Vec<String> {
    view.predicate_totals()
        .into_iter()
        .map(|(predicate, _)| predicate)
        .collect()
}

fn predicate_count(view: &SummaryView) -> u64 {
    view.predicate_totals().len() as u64
}

fn select_count_response(
    variable: &str,
    count: u64,
    progressive: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let mut row = Map::new();
    row.insert(variable.to_string(), Value::String(integer_literal(count)));
    json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": [variable],
        "rows": [Value::Object(row)],
        "progressive": progressive,
    })
}

fn select_predicate_list_response(
    variable: &str,
    predicates: &[String],
    progressive: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let rows: Vec<Value> = predicates
        .iter()
        .map(|predicate| {
            let mut row = Map::new();
            row.insert(variable.to_string(), Value::String(predicate.clone()));
            Value::Object(row)
        })
        .collect();

    json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": [variable],
        "rows": rows,
        "progressive": progressive,
    })
}

fn select_predicate_totals_response(
    predicate_variable: &str,
    count_variable: &str,
    totals: &[(String, u32)],
    progressive: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let rows: Vec<Value> = totals
        .iter()
        .map(|(predicate, count)| {
            let mut row = Map::new();
            row.insert(
                predicate_variable.to_string(),
                Value::String(predicate.clone()),
            );
            row.insert(
                count_variable.to_string(),
                Value::String(integer_literal(u64::from(*count))),
            );
            Value::Object(row)
        })
        .collect();

    json!({
        "schemaVersion": JSON_SCHEMA_VERSION,
        "kind": "select",
        "vars": [predicate_variable, count_variable],
        "rows": rows,
        "progressive": progressive,
    })
}

fn progressive_meta<R: RangeReader>(
    reader: &CountingReader<R>,
    file_bytes: u64,
    query_shape: &str,
    predicate: Option<&str>,
    value: serde_json::Value,
) -> serde_json::Value {
    use serde_json::{json, Map, Value};

    let mut meta = Map::new();
    meta.insert("stage".into(), json!("summary"));
    meta.insert("exact".into(), json!(true));
    meta.insert("readsIndex".into(), json!(false));
    meta.insert("queryShape".into(), json!(query_shape));
    meta.insert("value".into(), value);
    meta.insert("bytes".into(), json!(reader.bytes_read()));
    meta.insert("requests".into(), json!(reader.requests()));
    meta.insert("fileBytes".into(), json!(file_bytes));
    if let Some(predicate) = predicate {
        meta.insert("predicate".into(), json!(predicate));
    }
    Value::Object(meta)
}

fn integer_literal(value: u64) -> String {
    format!("\"{}\"^^<{}>", value, XSD_INTEGER_IRI)
}

fn provenance_json(m: &TripleProvenance) -> serde_json::Value {
    use serde_json::json;

    let tile = match (&m.tile, m.tile_range) {
        (Some(id), Some(range)) => json!({
            "available": true,
            "id": id,
            "range": range_json(range),
        }),
        (Some(id), None) => json!({
            "available": true,
            "id": id,
        }),
        _ => json!({
            "available": false,
            "reason": "not_materialized",
        }),
    };

    json!({
        "terms": {
            "subject": m.terms.0,
            "predicate": m.terms.1,
            "object": m.terms.2,
        },
        "ids": {
            "subject": m.ids.0,
            "predicate": m.ids.1,
            "object": m.ids.2,
        },
        "provenance": {
            "graph": m.graph.as_deref().unwrap_or("default"),
            "matchedPattern": {
                "subject": m.matched_pattern.0,
                "predicate": m.matched_pattern.1,
                "object": m.matched_pattern.2,
            },
            "indexPermutation": m.index_permutation.name(),
            "indexSection": m.index_permutation.section_index(),
            "dictionaryRange": range_json(m.dictionary_range),
            "indexRange": range_json(m.index_range),
            "indexSectionRange": range_json(m.index_section_range),
            "pyramidRange": m.pyramid_range.map(range_json),
            "tile": tile,
        },
    })
}

fn range_json(range: ByteRange) -> serde_json::Value {
    serde_json::json!({
        "offset": range.offset,
        "len": range.len,
        "end": range.end(),
    })
}

/// Serialize a triple list (canonical N-Triples tokens) to Turtle: group by
/// subject, sort predicates/objects, abbreviate `rdf:type` to `a`. The tokens are
/// already valid Turtle term syntax, so they pass through verbatim — except a
/// quoted triple, which `syntax` spells like `rete export` does:
///
/// - `rdf12` (the default): the RDF 1.2 triple term `<<( s p o )>>`, which
///   current Turtle 1.2 parsers read. Written as the stored `<< s p o >>`, the
///   same parsers read a *reifier* instead, one statement becoming two — the
///   silent misreading #262 fixed for the CLI. RDF 1.2 puts a triple term in
///   object position only, so a quoted triple as a subject is refused by name
///   ([`rdf12_object`]), not written.
/// - `rdf-star`: the stored token `<<s p o>>`, verbatim.
///
/// A graph with no quoted triple is written byte-for-byte the same either way.
fn to_turtle(
    triples: &[(String, String, String)],
    syntax: rete_core::ingest::QuotedTripleSurface,
) -> Result<String, String> {
    use std::borrow::Cow;
    use std::collections::BTreeMap;
    let rdf12 = syntax == rete_core::ingest::QuotedTripleSurface::Rdf12;
    let mut by_subject: BTreeMap<&str, BTreeMap<&str, Vec<Cow<'_, str>>>> = BTreeMap::new();
    for (s, p, o) in triples {
        let o = if rdf12 {
            rdf12_object(s, p, o)?
        } else {
            Cow::Borrowed(o.as_str())
        };
        by_subject
            .entry(s)
            .or_default()
            .entry(p)
            .or_default()
            .push(o);
    }
    let mut out = String::new();
    for (s, preds) in &by_subject {
        out.push_str(s);
        out.push('\n');
        let pred_count = preds.len();
        for (i, (p, objs)) in preds.iter().enumerate() {
            let pred = if *p == RDF_TYPE_IRI { "a" } else { p };
            let objects = objs.join(" , ");
            let terminator = if i + 1 == pred_count { " ." } else { " ;" };
            out.push_str(&format!("    {pred} {objects}{terminator}\n"));
        }
        out.push('\n');
    }
    Ok(out)
}

/// Serialize a triple list to expanded JSON-LD (array of node objects keyed by
/// `@id`; literals as `@value` + optional `@type`/`@language`).
///
/// Expanded JSON-LD has no term kind for a quoted triple, so a result holding
/// one is refused, as `rete export --format jsonld` refuses (#262): written
/// anyway it came out as an `@id`, a document that loads cleanly and means
/// something else. The CLI refuses from the header flag before any work; here
/// the CONSTRUCT result is already in hand, so the check is on the result.
fn to_jsonld(triples: &[(String, String, String)]) -> Result<String, String> {
    use rete_core::terms::is_quoted_triple;
    use serde_json::{json, Map, Value};
    use std::collections::BTreeMap;
    if let Some((s, p, o)) = triples
        .iter()
        .find(|(s, p, o)| is_quoted_triple(s) || is_quoted_triple(p) || is_quoted_triple(o))
    {
        return Err(format!(
            "this CONSTRUCT result contains an RDF-star quoted triple, and expanded JSON-LD has \
             no term kind for one.\n\
             Written anyway, a quoted triple would be serialized as though it were an IRI — a \
             document that loads cleanly and means something else.\n\
             statement: {s} {p} {o} .\n\
             hint: format \"ttl\" writes it as an RDF 1.2 triple term <<( s p o )>> (add \
             \";quotedTripleSyntax=rdf-star\" for <<s p o>>), and the table output lists it as is."
        ));
    }
    let mut nodes: BTreeMap<String, BTreeMap<String, Vec<Value>>> = BTreeMap::new();
    for (s, p, o) in triples {
        let id = node_id(s);
        let pred = p
            .strip_prefix('<')
            .and_then(|x| x.strip_suffix('>'))
            .unwrap_or(p)
            .to_string();
        nodes
            .entry(id)
            .or_default()
            .entry(pred)
            .or_default()
            .push(object_to_jsonld(o));
    }
    let arr: Vec<Value> = nodes
        .into_iter()
        .map(|(id, preds)| {
            let mut obj = Map::new();
            obj.insert("@id".into(), json!(id));
            for (pred, vals) in preds {
                obj.insert(pred, Value::Array(vals));
            }
            Value::Object(obj)
        })
        .collect();
    Ok(serde_json::to_string_pretty(&Value::Array(arr)).unwrap_or_default())
}

/// JSON-LD `@id` for a subject token: bare IRI for `<iri>`, `_:b` verbatim.
fn node_id(token: &str) -> String {
    token
        .strip_prefix('<')
        .and_then(|s| s.strip_suffix('>'))
        .map(str::to_string)
        .unwrap_or_else(|| token.to_string())
}

/// Classify an object token into a JSON-LD value object.
fn object_to_jsonld(token: &str) -> serde_json::Value {
    use serde_json::{json, Map, Value};
    if let Some(iri) = token.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
        return json!({ "@id": iri });
    }
    if let Some(b) = token.strip_prefix("_:") {
        return json!({ "@id": format!("_:{b}") });
    }
    if token.starts_with('"') {
        let bytes = token.as_bytes();
        let mut i = 1;
        while i < bytes.len() {
            match bytes[i] {
                b'\\' => i += 2,
                b'"' => break,
                _ => i += 1,
            }
        }
        let value = unescape_nt(&token[1..i.min(token.len())]);
        let rest = token.get(i + 1..).unwrap_or("");
        let mut obj = Map::new();
        obj.insert("@value".into(), Value::String(value));
        if let Some(dt) = rest.strip_prefix("^^<").and_then(|s| s.strip_suffix('>')) {
            obj.insert("@type".into(), json!(dt));
        } else if let Some(lang) = rest.strip_prefix('@') {
            obj.insert("@language".into(), json!(lang));
        }
        return Value::Object(obj);
    }
    json!({ "@value": token })
}

/// Resolve the N-Triples escape sequences in a literal's body to actual chars.
fn unescape_nt(s: &str) -> String {
    rete_core::terms::unescape_literal(s)
}

fn open(bytes: &[u8]) -> Result<Rete, JsValue> {
    let mut rete = Rete::open(bytes).map_err(err)?;
    // SERVICE blocks federate to remote SPARQL endpoints over sync XHR.
    rete.set_service_client(Box::new(XhrServiceClient));
    Ok(rete)
}

fn err<E: std::fmt::Display>(e: E) -> JsValue {
    js_error(e.to_string())
}

fn js_error(message: impl AsRef<str>) -> JsValue {
    js_sys::Error::new(message.as_ref()).into()
}

#[cfg(test)]
mod construct_writer_tests {
    use super::{construct_format, to_jsonld, to_turtle, write_query_json};
    use rete_core::ingest::QuotedTripleSurface::{Rdf12, RdfStar};
    use rete_core::QueryOutput;

    const S: &str = "<http://ex/s>";
    const P: &str = "<http://ex/p>";
    const QT: &str = "<<<http://ex/a> <http://ex/b> <http://ex/c>>>";

    fn t(s: &str, p: &str, o: &str) -> (String, String, String) {
        (s.to_string(), p.to_string(), o.to_string())
    }

    /// A graph with no quoted triple, the shape every published file has.
    fn plain() -> Vec<(String, String, String)> {
        vec![
            t(S, P, "\"a > b << c\"@en"),
            t(
                S,
                "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>",
                "<http://ex/T>",
            ),
            t(S, P, "_:b0"),
            t(
                "_:b0",
                P,
                "\"5\"^^<http://www.w3.org/2001/XMLSchema#integer>",
            ),
        ]
    }

    /// The writer as it was before this change, kept verbatim as the oracle
    /// for byte identity.
    fn legacy_turtle(triples: &[(String, String, String)]) -> String {
        use std::collections::BTreeMap;
        let mut by_subject: BTreeMap<&str, BTreeMap<&str, Vec<&str>>> = BTreeMap::new();
        for (s, p, o) in triples {
            by_subject
                .entry(s)
                .or_default()
                .entry(p)
                .or_default()
                .push(o);
        }
        let mut out = String::new();
        for (s, preds) in &by_subject {
            out.push_str(s);
            out.push('\n');
            let pred_count = preds.len();
            for (i, (p, objs)) in preds.iter().enumerate() {
                let pred = if *p == super::RDF_TYPE_IRI { "a" } else { p };
                let objects = objs.join(" , ");
                let terminator = if i + 1 == pred_count { " ." } else { " ;" };
                out.push_str(&format!("    {pred} {objects}{terminator}\n"));
            }
            out.push('\n');
        }
        out
    }

    #[test]
    fn turtle_without_quoted_triples_is_byte_identical_under_both_surfaces() {
        let g = plain();
        let before = legacy_turtle(&g);
        assert_eq!(to_turtle(&g, Rdf12).unwrap(), before);
        assert_eq!(to_turtle(&g, RdfStar).unwrap(), before);
    }

    #[test]
    fn turtle_writes_an_object_triple_term_in_the_rdf12_surface_by_default() {
        let g = vec![t(S, P, QT)];
        let out = to_turtle(&g, Rdf12).unwrap();
        assert!(
            out.contains("<<( <http://ex/a> <http://ex/b> <http://ex/c> )>>"),
            "{out}"
        );
        assert!(!out.contains("<<<"), "the legacy surface leaked: {out}");
        // Nested in the object slot: rewritten at depth too.
        let nested = format!("<<<http://ex/x> <http://ex/y> {QT}>>");
        let out = to_turtle(&[t(S, P, &nested)], Rdf12).unwrap();
        assert!(
            out.contains(
                "<<( <http://ex/x> <http://ex/y> <<( <http://ex/a> <http://ex/b> <http://ex/c> )>> )>>"
            ),
            "{out}"
        );
    }

    #[test]
    fn turtle_output_reads_back_as_the_same_graph_under_rdf12() {
        // Through rete's own RDF 1.2 Turtle reader: one statement (a triple
        // term, not a reifier), carrying the stored token it started as. The
        // grouped `;` / `,` layout is exercised by a second predicate.
        let g = vec![
            t(S, P, QT),
            t(S, P, "<http://ex/o>"),
            t(S, "<http://ex/q>", QT),
        ];
        let out = to_turtle(&g, Rdf12).unwrap();
        let mut quads = rete_core::ingest::parse_statements_audited_surface(
            &out,
            "ttl",
            None,
            rete_core::ingest::QuotedTripleSurface::Rdf12,
        )
        .unwrap();
        quads.sort();
        let mut want: Vec<_> = g
            .iter()
            .map(|(s, p, o)| (s.clone(), p.clone(), o.clone()))
            .collect();
        want.sort();
        let got: Vec<_> = quads
            .iter()
            .map(|q| (q.0.clone(), q.1.clone(), q.2.clone()))
            .collect();
        assert_eq!(got, want, "{out}");
    }

    #[test]
    fn turtle_rdf_star_keeps_the_stored_token() {
        let out = to_turtle(&[t(S, P, QT)], RdfStar).unwrap();
        assert_eq!(out, legacy_turtle(&[t(S, P, QT)]));
        assert!(out.contains(QT));
    }

    #[test]
    fn turtle_refuses_a_subject_position_quoted_triple_by_name() {
        let e = to_turtle(&[t(QT, P, "<http://ex/o>")], Rdf12).unwrap_err();
        assert!(e.contains("quoted triple in the subject position"), "{e}");
        assert!(e.contains("OBJECT position only"), "{e}");
        assert!(e.contains("rdf-star"), "the hint names the escape: {e}");
        // …and one nested in another's subject.
        let inner_subject = format!("<<{QT} <http://ex/y> <http://ex/z>>>");
        let e = to_turtle(&[t(S, P, &inner_subject)], Rdf12).unwrap_err();
        assert!(e.contains("nested in the SUBJECT"), "{e}");
        // The RDF-star surface has a spelling for both.
        assert!(to_turtle(&[t(QT, P, "<http://ex/o>")], RdfStar).is_ok());
    }

    #[test]
    fn jsonld_refuses_a_quoted_triple_in_any_position() {
        for g in [vec![t(S, P, QT)], vec![t(QT, P, "<http://ex/o>")]] {
            let e = to_jsonld(&g).unwrap_err();
            assert!(e.contains("expanded JSON-LD has no term kind"), "{e}");
            assert!(e.contains("<<( s p o )>>"), "{e}");
        }
    }

    #[test]
    fn jsonld_without_quoted_triples_is_unchanged() {
        let out = to_jsonld(&plain()).unwrap();
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v.as_array().unwrap().len(), 2);
        // A literal that merely contains `<<` is not a quoted triple.
        assert!(out.contains(r#""@value": "a > b << c""#), "{out}");
    }

    #[test]
    fn the_format_parameter_mirrors_the_cli_flag() {
        assert_eq!(construct_format("ttl").unwrap(), ("ttl", Rdf12));
        assert_eq!(
            construct_format("ttl;quotedTripleSyntax=rdf-star").unwrap(),
            ("ttl", RdfStar)
        );
        assert_eq!(
            construct_format("ttl;quotedTripleSyntax=rdf12").unwrap(),
            ("ttl", Rdf12)
        );
        assert!(construct_format("ttl;quotedTripleSyntax=rdfstar")
            .unwrap_err()
            .contains("unknown quotedTripleSyntax"));
        assert!(construct_format("ttl;surface=rdf12")
            .unwrap_err()
            .contains("unknown format parameter"));

        // End to end through the envelope.
        let out = QueryOutput::Construct(vec![t(S, P, QT)]);
        let env = write_query_json(&out, "ttl", "").unwrap();
        assert!(
            env.contains(r#""format":"ttl""#) && env.contains("<<( "),
            "{env}"
        );
        let env = write_query_json(&out, "ttl;quotedTripleSyntax=rdf-star", "").unwrap();
        assert!(env.contains("<<<http://ex/a>"), "{env}");
        assert!(write_query_json(&out, "jsonld", "").is_err());
        // The table form lists the stored token as before.
        let env = write_query_json(&out, "table", "").unwrap();
        assert!(env.contains("<<<http://ex/a>"), "{env}");
    }
}