zuzu-rust 0.6.0

Rust implementation of ZuzuScript
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
=encoding utf8

=head1 NAME

std/zuzuzoo - Plan and install Zuzu distributions.

=head1 IMPLEMENTATION SUPPORT

This module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and
Electron. It is not supported by zuzu-js in the browser.

=head1 DESCRIPTION

C<std/zuzuzoo> provides the package-management engine used by the
command-line C<zuzuzoo> tool. It supports installed distribution
metadata queries, source archive inspection, dependency-aware install
planning, distribution test execution, file installation, planned
target-root removal execution, installed metadata writing, standalone
safe removal planning and execution, installed-file verification,
latest-version checks, upgrade checks, and canonical pretty JSON
formatting.

The command-line C<zuzuzoo> wrapper delegates package behaviour to this
module and handles argument parsing, user prompts, output formatting,
JSON output selection, and exit-code translation.

=head1 EXPORTS

=head2 Functions

=over

=item C<< compare_versions(left, right) >>

Parameters: C<left> and C<right> are version strings. Returns:
C<Number>. Compares two versions, returning a negative, zero, or
positive value.

=item C<< list_installed(options?) >>, C<< query(module_name, options?) >>, C<< query_distribution(distribution_name, options?) >>

Parameters: names identify installed modules or distributions and
C<options> controls roots and output. Returns: value. Reads installed
distribution metadata.

=item C<< is_installed(module_name, min_version?, options?) >>, C<< installed_version(module_name, options?) >>

Parameters: C<module_name> identifies a module, C<min_version> is
optional, and C<options> controls roots. Returns: C<Boolean> or
C<String>/C<null>. Checks installed module state.

=item C<< pretty_json(value, options?) >>, C<< format_json(value, options?) >>

Parameters: C<value> is JSON-encodable data and C<options> controls
formatting. Returns: C<String>. Formats canonical JSON output.

=item C<< fetch_source(target, options?) >>, C<< load_distribution(target, options?) >>

Parameters: C<target> identifies a source archive or distribution and
C<options> controls fetch/load behaviour. Returns: value. Fetches or
loads distribution metadata.

=item C<< dependency_roots(options?) >>, C<< find_dependency(module_name, min_version?, options?) >>

Parameters: C<options> controls search roots and C<module_name> names a
dependency. Returns: value. Locates dependency sources.

=item C<< plan_install(targets, options?) >>, C<< plan_remove(targets, options?) >>

Parameters: C<targets> is an array of requested modules or
distributions. Returns: C<Dict>. Builds an install or removal plan.

=item C<< verify(targets, options?) >>, C<< latest(module_name, options?) >>, C<< can_upgrade(module_name, options?) >>

Parameters: C<targets> or C<module_name> identify installed or remote
items. Returns: value. Verifies installation state or checks available
versions.

=item C<< install(targets, options?) >>, C<< remove(targets, options?) >>

Parameters: C<targets> is an array of modules or distributions. Returns:
C<Dict>. Executes installation or removal.

=item C<< run_distribution_tests(install_action, options?) >>, C<< execute_removal(removal_action, options?) >>

Parameters: action dictionaries come from plans and C<options> controls
execution. Returns: C<Dict>. Runs tests or executes one removal action.

=item C<< format_install_plan(plan, options?) >>, C<< format_remove_plan(plan, options?) >>

Parameters: C<plan> is a plan dictionary. Returns: C<String>. Formats a
plan for display.

=back

=head2 Classes

=over

=item C<ZuzuzooLock>

Filesystem lock object.

=over

=item C<< lock.release() >>

Parameters: none. Returns: C<null>. Releases the lock.

=back

=item C<Zuzuzoo>

Stateful package-management helper. Its methods correspond to the
module-level functions and take the same parameters, without the final
C<options> argument where object configuration already supplies defaults.

=over

=item C<< zoo.config() >>

Parameters: none. Returns: C<Dict>. Returns the effective configuration.

=item C<< zoo.acquire_lock(operation, options?) >>

Parameters: C<operation> names the operation and C<options> controls
locking. Returns: C<ZuzuzooLock>. Acquires an operation lock.

=item C<< zoo.find_installed_module(module_name, options?) >>

Parameters: C<module_name> identifies a module and C<options> controls
roots. Returns: C<Dict> or C<null>. Finds installed metadata for a
module.

=item C<< zoo.find_installed_distribution(distribution_name, options?) >>

Parameters: C<distribution_name> identifies a distribution and
C<options> controls roots. Returns: C<Dict> or C<null>. Finds installed
metadata for a distribution.

=back

=back

=head1 COPYRIGHT AND LICENCE

B<< std/zuzuzoo >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/data/json import JSON;
from std/archive import Archive;
from std/digest/sha import sha256_hex;
from std/io import Path, STDERR, STDOUT;
from std/net/http import UserAgent;
from std/proc import Env, Proc, sleep;
from std/string import contains, ends_with, join, split, starts_with, substr;
from std/time import Time;
from test/parser import parse as parse_tap;


function _opt ( options, key, fallback := null ) {
	if ( options instanceof Dict and options.exists(key) ) {
		return options.get(key);
	}
	return fallback;
}

function _progress ( options, message ) {
	if ( _opt( options, "progress", false ) ) {
		STDERR.say( "zuzuzoo: " _ message );
	}
	return true;
}

function _response_success ( response ) {
	return response.success() if response can "success";
	return true;
}

function _response_status_text ( response ) {
	let status := ( response can "status" ) ? response.status() : "?";
	let reason := ( response can "reason" ) ? response.reason() : "";
	return "" _ status _ " " _ reason;
}

function _archive_url_from_latest ( latest_info ) {
	let metadata := latest_info{remote_metadata};
	if (
		( metadata instanceof Dict or metadata instanceof PairList ) and
		metadata.exists("archive_url")
	) {
		return metadata{archive_url};
	}

	let remote_url := latest_info{remote_url};
	if ( ends_with( remote_url, ".json" ) ) {
		return substr( remote_url, 0, length remote_url - 5 ) _ ".tar.gz";
	}

	die(
		"Latest metadata URL does not identify a source archive " _
		"(remote_url=" _ remote_url _ ")"
	);
}

function _push_unique_string ( items, seen, value ) {
	let key := "" _ value;
	return false if key eq "";
	return false if seen.exists(key);
	seen.add( key, true );
	items.push(key);
	return true;
}

function _copy_options_with ( options, key, value ) {
	let out := {};
	if ( options instanceof Dict ) {
		for ( let existing_key in options.keys() ) {
			out.set( existing_key, options.get(existing_key) );
		}
	}
	out.set( key, value );
	return out;
}

function _is_windows_platform () {
	if ( "platform" in __system__ ) {
		let platform := lc( "" _ __system__.get("platform") );
		return platform eq "windows" or platform eq "mswin32";
	}
	return false;
}

function _join_dir ( String base, String child, Boolean windows ) {
	let sep := windows ? "\\": "/";
	return base _ sep _ child;
}

function _require_text ( obj, String key, String where ) {
	if ( not( obj instanceof Dict ) or not obj.exists(key) ) {
		die `Invalid installed metadata ${where}: missing ${key}`;
	}
	let value := obj.get(key);
	if ( not( value instanceof String ) or value eq "" ) {
		die `Invalid metadata ${where}: ${key} must be a string`;
	}
	return value;
}

function _require_object ( obj, String key, String where ) {
	if ( not( obj instanceof Dict ) or not obj.exists(key) ) {
		die `Invalid installed metadata ${where}: missing ${key}`;
	}
	let value := obj.get(key);
	if ( not( value instanceof Dict ) ) {
		die `Invalid metadata ${where}: ${key} must be an object`;
	}
	return value;
}

function _require_array ( obj, String key, String where ) {
	if ( not( obj instanceof Dict ) or not obj.exists(key) ) {
		die `Invalid installed metadata ${where}: missing ${key}`;
	}
	let value := obj.get(key);
	if ( not( value instanceof Array ) ) {
		die `Invalid metadata ${where}: ${key} must be an array`;
	}
	return value;
}

function _source_require_text ( obj, String key, String where ) {
	if ( not( obj instanceof Dict ) and not( obj instanceof PairList ) ) {
		die `Invalid source metadata ${where}: root must be an object`;
	}
	if ( not obj.exists(key) ) {
		die `Invalid source metadata ${where}: missing ${key}`;
	}
	let value := obj.get(key);
	if ( not( value instanceof String ) or value eq "" ) {
		die `Invalid source metadata ${where}: ${key} must be a string`;
	}
	return value;
}

function _validate_dependency_pair ( key, value, String where ) {
	if ( not( key instanceof String ) or key eq "" ) {
		die `Invalid source metadata ${where}: bad dependency name`;
	}
	if ( not( value instanceof String ) or value eq "" ) {
		die `Invalid source metadata ${where}: bad dependency version`;
	}
	return true;
}

function _validate_dependencies ( meta, String where ) {
	if ( not meta.exists("dependencies") ) {
		return true;
	}
	let deps := meta.get("dependencies");
	if ( not( deps instanceof Dict ) ) {
		die `Invalid metadata ${where}: dependencies must be an object`;
	}
	for ( let key in deps.keys() ) {
		if ( not( key instanceof String ) or key eq "" ) {
			die `Invalid metadata ${where}: bad dependency name`;
		}
		let value := deps.get(key);
		if ( not( value instanceof String ) or value eq "" ) {
			die `Invalid metadata ${where}: bad dependency version`;
		}
	}
	return true;
}

function _validate_source_dependencies ( meta, String where ) {
	if ( not meta.exists("dependencies") ) {
		return true;
	}
	let deps := meta.get("dependencies");
	if ( deps instanceof Dict ) {
		for ( let key in deps.keys() ) {
			_validate_dependency_pair( key, deps.get(key), where );
		}
		return true;
	}
	if ( deps instanceof PairList ) {
		let keys := deps.keys();
		let values := deps.values();
		let i := 0;
		while ( i < keys.length() ) {
			_validate_dependency_pair( keys[i], values[i], where );
			i++;
		}
		return true;
	}
	die `Invalid source metadata ${where}: dependencies must be an object`;
}

function _validate_source_metadata ( meta, String metadata_file ) {
	if ( not( meta instanceof Dict ) and not( meta instanceof PairList ) ) {
		die `Invalid source metadata ${metadata_file}: root must be an object`;
	}
	if ( meta.exists("installed") ) {
		die `Invalid source metadata ${metadata_file}: installed is not allowed`;
	}
	if ( meta.exists("modules") or meta.exists("scripts") ) {
		die(
			`Invalid source metadata ${metadata_file}: top-level ` _
			"modules/scripts are not allowed"
		);
	}

	_source_require_text( meta, "name", metadata_file );
	_source_require_text( meta, "version", metadata_file );
	_source_require_text( meta, "author", metadata_file );
	_source_require_text( meta, "license", metadata_file );

	if ( meta.exists("status") ) {
		let status := _source_require_text( meta, "status", metadata_file );
		if ( status ne "stable" and status ne "trial" ) {
			die `Invalid source metadata ${metadata_file}: bad status ${status}`;
		}
	}
	_validate_source_dependencies( meta, metadata_file );

	if ( meta instanceof Dict ) {
		meta.set( "metadata_file", metadata_file );
	}
	else {
		meta.add( "metadata_file", metadata_file );
	}
	return meta;
}

function _validate_entry ( entry, String kind, String where ) {
	if ( not( entry instanceof Dict ) ) {
		die `Invalid metadata ${where}: bad ${kind} entry`;
	}
	_require_text( entry, "source", where );
	_require_text( entry, "install_as", where );
	_require_text( entry, "sha256", where );
	if ( kind eq "script" and entry.exists("wrappers") ) {
		let wrappers := entry.get("wrappers");
		if ( not( wrappers instanceof Array ) ) {
			die `Invalid metadata ${where}: bad script wrappers`;
		}
		for ( let wrapper in wrappers ) {
			if ( not( wrapper instanceof String ) or wrapper eq "" ) {
				die `Invalid metadata ${where}: bad wrapper`;
			}
		}
	}
	return true;
}

function _validate_installed_metadata ( meta, String metadata_file ) {
	if ( not( meta instanceof Dict ) ) {
		die `Invalid metadata ${metadata_file}: root must be an object`;
	}
	if ( meta.exists("modules") or meta.exists("scripts") ) {
		die(
			`Invalid metadata ${metadata_file}: top-level ` _
			"modules/scripts are not allowed"
		);
	}

	_require_text( meta, "name", metadata_file );
	_require_text( meta, "version", metadata_file );
	_require_text( meta, "author", metadata_file );
	_require_text( meta, "license", metadata_file );
	let status := _require_text( meta, "status", metadata_file );
	if ( status ne "stable" and status ne "trial" ) {
		die `Invalid metadata ${metadata_file}: bad status ${status}`;
	}
	_validate_dependencies( meta, metadata_file );

	let installed := _require_object( meta, "installed", metadata_file );
	let zdf := _require_text( installed, "zdf", metadata_file );
	if ( zdf ne "ZDF-1" ) {
		die `Invalid metadata ${metadata_file}: bad installed.zdf`;
	}
	_require_text( installed, "lib_dir", metadata_file );
	_require_text( installed, "bin_dir", metadata_file );
	_require_text( installed, "meta_dir", metadata_file );

	let modules := _require_array( installed, "modules", metadata_file );
	let scripts := _require_array( installed, "scripts", metadata_file );
	if ( modules.length() + scripts.length() = 0 ) {
		die `Invalid metadata ${metadata_file}: no installed files`;
	}

	for ( let module in modules ) {
		_validate_entry( module, "module", metadata_file );
	}
	for ( let script in scripts ) {
		_validate_entry( script, "script", metadata_file );
	}

	meta.set( "metadata_file", metadata_file );
	return meta;
}

function _parse_version ( version ) {
	let text := "" _ version;
	let nums := [];
	let i := 0;
	let n := length text;

	while ( i < n and substr( text, i, 1 ) ~ /^[0-9]$/ ) {
		let start := i;
		while ( i < n and substr( text, i, 1 ) ~ /^[0-9]$/ ) {
			i++;
		}
		nums.push( int( substr( text, start, i - start ) ) );

		if (
			i < n - 1 and
			substr( text, i, 1 ) eq "." and
			substr( text, i + 1, 1 ) ~ /^[0-9]$/
		) {
			i++;
			next;
		}
		last;
	}

	return {
		nums: nums,
		suffix: substr( text, i ),
	};
}

function compare_versions ( left, right ) {
	let a := _parse_version(left);
	let b := _parse_version(right);
	let max := a{nums}.length() > b{nums}.length()
		? a{nums}.length()
		: b{nums}.length();

	let i := 0;
	while ( i < max ) {
		let av := i < a{nums}.length() ? a{nums}[i]: 0;
		let bv := i < b{nums}.length() ? b{nums}[i]: 0;
		return av <=> bv if av != bv;
		i++;
	}

	if ( a{suffix} eq "" and b{suffix} ne "" ) {
		return 1;
	}
	if ( a{suffix} ne "" and b{suffix} eq "" ) {
		return -1;
	}
	return a{suffix} cmp b{suffix};
}

function _module_key ( module_name ) {
	let text := "" _ module_name;
	if ( ends_with( text, ".zzm" ) ) {
		return substr( text, 0, length text - 4 );
	}
	return text;
}

function _is_url ( String target ) {
	return (
		starts_with( target, "http://" ) or
		starts_with( target, "https://" )
	);
}

function _trim_right_slash ( String text ) {
	let out := text;
	while ( length out > 0 and substr( out, length out - 1, 1 ) eq "/" ) {
		out := substr( out, 0, length out - 1 );
	}
	return out;
}

function _safe_archive_root ( archive, String where ) {
	if ( not( archive instanceof Dict ) or not( archive.get("entries") instanceof Array ) ) {
		die `Invalid archive ${where}: entries must be an array`;
	}

	let seen := {};
	let root := null;
	for ( let entry in archive{entries} ) {
		if ( not( entry instanceof Dict ) or not( entry.get("path") instanceof String ) ) {
			die `Invalid archive ${where}: bad entry path`;
		}
		let path := entry{path};
		if ( path eq "" ) {
			die `Invalid archive ${where}: empty path`;
		}
		if ( starts_with( path, "/" ) or contains( path, "\\" ) ) {
			die `Invalid archive ${where}: unsafe path ${path}`;
		}
		if ( seen.exists(path) ) {
			die `Invalid archive ${where}: duplicate path ${path}`;
		}
		seen.add( path, true );

		let parts := split( path, "/" );
		if ( parts.length() == 0 or parts[0] eq "" ) {
			die `Invalid archive ${where}: empty path component`;
		}
		for ( let part in parts ) {
			if ( part eq "" or part eq "." or part eq ".." ) {
				die `Invalid archive ${where}: unsafe path ${path}`;
			}
		}
		if ( root instanceof Null ) {
			root := parts[0];
		}
		else if ( root ne parts[0] ) {
			die `Invalid archive ${where}: multiple top-level roots`;
		}
	}

	die `Invalid archive ${where}: no entries` if root instanceof Null;
	return root;
}

function _ensure_dir ( path ) {
	return true if path.exists();
	let parent := path.parent();
	_ensure_dir(parent) if not parent.exists();
	path.mkdir();
	return true;
}

function _mkdir_parent ( path ) {
	_ensure_dir( path.parent() );
	return true;
}

function _extract_archive ( archive, String root_name, root_dir ) {
	for ( let entry in archive{entries} ) {
		let parts := split( entry{path}, "/" );
		let out := root_dir;
		let i := 1;
		while ( i < parts.length() ) {
			out := out.child(parts[i]);
			i++;
		}
		_mkdir_parent(out);
		out.spew(entry{data});
	}
	return true;
}

function _relative_path ( root, path ) {
	let prefix := root.to_String() _ "/";
	let text := path.to_String();
	if ( starts_with( text, prefix ) ) {
		return substr( text, length prefix );
	}
	return path.basename();
}

function _discover_files ( root, dir_name, extension ) {
	let base := root.child(dir_name);
	return [] if not base.exists();
	return [] if not base.is_dir();

	let found := [];
	function walk ( path ) {
		for ( let child in path.children() ) {
			if ( child.is_dir() ) {
				walk(child);
			}
			else if ( child.is_file() and ends_with( child.basename(), extension ) ) {
				found.push( _relative_path( root, child ) );
			}
		}
	}
	walk(base);
	return found.sort( fn ( a, b ) -> a cmp b );
}

function _has_extension ( String basename ) {
	return contains( basename, "." );
}

function _has_zuzu_shebang ( path ) {
	let text := "";
	try {
		text := path.slurp_utf8();
	}
	catch {
		return false;
	}

	let lines := split( text, "\n" );
	let first_line := lines.length() == 0 ? "" : lines[0];
	return starts_with( first_line, "#!" ) and contains( first_line, "zuzu" );
}

function _discover_scripts ( root ) {
	let base := root.child("scripts");
	return [] if not base.exists();
	return [] if not base.is_dir();

	let found := [];
	function walk ( path ) {
		for ( let child in path.children() ) {
			if ( child.is_dir() ) {
				walk(child);
			}
			else if ( child.is_file() ) {
				let basename := child.basename();
				if (
					ends_with( basename, ".zzs" ) or
					(
						not _has_extension(basename) and
						_has_zuzu_shebang(child)
					)
				) {
					found.push( _relative_path( root, child ) );
				}
			}
		}
	}
	walk(base);
	return found.sort( fn ( a, b ) -> a cmp b );
}

function _module_install_name ( String source ) {
	return substr( source, length "modules/" );
}

function _script_install_name ( String source ) {
	return substr( source, length "scripts/" );
}

function _target_list ( targets ) {
	return targets instanceof Array ? targets : [ targets ];
}

function _root_key ( root ) {
	return (
		root{lib_dir} _ "\n" _
		root{bin_dir} _ "\n" _
		root{meta_dir}
	);
}

function _root_from_config ( String name, String kind, cfg ) {
	return {
		name: name,
		kind: kind,
		lib_dir: cfg{lib_dir},
		bin_dir: cfg{bin_dir},
		meta_dir: cfg{meta_dir},
		global: cfg{global},
		windows: cfg{windows},
	};
}

function _require_root_text ( root, String key, String where ) {
	if ( not( root instanceof Dict ) or not root.exists(key) ) {
		die `Invalid dependency root ${where}: missing ${key}`;
	}
	let value := root.get(key);
	if ( not( value instanceof String ) or value eq "" ) {
		die `Invalid dependency root ${where}: ${key} must be a string`;
	}
	return value;
}

function _custom_root ( root, String where ) {
	return {
		name: _require_root_text( root, "name", where ),
		kind: "custom",
		lib_dir: _require_root_text( root, "lib_dir", where ),
		bin_dir: _require_root_text( root, "bin_dir", where ),
		meta_dir: _require_root_text( root, "meta_dir", where ),
		global: root.exists("global") ? root{global} : false,
		windows: root.exists("windows") ? root{windows} : false,
	};
}

function _root_override ( root, String name, String kind, String where ) {
	return {
		name: name,
		kind: kind,
		lib_dir: _require_root_text( root, "lib_dir", where ),
		bin_dir: _require_root_text( root, "bin_dir", where ),
		meta_dir: _require_root_text( root, "meta_dir", where ),
		global: root.exists("global") ? root{global} : false,
		windows: root.exists("windows") ? root{windows} : false,
	};
}

function _add_root ( roots, seen, root ) {
	let key := _root_key(root);
	return false if seen.exists(key);
	seen.add( key, true );
	roots.push(root);
	return true;
}

function _path_join ( String base, String child, Boolean windows ) {
	let sep := windows ? "\\": "/";
	return base _ sep _ child;
}

function _path_child ( String base, String relative ) {
	let out := new Path(base);
	for ( let part in split( relative, "/" ) ) {
		out := out.child(part) if part ne "";
	}
	return out;
}

function _relative_basename ( String relative ) {
	let parts := split( relative, "/" );
	return parts[ parts.length() - 1 ];
}

function _replace_script_suffix ( String relative, String suffix ) {
	if ( ends_with( relative, ".zzs" ) ) {
		return substr( relative, 0, length relative - 4 ) _ suffix;
	}
	return relative _ suffix;
}

function _installed_at () {
	return ( new Time() ).strftime("%Y-%m-%dT%H:%M:%SZ");
}

function _now_epoch () {
	return ( new Time() ).epoch();
}

function _temp_parent ( options? ) {
	let temp_root := _opt( options, "temp_root", null );
	if ( temp_root instanceof Null ) {
		return null;
	}
	let root := new Path(temp_root);
	_ensure_dir(root);
	return root;
}

function _unique_temp_path ( parent, String prefix, String suffix ) {
	let base := prefix _ Proc.pid() _ "-" _ _now_epoch();
	let i := 0;
	while ( true ) {
		let candidate := parent.child( base _ "-" _ i _ suffix );
		return candidate if not candidate.exists();
		i++;
	}
}

function _new_temp_dir ( options?, String prefix := "zuzuzoo-" ) {
	let parent := _temp_parent(options);
	if ( parent instanceof Null ) {
		return Path.tempdir();
	}

	let i := 0;
	while ( true ) {
		let candidate := _unique_temp_path(
			parent,
			prefix,
			".d",
		);
		if ( candidate.mkdir_exclusive() ) {
			return candidate;
		}
		i++;
		die `Could not allocate temporary directory in ${parent}`
			if i > 1000;
	}
}

function _cleanup_path ( path ) {
	return false if path instanceof Null;
	try {
		if ( path.exists() ) {
			if ( path.is_dir() ) {
				path.remove_tree();
			}
			else {
				path.remove();
			}
			return true;
		}
	}
	catch ( Exception e ) {
		return false;
	}
	return false;
}

function _cleanup_source ( source, options? ) {
	return false if source instanceof Null;
	return false if _opt( options, "keep_work_dirs", false );
	if ( source.exists("temp_dir") ) {
		return _cleanup_path(source{temp_dir});
	}
	return false;
}

function _cleanup_install_action ( install_action, options? ) {
	return false if _opt( options, "keep_work_dirs", false );
	_cleanup_source( install_action{source}, options )
		if install_action.exists("source");
	_cleanup_path( install_action{work_dir_obj} )
		if install_action.exists("work_dir_obj");
	return true;
}

function _cleanup_plan_work_dirs ( plan, options? ) {
	return false if plan instanceof Null;
	return false if _opt( options, "keep_work_dirs", false );
	for ( let install_action in plan.get( "installs", [] ) ) {
		_cleanup_install_action( install_action, options );
	}
	return true;
}

function _cleanup_loaded_work_dirs ( loaded, options? ) {
	return false if _opt( options, "keep_work_dirs", false );
	for ( let item in loaded ) {
		_cleanup_install_action( item, options );
	}
	return true;
}

function _atomic_temp_sibling ( path, String suffix := ".tmp" ) {
	return _unique_temp_path(
		path.parent(),
		"." _ path.basename() _ ".",
		suffix,
	);
}

function _atomic_json_write ( path, value ) {
	_mkdir_parent(path);
	let temp := _atomic_temp_sibling(path);
	let codec := new JSON( pretty: true, canonical: true );
	try {
		codec.dump( temp, value );
		codec.load(temp);
		temp.move(path);
	}
	catch ( Exception e ) {
		_cleanup_path(temp);
		throw e;
	}
	return path;
}

function _copy_file_atomic ( source, destination, chmod_mode? ) {
	_mkdir_parent(destination);
	let temp := _atomic_temp_sibling(destination);
	try {
		source.copy(temp);
		let temp_sha := sha256_hex(temp.slurp());
		temp.chmod(chmod_mode) if not( chmod_mode instanceof Null );
		temp.move(destination);
		let final_bytes := destination.slurp();
		let final_sha := sha256_hex(final_bytes);
		if ( final_sha ne temp_sha ) {
			die(
				`Atomic install verification failed for ${destination}: ` _
				`expected ${temp_sha}, got ${final_sha}`
			);
		}
		return {
			sha256: final_sha,
			size: destination.size(),
		};
	}
	catch ( Exception e ) {
		_cleanup_path(temp);
		throw e;
	}
}

function _spew_utf8_atomic ( destination, String text ) {
	_mkdir_parent(destination);
	let temp := _atomic_temp_sibling(destination);
	try {
		temp.spew_utf8(text);
		temp.move(destination);
	}
	catch ( Exception e ) {
		_cleanup_path(temp);
		throw e;
	}
	return destination;
}

function _source_context ( source ) {
	let parts := [
		"target=" _ source{value},
		"source_type=" _ source{type},
	];
	parts.push( "url=" _ source{url} ) if source.exists("url");
	parts.push( "resolved_url=" _ source{resolved_url} )
		if source.exists("resolved_url");
	parts.push( "path=" _ source{path} ) if source.exists("path");
	return join( ", ", parts );
}

function _corrupt_archive_error ( source, underlying ) {
	return (
		"Corrupt source archive (" _ _source_context(source) _
		"): " _ underlying.to_String()
	);
}

function _cache_key ( String url ) {
	return sha256_hex(to_binary(url));
}

function _cache_paths ( String cache_dir, String url ) {
	let dir := new Path(cache_dir);
	_ensure_dir(dir);
	let key := _cache_key(url);
	return {
		dir: dir,
		key: key,
		archive: dir.child(key _ ".archive"),
		sidecar: dir.child(key _ ".json"),
	};
}

function _delete_cache_entry ( paths ) {
	_cleanup_path(paths{archive});
	_cleanup_path(paths{sidecar});
	return true;
}

function _validate_cache_entry ( paths ) {
	return false if not paths{archive}.exists();
	return false if not paths{sidecar}.exists();

	let sidecar := null;
	try {
		sidecar := ( new JSON() ).load(paths{sidecar});
	}
	catch ( Exception e ) {
		return false;
	}

	let bytes := paths{archive}.slurp();
	let actual_sha := sha256_hex(bytes);
	if ( sidecar.get( "archive_sha256", "" ) ne actual_sha ) {
		return false;
	}
	if ( sidecar.get( "byte_size", -1 ) != paths{archive}.size() ) {
		return false;
	}
	try {
		Archive.decode(bytes);
	}
	catch ( Exception e ) {
		return false;
	}
	return sidecar;
}

function _write_cache_entry ( paths, source, temp_path ) {
	let bytes := temp_path.slurp();
	let sidecar := {
		original_url: source{url},
		resolved_url: source{resolved_url},
		downloaded_at: _installed_at(),
		archive_sha256: sha256_hex(bytes),
		byte_size: temp_path.size(),
	};
	Archive.decode(bytes);
	let archive_temp := _atomic_temp_sibling(paths{archive});
	let sidecar_temp := _atomic_temp_sibling(paths{sidecar});
	try {
		temp_path.copy(archive_temp);
		archive_temp.move(paths{archive});
		( new JSON( pretty: true, canonical: true ) ).dump(
			sidecar_temp,
			sidecar,
		);
		( new JSON() ).load(sidecar_temp);
		sidecar_temp.move(paths{sidecar});
	}
	catch ( Exception e ) {
		_cleanup_path(archive_temp);
		_cleanup_path(sidecar_temp);
		_delete_cache_entry(paths);
		throw e;
	}
	return sidecar;
}

function _check_expected_source_sha ( source, expected_sha256 ) {
	return true if expected_sha256 instanceof Null;
	let actual := sha256_hex( ( new Path(source{path}) ).slurp() );
	if ( actual ne expected_sha256 ) {
		die(
			"Source checksum mismatch (" _ _source_context(source) _
			`): expected ${expected_sha256}, got ${actual}`
		);
	}
	return true;
}

function _dependency_chain ( stack, dependency_of, module_name ) {
	let chain := [];
	for ( let item in stack ) {
		chain.push(item);
	}
	if ( not( dependency_of instanceof Null ) ) {
		chain.push(dependency_of{metadata}{name});
	}
	chain.push(module_name);
	return join( " -> ", chain );
}

function _dependency_conflict_message (
	dep,
	dependency_of,
	stack,
	planned_action,
	conflicting_dist
) {
	let requested_by := dependency_of instanceof Null
		? "<requested target>"
		: dependency_of{metadata}{name};
	let planned_text := planned_action instanceof Null
		? "none"
		: planned_action{metadata}{name} _ " " _
			planned_action{metadata}{version};
	let conflicting_text := conflicting_dist{metadata}{name} _ " " _
		conflicting_dist{metadata}{version};
	return (
		"Dependency conflict: requested dependency " _
		dep{module_name} _ " >= " _ dep{min_version} _
		"; requester chain " _
		_dependency_chain(
			stack,
			dependency_of,
			dep{module_name},
		) _
		"; requested by " _ requested_by _
		"; planned/provided version " _ planned_text _
		"; conflicting planned/provided version " _
		conflicting_text
	);
}

function _planned_version_conflict_message (
	String dist_name,
	existing,
	dist,
	String target_text
) {
	return (
		`Conflicting planned versions for ${dist_name}: ` _
		existing{metadata}{version} _ " and " _
		dist{metadata}{version} _
		"; existing target " _ existing{target} _
		"; conflicting target " _ target_text _
		"; existing metadata " _
		existing{metadata}{metadata_file} _
		"; conflicting metadata " _
		dist{metadata}{metadata_file}
	);
}

function _copy_dependencies ( metadata ) {
	let out := {};
	return out if not metadata.exists("dependencies");
	let deps := metadata{dependencies};
	if ( deps instanceof PairList ) {
		let keys := deps.keys();
		let values := deps.values();
		let i := 0;
		while ( i < keys.length() ) {
			out.set( keys[i], values[i] );
			i++;
		}
		return out;
	}
	for ( let key in deps.keys() ) {
		out.set( key, deps.get(key) );
	}
	return out;
}

function _copy_source_record ( source ) {
	let out := {
		type: source{type},
		value: source{value},
	};
	out{url} := source{url} if source.exists("url");
	out{resolved_url} := source{resolved_url}
		if source.exists("resolved_url");
	out{path} := source{path} if source.exists("path");
	return out;
}

function _copy_source_metadata ( metadata ) {
	let out := {};
	for ( let key in metadata.keys() ) {
		next if key eq "metadata_file";
		if ( key eq "dependencies" ) {
			out.set( key, _copy_dependencies(metadata) );
		}
		else {
			out.set( key, metadata.get(key) );
		}
	}
	out.set( "status", "stable" ) if not out.exists("status");
	out.set( "dependencies", {} ) if not out.exists("dependencies");
	return out;
}

function _test_ok ( parsed, run_result ) {
	return false if not Proc.is_success(run_result);
	return false if parsed{planned} instanceof Null;
	return false if parsed{assertions}{failed} > 0;
	return true;
}

function _dependency_entries ( metadata ) {
	let out := [];
	return out if not metadata.exists("dependencies");

	let deps := metadata{dependencies};
	if ( deps instanceof PairList ) {
		let keys := deps.keys();
		let values := deps.values();
		let i := 0;
		while ( i < keys.length() ) {
			out.push(
				{
					module_name: keys[i],
					min_version: values[i],
				},
			);
			i++;
		}
		return out;
	}

	let keys := deps.keys();
	for ( let key in keys ) {
		out.push(
			{
				module_name: key,
				min_version: deps.get(key),
			},
		);
	}
	return out;
}

function _version_satisfies ( version, min_version ) {
	return true if min_version instanceof Null;
	return true if "" _ min_version eq "0";
	return compare_versions( version, min_version ) >= 0;
}

function _provides_module ( dist, module_name, min_version ) {
	return false if not _version_satisfies( dist{version}, min_version );
	let wanted := _module_key(module_name);
	for ( let module in dist{installed}{modules} ) {
		return true if _module_key( module{install_as} ) eq wanted;
	}
	return false;
}

function _planned_provides_module ( install_action, module_name, min_version ) {
	return false if not _version_satisfies(
		install_action{metadata}{version},
		min_version,
	);
	let wanted := _module_key(module_name);
	for ( let module in install_action{modules} ) {
		return true if _module_key( module{install_as} ) eq wanted;
	}
	return false;
}

function _loaded_distribution_provides ( dist, module_name, min_version ) {
	return false if not _version_satisfies(
		dist{metadata}{version},
		min_version,
	);
	let wanted := _module_key(module_name);
	for ( let module in dist{modules} ) {
		return true if _module_key( module{install_as} ) eq wanted;
	}
	return false;
}

function _metadata_files_in_dir ( String meta_dir ) {
	let dir := new Path(meta_dir);
	return [] if not dir.exists();
	die `Metadata path is not a directory: ${dir}`
		if not dir.is_dir();

	let files := [];
	for ( let child in dir.children() ) {
		if (
			child.is_file() and
			ends_with( child.basename(), ".json" )
		) {
			files.push(child);
		}
	}
	return files.sort(
		fn ( a, b ) -> a.to_String() cmp b.to_String()
	);
}

function _list_installed_in_root ( root ) {
	let codec := new JSON();
	let installed := [];
	for ( let file in _metadata_files_in_dir( root{meta_dir} ) ) {
		let data := codec.load(file);
		let valid := _validate_installed_metadata(
			data,
			file.to_String(),
		);
		installed.push(valid);
	}

	return installed.sort( function ( a, b ) {
		let name_cmp := a{name} cmp b{name};
		return name_cmp if name_cmp != 0;
		return compare_versions( b{version}, a{version} );
	} );
}

function _candidate_record (
	String source,
	module_name,
	min_version,
	version,
	distribution,
	root,
	metadata_file,
	install_action
) {
	let record := {
		module_name: "" _ module_name,
		min_version: min_version instanceof Null ? null : "" _ min_version,
		version: "" _ version,
		source: source,
		distribution: distribution,
		metadata_file: metadata_file,
	};
	record{root} := root if not( root instanceof Null );
	record{install} := install_action if not( install_action instanceof Null );
	return record;
}

function _better_dependency_candidate ( current, candidate, root_order ) {
	return true if current instanceof Null;

	let version_cmp := compare_versions(
		candidate{version},
		current{version},
	);
	return true if version_cmp > 0;
	return false if version_cmp < 0;

	let current_order := root_order.exists(current{root}{name})
		? root_order.get(current{root}{name})
		: 1000000;
	let candidate_order := root_order.exists(candidate{root}{name})
		? root_order.get(candidate{root}{name})
		: 1000000;
	return true if candidate_order < current_order;
	return false if candidate_order > current_order;

	return candidate{metadata_file} lt current{metadata_file};
}

function _find_dependency_in_roots ( roots, module_name, min_version ) {
	let root_order := {};
	let i := 0;
	while ( i < roots.length() ) {
		root_order.add( roots[i]{name}, i );
		i++;
	}

	let best := null;
	for ( let root in roots ) {
		for ( let dist in _list_installed_in_root(root) ) {
			if ( _provides_module( dist, module_name, min_version ) ) {
				let candidate := _candidate_record(
					"root",
					module_name,
					min_version,
					dist{version},
					dist{name},
					root,
					dist{metadata_file},
					null,
				);
				candidate{installed} := dist;
				if (
					_better_dependency_candidate(
						best,
						candidate,
						root_order,
					)
				) {
					best := candidate;
				}
			}
		}
	}
	return best;
}

function _find_dependency_in_planned ( planned, module_name, min_version ) {
	let best := null;
	for ( let install_action in planned ) {
		if ( _planned_provides_module( install_action, module_name, min_version ) ) {
			let candidate := _candidate_record(
				"planned",
				module_name,
				min_version,
				install_action{metadata}{version},
				install_action{metadata}{name},
				install_action{target_root},
				install_action{metadata}{metadata_file},
				install_action,
			);
			if (
					best instanceof Null or
				compare_versions(
					candidate{version},
					best{version},
				) > 0 or
				(
					compare_versions(
						candidate{version},
						best{version},
					) == 0 and
					candidate{metadata_file} lt best{metadata_file}
				)
			) {
				best := candidate;
			}
		}
	}
	return best;
}

function _runtime_module_path ( module_name ) {
	return null if not starts_with( "" _ module_name, "std/" );

	let inc := [];
	if ( "inc" in __system__ ) {
		inc := __system__.get("inc");
	}
	return null if inc ≡ null;
	if ( not( inc instanceof Array ) ) {
		let separator := _is_windows_platform() ? ";" : ":";
		inc := split( "" _ inc, separator );
	}

	let relative := module_name _ ".zzm";
	for ( let root in inc ) {
		next if root eq "";
		let path := ( new Path(root) ).child(relative);
		return path if path.exists() and path.is_file();
	}
	return null;
}

function _runtime_include_dirs () {
	let out := [];
	let seen := {};
	let inc := [];
	if ( "inc" in __system__ ) {
		inc := __system__.get("inc");
	}
	return out if inc ≡ null;
	if ( not( inc instanceof Array ) ) {
		let separator := _is_windows_platform() ? ";" : ":";
		inc := split( "" _ inc, separator );
	}

	for ( let root in inc ) {
		next if root eq "";
		let path := ( new Path(root) ).absolute();
		_push_unique_string( out, seen, path.to_String() )
			if path.exists() and path.is_dir();
	}
	return out;
}

function _find_dependency_in_runtime ( module_name, min_version ) {
	return null if not _version_satisfies( "0", min_version );

	let module_path := _runtime_module_path(module_name);
	return null if module_path instanceof Null;

	let root := {
		name: "runtime",
		lib_dir: "",
		bin_dir: "",
		meta_dir: "",
	};
	let candidate := _candidate_record(
		"runtime",
		module_name,
		min_version,
		"0",
		"zuzu-runtime",
		root,
		module_path.to_String(),
		null,
	);
	candidate{module_file} := module_path.to_String();
	return candidate;
}

function _find_dependency_for_plan (
	planned,
	roots,
	module_name,
	min_version
) {
	let found := _find_dependency_in_planned(
		planned,
		module_name,
		min_version,
	);
	return found if not( found instanceof Null );
	found := _find_dependency_in_roots( roots, module_name, min_version );
	return found if not( found instanceof Null );
	return _find_dependency_in_runtime( module_name, min_version );
}

function _cycle_path ( stack, module_name ) {
	let path := [];
	let started := false;
	for ( let item in stack ) {
		started := true if item eq module_name;
		path.push(item) if started;
	}
	path.push(module_name);
	return join( " -> ", path );
}

function _stack_contains ( stack, value ) {
	for ( let item in stack ) {
		return true if item eq value;
	}
	return false;
}

function _remove_file_kind_order ( String kind ) {
	return kind eq "metadata" ? 1 : 0;
}

function _remove_file_cmp ( a, b ) {
	let kind_cmp := _remove_file_kind_order(a{kind}) <=>
		_remove_file_kind_order(b{kind});
	return kind_cmp if kind_cmp != 0;
	let path_cmp := a{path} cmp b{path};
	return path_cmp if path_cmp != 0;
	return a{kind} cmp b{kind};
}

function _removal_cmp ( a, b ) {
	let name_cmp := a{name} cmp b{name};
	return name_cmp if name_cmp != 0;
	let version_cmp := compare_versions( b{version}, a{version} );
	return version_cmp if version_cmp != 0;
	return a{metadata_file} cmp b{metadata_file};
}

function _owner_record ( dist ) {
	return {
		name: dist{name},
		version: dist{version},
		metadata_file: dist{metadata_file},
	};
}

function _same_owner ( left, right ) {
	return left{metadata_file} eq right{metadata_file};
}

function _owner_list_contains ( owners, owner ) {
	for ( let item in owners ) {
		return true if _same_owner( item, owner );
	}
	return false;
}

function _add_owner_to_list ( owners, owner ) {
	return false if _owner_list_contains( owners, owner );
	owners.push(owner);
	return true;
}

function _add_owner_for_path ( by_path, String path, owner ) {
	if ( not by_path.exists(path) ) {
		by_path.add( path, [] );
	}
	_add_owner_to_list( by_path.get(path), owner );
	return true;
}

function _remove_target_record ( target, options? ) {
	if ( target instanceof Dict ) {
		let type := target.exists("type") ? "" _ target{type} : "";
		let value := target.exists("value") ? "" _ target{value} : "";
		return {
			type: type,
			value: value,
			raw: target,
		};
	}
	return {
		type: _opt( options, "dist", false ) ? "distribution" : "module",
		value: "" _ target,
		raw: target,
	};
}

function _latest_module_name ( module_name ) {
	if ( not( module_name instanceof String ) ) {
		die "latest target must be a module name";
	}
	if ( module_name eq "" or _is_url(module_name) ) {
		die "latest target must be a module name";
	}
	let path := new Path(module_name);
	if ( path.exists() ) {
		die "latest target must be a module name";
	}
	return module_name;
}

function _latest_status ( installed_version, remote_version ) {
	return "not-installed" if installed_version instanceof Null;
	let comparison := compare_versions( installed_version, remote_version );
	return "current" if comparison == 0;
	return comparison < 0 ? "outdated" : "newer-local";
}

function _add_verify_target_error ( result, code, target, message ) {
	result{errors}.push(
		{
			code: code,
			target: target,
			message: message,
		},
	);
	return true;
}

class ZuzuzooLock {
	let lock_path := null;
	let owner_file := null;
	let acquired := false;

	method release () {
		return false if not acquired;
		_cleanup_path(owner_file);
		_cleanup_path(lock_path);
		acquired := false;
		return true;
	}
}

class Zuzuzoo {
	let lib_dir := null;
	let bin_dir := null;
	let meta_dir := null;
	let global := false;
	let windows := null;
	let home := null;
	let userprofile := null;
	let base_url := "https://zuzulang.org";
	let user_agent := null;
	let zuzu_command := "zuzu";
	let dependency_roots := [];
	let global_root := null;

	method _user_agent () {
		return not( user_agent instanceof Null ) ? user_agent : new UserAgent();
	}

	method config () {
		let resolved_windows := windows instanceof Null
			? _is_windows_platform()
			: windows;
		let resolved_global := global ? true: false;

		if ( resolved_windows and resolved_global ) {
			die "Global Windows installs are not supported";
		}

		let base_home := not( home instanceof Null ) ? home : Env.get( "HOME", "" );
		let base_userprofile := not( userprofile instanceof Null )
			? userprofile
			: Env.get( "USERPROFILE", "" );

		let resolved_lib := lib_dir;
		let resolved_bin := bin_dir;
		let resolved_meta := meta_dir;
		let needs_default := (
			resolved_lib instanceof Null or
			resolved_bin instanceof Null or
			resolved_meta instanceof Null
		);

		if ( resolved_windows ) {
			if ( needs_default ) {
				die "USERPROFILE required for Windows install"
					if base_userprofile eq "";
				let root := _join_dir(
					base_userprofile,
					".zuzu",
					true,
				);
				resolved_lib := _join_dir(
					root,
					"modules",
					true,
				)
					if resolved_lib instanceof Null;
				resolved_bin := _join_dir( root, "bin", true )
					if resolved_bin instanceof Null;
				resolved_meta := _join_dir( root, "meta", true )
					if resolved_meta instanceof Null;
			}
		}
		else if ( resolved_global ) {
			resolved_lib := "/var/lib/zuzu/modules"
				if resolved_lib instanceof Null;
			resolved_bin := "/usr/local/bin"
				if resolved_bin instanceof Null;
			resolved_meta := "/var/lib/zuzu/meta"
				if resolved_meta instanceof Null;
		}
		else {
			if ( needs_default ) {
				die "HOME required for POSIX user install"
					if base_home eq "";
				let root := _join_dir(
					base_home,
					".zuzu",
					false,
				);
				resolved_lib := _join_dir(
					root,
					"modules",
					false,
				)
					if resolved_lib instanceof Null;
				resolved_bin := _join_dir( root, "bin", false )
					if resolved_bin instanceof Null;
				resolved_meta := _join_dir(
					root,
					"meta",
					false,
				)
					if resolved_meta instanceof Null;
			}
		}

		return {
			lib_dir: resolved_lib,
			bin_dir: resolved_bin,
			meta_dir: resolved_meta,
			global: resolved_global,
			windows: resolved_windows,
		};
	}

	method acquire_lock ( operation, options? ) {
		if ( not _opt( options, "lock", true ) ) {
			return new ZuzuzooLock( acquired: false );
		}

		let cfg := self.config();
		let meta_path := new Path(cfg{meta_dir});
		_ensure_dir(meta_path);
		let lock_path := meta_path.child(".zuzuzoo.lock");
		let owner_file := lock_path.child("owner.json");
		let timeout := _opt( options, "lock_timeout", 30 );
		let poll := _opt( options, "lock_poll", 0.1 );
		let started := _now_epoch();

		while ( true ) {
			if ( lock_path.mkdir_exclusive() ) {
				let owner := {
					pid: Proc.pid(),
					created_at: _installed_at(),
					meta_dir: cfg{meta_dir},
					operation: "" _ operation,
				};
				try {
					( new JSON( pretty: true, canonical: true ) ).dump(
						owner_file,
						owner,
					);
				}
				catch ( Exception e ) {
					_cleanup_path(lock_path);
					throw e;
				}
				return new ZuzuzooLock(
					lock_path: lock_path,
					owner_file: owner_file,
					acquired: true,
				);
			}

			if ( _now_epoch() - started >= timeout ) {
				let owner_text := "";
				try {
					owner_text := owner_file.slurp_utf8();
				}
				catch ( Exception e ) {
					owner_text := "<unreadable>";
				}
				die(
					`Timed out waiting for Zuzuzoo lock ${lock_path} ` _
					`after ${timeout} seconds; owner=${owner_text}`
				);
			}
			sleep(poll);
		}
	}

	method _metadata_files () {
		return _metadata_files_in_dir( self.config(){meta_dir} );
	}

	method list_installed ( options? ) {
		let codec := new JSON();
		let installed := [];
		for ( let file in self._metadata_files() ) {
			let data := codec.load(file);
			let valid := _validate_installed_metadata(
				data,
				file.to_String(),
			);
			installed.push(valid);
		}

		return installed.sort( function ( a, b ) {
			let name_cmp := a{name} cmp b{name};
			return name_cmp if name_cmp != 0;
			return compare_versions( b{version}, a{version} );
		} );
	}

	method find_installed_module ( module_name, options? ) {
		let wanted := _module_key(module_name);
		for ( let dist in self.list_installed(options) ) {
			for ( let module in dist{installed}{modules} ) {
				let installed_as := _module_key(
					module{install_as},
				);
				if ( installed_as eq wanted ) {
					return dist;
				}
			}
		}
		return null;
	}

	method find_installed_distribution ( distribution_name, options? ) {
		let wanted := "" _ distribution_name;
		for ( let dist in self.list_installed(options) ) {
			return dist if dist{name} eq wanted;
		}
		return null;
	}

	method query ( module_name, options? ) {
		return self.find_installed_module( module_name, options );
	}

	method query_distribution ( distribution_name, options? ) {
		return self.find_installed_distribution(
			distribution_name,
			options,
		);
	}

	method is_installed ( module_name, min_version? ) {
		let found := self.find_installed_module(module_name);
		return false if found instanceof Null;
		if ( not( min_version instanceof Null ) ) {
			let comparison := compare_versions(
				found{version},
				min_version,
			);
			return comparison >= 0;
		}
		return true;
	}

	method installed_version ( module_name ) {
		let found := self.find_installed_module(module_name);
		return found instanceof Null ? null : found{version};
	}

	method pretty_json ( value ) {
		let codec := new JSON( pretty: true, canonical: true );
		return codec.encode(value);
	}

	method format_json ( value, options? ) {
		return self.pretty_json(value);
	}

	method _verify_module_file ( result, dist, entry ) {
		let path := _path_child(
			dist{installed}{lib_dir},
			entry{install_as},
		);
		let file := {
			kind: "module",
			distribution: dist{name},
			version: dist{version},
			install_as: entry{install_as},
			path: path.to_String(),
			exists: path.exists(),
			expected_sha256: entry{sha256},
			expected_size: entry.get( "size", null ),
			actual_sha256: null,
			actual_size: null,
			hash_ok: false,
			size_ok: null,
		};
		if ( path.exists() ) {
			let bytes := path.slurp();
			file{actual_sha256} := sha256_hex(bytes);
			file{actual_size} := path.size();
			file{hash_ok} := file{actual_sha256} eq entry{sha256};
			if ( file{expected_size} != null ) {
				file{size_ok} := file{actual_size} == file{expected_size};
				if ( not file{size_ok} ) {
					result{size_mismatches}.push(file);
				}
			}
			if ( not file{hash_ok} ) {
				result{hash_mismatches}.push(file);
			}
		}
		else {
			result{missing_files}.push(file);
		}
		result{files}.push(file);
		result{checked_files}.push(file);
		return file;
	}

	method _verify_script_file ( result, dist, entry ) {
		let path := _path_child(
			dist{installed}{bin_dir},
			entry{install_as},
		);
		let file := {
			kind: "script",
			distribution: dist{name},
			version: dist{version},
			install_as: entry{install_as},
			path: path.to_String(),
			exists: path.exists(),
			expected_sha256: entry{sha256},
			expected_size: entry.get( "size", null ),
			actual_sha256: null,
			actual_size: null,
			hash_ok: false,
			size_ok: null,
		};
		if ( path.exists() ) {
			let bytes := path.slurp();
			file{actual_sha256} := sha256_hex(bytes);
			file{actual_size} := path.size();
			file{hash_ok} := file{actual_sha256} eq entry{sha256};
			if ( file{expected_size} != null ) {
				file{size_ok} := file{actual_size} == file{expected_size};
				if ( not file{size_ok} ) {
					result{size_mismatches}.push(file);
				}
			}
			if ( not file{hash_ok} ) {
				result{hash_mismatches}.push(file);
			}
		}
		else {
			result{missing_files}.push(file);
		}
		result{files}.push(file);
		result{checked_files}.push(file);

		for ( let wrapper in entry.get( "wrappers", [] ) ) {
			let wrapper_path := _path_child(
				dist{installed}{bin_dir},
				wrapper,
			);
			let wrapper_file := {
				kind: "wrapper",
				distribution: dist{name},
				version: dist{version},
				install_as: wrapper,
				path: wrapper_path.to_String(),
				exists: wrapper_path.exists(),
				expected_sha256: null,
				actual_sha256: null,
				hash_ok: null,
			};
			if ( not wrapper_file{exists} ) {
				result{missing_files}.push(wrapper_file);
			}
			result{files}.push(wrapper_file);
			result{wrapper_files}.push(wrapper_file);
		}
		return file;
	}

	method verify ( targets, options? ) {
		let roots := self.dependency_roots(options);
		let target_root := roots[0];
		let installed := _list_installed_in_root(target_root);
		let result := {
			ok: true,
			target_root: target_root,
			targets: [],
			distributions: [],
			files: [],
			checked_files: [],
			wrapper_files: [],
			missing_files: [],
			hash_mismatches: [],
			size_mismatches: [],
			skipped_duplicates: [],
			errors: [],
		};

		let seen := {};
		for ( let target in _target_list(targets) ) {
			let record := _remove_target_record( target, options );
			if ( record{type} eq "dist" ) {
				record{type} := "distribution";
			}
			record{matches} := [];
			result{targets}.push(record);

			if (
				(
					record{type} ne "module" and
					record{type} ne "distribution"
				) or
				record{value} eq ""
			) {
				_add_verify_target_error(
					result,
					"invalid-target",
					record,
					"verify target must be a module or distribution",
				);
				next;
			}

			let matches := record{type} eq "module"
				? self._module_remove_matches(
					installed,
					record{value},
				)
				: self._distribution_remove_matches(
					installed,
					record{value},
				);
			for ( let match in matches ) {
				record{matches}.push(
					{
						name: match{name},
						version: match{version},
						metadata_file: match{metadata_file},
					},
				);
			}

			if ( matches.length() == 0 ) {
				_add_verify_target_error(
					result,
					"missing-target",
					record,
					"verify target is not installed",
				);
				next;
			}
			if ( record{type} eq "module" and matches.length() > 1 ) {
				_add_verify_target_error(
					result,
					"ambiguous-target",
					record,
					"module target has multiple owners",
				);
				result{errors}[ result{errors}.length() - 1 ]{matches} :=
					record{matches};
				next;
			}

			for ( let dist in matches ) {
				let key := dist{metadata_file};
				if ( seen.exists(key) ) {
					result{skipped_duplicates}.push(
						{
							target: record,
							name: dist{name},
							version: dist{version},
							metadata_file: dist{metadata_file},
						},
					);
					next;
				}
				seen.add( key, true );
				result{distributions}.push(
					{
						name: dist{name},
						version: dist{version},
						metadata_file: dist{metadata_file},
					},
				);
				for ( let module in dist{installed}{modules} ) {
					self._verify_module_file(
						result,
						dist,
						module,
					);
				}
				for ( let script in dist{installed}{scripts} ) {
					self._verify_script_file(
						result,
						dist,
						script,
					);
				}
			}
		}

		result{ok} := (
			result{errors}.length() == 0 and
			result{missing_files}.length() == 0 and
			result{hash_mismatches}.length() == 0 and
			result{size_mismatches}.length() == 0
		);
		return result;
	}

	method latest ( module_name, options? ) {
		let module := _latest_module_name(module_name);
		let base := _trim_right_slash(
			"" _ _opt( options, "base_url", base_url ),
		);
		let url := base _ "/module/" _ module _ ".json";
		let ua := _opt( options, "user_agent", self._user_agent() );
		let req := ua.build_request( "GET", url );
		_progress( options, "downloading latest metadata " _ url );
		let response := ua.send(req);
		response.expect_success();
		let remote_url := url;
		if ( response can "url" ) {
			remote_url := response.url();
		}
		_progress( options, "received latest metadata " _ remote_url );

		let metadata := _validate_source_metadata(
			response.json(),
			remote_url,
		);
		if ( not metadata.exists("status") ) {
			metadata{status} := "stable";
		}
		if (
			metadata.exists("status") and
			metadata{status} eq "trial"
		) {
			die(
				"Trial distributions are not available through " _
				"module-name latest endpoints"
			);
		}

		let installed := self.find_installed_module( module, options );
			let installed_version := installed instanceof Null
			? null
			: installed{version};
		let status := _latest_status(
			installed_version,
			metadata{version},
		);

		return {
			ok: true,
			module_name: module,
			status: status,
			can_upgrade: status eq "outdated",
			installed_version: installed_version,
			remote_version: metadata{version},
			remote_distribution: metadata{name},
			remote_status: metadata{status},
			url: url,
			remote_url: remote_url,
			installed: installed,
			remote_metadata: metadata,
		};
	}

	method can_upgrade ( module_name, options? ) {
		return self.latest( module_name, options );
	}

	method fetch_source ( target, options? ) {
		let value := "" _ target;
		let file := new Path(value);
		if ( file.exists() and file.is_file() ) {
			_progress( options, "using local archive " _ file.to_String() );
			let source := {
				type: "file",
				value: value,
				path: file.to_String(),
				path_obj: file,
			};
			_check_expected_source_sha(
				source,
				_opt( options, "expected_sha256", null ),
			);
			return source;
		}

		let source_type := _is_url(value) ? "url" : "module";
		let url := value;
		if ( source_type eq "module" ) {
			let base := _trim_right_slash(
				"" _ _opt( options, "base_url", base_url ),
			);
			url := base _ "/module/" _ value;
		}

		let cache_dir := _opt( options, "cache_dir", null );
		if ( not( cache_dir instanceof Null ) ) {
			let paths := _cache_paths( cache_dir, url );
			let cached := _validate_cache_entry(paths);
			if ( cached ) {
				_progress(
					options,
					"using cached archive for " _ value _ " from " _
						paths{archive}.to_String(),
				);
				let source := {
					type: source_type,
					value: value,
					url: url,
					resolved_url: cached{resolved_url},
					path: paths{archive}.to_String(),
					path_obj: paths{archive},
					cache_hit: true,
					cache_sidecar: paths{sidecar}.to_String(),
				};
				_check_expected_source_sha(
					source,
					_opt( options, "expected_sha256", null ),
				);
				return source;
			}
			_delete_cache_entry(paths);
		}

		let temp_dir := _new_temp_dir( options, "zuzuzoo-source-" );
		let temp_path := temp_dir.child("source.archive");
		let ua := _opt( options, "user_agent", self._user_agent() );
		let req := ua.build_request( "GET", url )
			.download_to( temp_path.to_String() );
		_progress( options, "downloading " _ value _ " from " _ url );
		let response := ua.send(req);

		let download_url := url;
		if ( not _response_success(response) and source_type eq "module" ) {
			_progress(
				options,
				"module archive download failed from " _ url _ " (" _
					_response_status_text(response) _
					"); checking latest metadata",
			);
			_cleanup_path(temp_path);

			let latest_info := self.latest( value, options );
			let archive_url := _archive_url_from_latest(latest_info);
			req := ua.build_request( "GET", archive_url )
				.download_to( temp_path.to_String() );
			_progress(
				options,
				"downloading " _ value _ " from " _ archive_url,
			);
			response := ua.send(req);
			download_url := archive_url;
		}

		if ( not _response_success(response) ) {
			_cleanup_path(temp_dir);
			die(
				"Source download failed (target=" _ value _
				", source_type=" _ source_type _
				", url=" _ download_url _
				"): HTTP request failed (" _
					_response_status_text(response) _ ")"
			);
		}

		let resolved_url := download_url;
		if ( response can "url" ) {
			resolved_url := response.url();
		}
		_progress(
			options,
			"downloaded " _ value _ " from " _ resolved_url _ " to " _
				temp_path.to_String(),
		);

		let source := {
			type: source_type,
			value: value,
			url: url,
			resolved_url: resolved_url,
			path: temp_path.to_String(),
			path_obj: temp_path,
			temp_dir: temp_dir,
		};
		_check_expected_source_sha(
			source,
			_opt( options, "expected_sha256", null ),
		);

		if ( not( cache_dir instanceof Null ) ) {
			let paths := _cache_paths( cache_dir, url );
			try {
				let sidecar := _write_cache_entry(
					paths,
					source,
					temp_path,
				);
				source{path} := paths{archive}.to_String();
				source{path_obj} := paths{archive};
				source{cache_hit} := false;
				source{cache_sidecar} := paths{sidecar}.to_String();
				source{cache_metadata} := sidecar;
				_progress(
					options,
					"cached " _ value _ " at " _
						paths{archive}.to_String(),
				);
				_cleanup_path(temp_dir);
			}
			catch ( Exception e ) {
				_cleanup_path(temp_dir);
				die _corrupt_archive_error( source, e );
			}
		}

		return source;
	}

	method load_distribution ( target, options? ) {
		let source := null;
		let work_dir := null;
		try {
			source := self.fetch_source( target, options );
			let source_path := new Path( source{path} );
			let archive := null;
			try {
				archive := Archive.decode( source_path.slurp() );
			}
			catch ( Exception e ) {
				die _corrupt_archive_error( source, e );
			}
			let root_name := _safe_archive_root( archive, source{path} );
			work_dir := _new_temp_dir( options, "zuzuzoo-work-" );
			let root_dir := work_dir.child(root_name);
			root_dir.mkdir();
			_progress(
				options,
				"extracting " _ source{path} _ " to " _
					work_dir.to_String(),
			);
			_extract_archive( archive, root_name, root_dir );

			let metadata_file := root_dir.child("zuzu-distribution.json");
			if ( not metadata_file.exists() ) {
				die(
					`Invalid archive ${source{path}}: ` _
					"missing zuzu-distribution.json"
				);
			}
			let codec := new JSON( pairlists: true );
			let metadata := _validate_source_metadata(
				codec.load(metadata_file),
				metadata_file.to_String(),
			);

			let expected_root := metadata{name} _ "-" _ metadata{version};
			if ( root_name ne expected_root ) {
				die(
					`Invalid archive ${source{path}}: root ${root_name} ` _
					`does not match ${expected_root}`
				);
			}

			let build_result := null;
			let build_file := root_dir.child("Build.zzs");
			if ( build_file.exists() and build_file.is_file() ) {
				_progress(
					options,
					"building " _ metadata{name} _ " " _
						metadata{version} _ " with Build.zzs",
				);
				build_result := Proc.run(
					_opt( options, "zuzu_command", zuzu_command ),
					[ "Build.zzs" ],
					{
						cwd: root_dir.to_String(),
						capture_stdout: true,
						capture_stderr: true,
					},
				);
				if ( not Proc.is_success(build_result) ) {
					die(
						"Build.zzs failed: " _
						Proc.status_text(build_result)
					);
				}
				metadata := _validate_source_metadata(
					codec.load(metadata_file),
					metadata_file.to_String(),
				);
				let post_build_root := metadata{name} _ "-" _
					metadata{version};
				if ( root_name ne post_build_root ) {
					die(
						`Invalid archive ${source{path}}: root ${root_name} ` _
						`does not match ${post_build_root}`
					);
				}
			}

			let module_sources := _discover_files(
				root_dir,
				"modules",
				".zzm",
			);
			let script_sources := _discover_scripts(root_dir);
			let tests := _discover_files( root_dir, "tests", ".zzs" );
			let modules := module_sources.map( function ( source ) {
				return {
					source: source,
					install_as: _module_install_name(source),
				};
			} );
			let scripts := script_sources.map( function ( source ) {
				return {
					source: source,
					install_as: _script_install_name(source),
				};
			} );

			let loaded := {
				source: source,
				archive: archive,
				work_dir: work_dir.to_String(),
				root: root_dir.to_String(),
				work_dir_obj: work_dir,
				root_obj: root_dir,
				root_name: root_name,
				metadata: metadata,
				modules: modules,
				scripts: scripts,
				tests: tests,
				build: build_result,
			};
			if ( not _opt( options, "keep_work_dirs", false ) ) {
				_cleanup_source( source, options );
				_cleanup_path(work_dir);
			}
			return loaded;
		}
		catch ( Exception e ) {
			_cleanup_source( source, options );
			_cleanup_path(work_dir)
				if not _opt( options, "keep_work_dirs", false );
			throw e;
		}
	}

	method dependency_roots ( options? ) {
		let cfg := self.config();
		let target := _root_from_config( "target", "target", cfg );
		let roots := [];
		let seen := {};
		_add_root( roots, seen, target );

		if ( not cfg{global} and not cfg{windows} ) {
			let global_override := _opt(
				options,
				"global_root",
				global_root,
			);
			let global_dependency_root := null;
			if ( not( global_override instanceof Null ) ) {
				global_dependency_root := _root_override(
					global_override,
					"global",
					"global",
					"global",
				);
			}
			else {
				let global_cfg := new Zuzuzoo(
					global: true,
					windows: false,
					home: home,
					userprofile: userprofile,
				).config();
				global_dependency_root := _root_from_config(
					"global",
					"global",
					global_cfg,
				);
			}
			_add_root(
				roots,
				seen,
				global_dependency_root,
			);
		}

		let user_cfg := new Zuzuzoo(
			global: false,
			windows: cfg{windows},
			home: home,
			userprofile: userprofile,
		).config();
		_add_root(
			roots,
			seen,
			_root_from_config( "user", "user", user_cfg ),
		);

		let ctor_roots := dependency_roots instanceof Null
			? []
			: dependency_roots;
		for ( let root in ctor_roots ) {
			let where := (
				root instanceof Dict and root.exists("name")
			)
				? root{name}
				: "constructor";
			_add_root(
				roots,
				seen,
				_custom_root( root, where ),
			);
		}

		let option_roots := _opt( options, "dependency_roots", [] );
		for ( let root in option_roots ) {
			let where := (
				root instanceof Dict and root.exists("name")
			)
				? root{name}
				: "options";
			_add_root(
				roots,
				seen,
				_custom_root( root, where ),
			);
		}

		return roots;
	}

	method find_dependency ( module_name, min_version?, options? ) {
		let planned := _opt( options, "planned_installs", [] );
		return _find_dependency_for_plan(
			planned,
			self.dependency_roots(options),
			module_name,
			min_version instanceof Null ? "0" : min_version,
		);
	}

	method _add_removal ( removals, removal_seen, dist, root, reason ) {
		let key := dist{metadata_file};
		if ( removal_seen.exists(key) ) {
			removal_seen.get(key){reasons}.push(reason);
			return false;
		}
		let removal := {
			name: dist{name},
			version: dist{version},
			metadata_file: dist{metadata_file},
			root: root,
			reasons: [ reason ],
			distribution: dist,
		};
		removal_seen.add( key, removal );
		removals.push(removal);
		return true;
	}

	method _plan_target_root_removals (
		plan,
		target_installed,
		target_root
	) {
		let removal_seen := {};
			for ( let install_action in plan{installs} ) {
				for ( let dist in target_installed ) {
					if ( dist{name} eq install_action{metadata}{name} ) {
						let reason := dist{version} eq install_action{metadata}{version}
							? "reinstall"
							: "prior-version";
					self._add_removal(
						plan{removals},
						removal_seen,
						dist,
						target_root,
						reason,
					);
				}
			}
		}

			for ( let install_action in plan{installs} ) {
				for ( let module in install_action{modules} ) {
					let destination := _path_join(
						target_root{lib_dir},
					module{install_as},
					target_root{windows},
				);
				for ( let dist in target_installed ) {
					for ( let owned in dist{installed}{modules} ) {
						if ( owned{install_as} eq module{install_as} ) {
							plan{ownership_conflicts}.push(
									{
										kind: "module",
										install_as: module{install_as},
										destination: destination,
										planned_distribution: install_action{metadata}{name},
										planned_version: install_action{metadata}{version},
										owner_distribution: dist{name},
									owner_version: dist{version},
									owner_metadata_file: dist{metadata_file},
									root: target_root,
								},
							);
							self._add_removal(
								plan{removals},
								removal_seen,
								dist,
								target_root,
								"owner-conflict",
							);
						}
					}
				}
			}

				for ( let script in install_action{scripts} ) {
					let destination := _path_join(
					target_root{bin_dir},
					script{install_as},
					target_root{windows},
				);
				for ( let dist in target_installed ) {
					for ( let owned in dist{installed}{scripts} ) {
						if ( owned{install_as} eq script{install_as} ) {
							plan{ownership_conflicts}.push(
									{
										kind: "script",
										install_as: script{install_as},
										destination: destination,
										planned_distribution: install_action{metadata}{name},
										planned_version: install_action{metadata}{version},
										owner_distribution: dist{name},
									owner_version: dist{version},
									owner_metadata_file: dist{metadata_file},
									root: target_root,
								},
							);
							self._add_removal(
								plan{removals},
								removal_seen,
								dist,
								target_root,
								"owner-conflict",
							);
						}
					}
				}
			}
		}
		return plan;
	}

	method _module_remove_matches ( installed, module_name ) {
		let wanted := _module_key(module_name);
		let matches := [];
		for ( let dist in installed ) {
			for ( let module in dist{installed}{modules} ) {
				if ( _module_key( module{install_as} ) eq wanted ) {
					matches.push(dist);
					last;
				}
			}
		}
		return matches;
	}

	method _distribution_remove_matches ( installed, distribution_name ) {
		let wanted := "" _ distribution_name;
		let matches := [];
		for ( let dist in installed ) {
			matches.push(dist) if dist{name} eq wanted;
		}
		return matches;
	}

	method _remove_owner_map ( installed, target_root ) {
		let by_path := {};
		for ( let dist in installed ) {
			let owner := _owner_record(dist);
			for ( let module in dist{installed}{modules} ) {
				_add_owner_for_path(
					by_path,
					_path_join(
						target_root{lib_dir},
						module{install_as},
						target_root{windows},
					),
					owner,
				);
			}
			for ( let script in dist{installed}{scripts} ) {
				_add_owner_for_path(
					by_path,
					_path_join(
						target_root{bin_dir},
						script{install_as},
						target_root{windows},
					),
					owner,
				);
				for ( let wrapper in script.get( "wrappers", [] ) ) {
					_add_owner_for_path(
						by_path,
						_path_join(
							target_root{bin_dir},
							wrapper,
							target_root{windows},
						),
						owner,
					);
				}
			}
		}
		return by_path;
	}

	method _add_remove_file (
		plan,
		file_seen,
		owner_map,
		planned_metadata,
		kind,
		path,
		dist,
		install_as
	) {
		return false if file_seen.exists(path);
		file_seen.add( path, true );

		let owners := kind eq "metadata"
			? [ _owner_record(dist) ]
			: owner_map.get( path, [ _owner_record(dist) ] );
		let planned_owners := [];
		let kept_owners := [];
		for ( let owner in owners ) {
			if ( planned_metadata.exists(owner{metadata_file}) ) {
				planned_owners.push(owner);
			}
			else {
				kept_owners.push(owner);
			}
		}

		let blocked := kind ne "metadata" and kept_owners.length() > 0;
		let file := {
			kind: kind,
			path: path,
			exists: ( new Path(path) ).exists(),
			owners: owners,
			planned_owners: planned_owners,
			kept_owners: kept_owners,
			blocked: blocked,
		};
		file{install_as} := install_as if not( install_as instanceof Null );
		plan{files}.push(file);

		if ( blocked ) {
			let conflict := {
				kind: kind,
				path: path,
				install_as: install_as,
				owners: owners,
				planned_owners: planned_owners,
				kept_owners: kept_owners,
			};
			plan{shared_file_conflicts}.push(conflict);
			plan{errors}.push(
				{
					code: "shared-file-conflict",
					message: "file is also owned by a kept distribution",
					path: path,
					owners: owners,
					kept_owners: kept_owners,
				},
			);
		}
		return true;
	}

	method _build_remove_files ( plan, installed, target_root ) {
		let owner_map := self._remove_owner_map( installed, target_root );
		let planned_metadata := {};
		for ( let removal in plan{removals} ) {
			planned_metadata.add( removal{metadata_file}, true );
		}

		let file_seen := {};
		for ( let removal in plan{removals} ) {
			let dist := removal{distribution};
			for ( let module in dist{installed}{modules} ) {
				self._add_remove_file(
					plan,
					file_seen,
					owner_map,
					planned_metadata,
					"module",
					_path_join(
						target_root{lib_dir},
						module{install_as},
						target_root{windows},
					),
					dist,
					module{install_as},
				);
			}
			for ( let script in dist{installed}{scripts} ) {
				self._add_remove_file(
					plan,
					file_seen,
					owner_map,
					planned_metadata,
					"script",
					_path_join(
						target_root{bin_dir},
						script{install_as},
						target_root{windows},
					),
					dist,
					script{install_as},
				);
				for ( let wrapper in script.get( "wrappers", [] ) ) {
					self._add_remove_file(
						plan,
						file_seen,
						owner_map,
						planned_metadata,
						"wrapper",
						_path_join(
							target_root{bin_dir},
							wrapper,
							target_root{windows},
						),
						dist,
						wrapper,
					);
				}
			}
		}

		for ( let removal in plan{removals} ) {
			self._add_remove_file(
				plan,
				file_seen,
				owner_map,
				planned_metadata,
				"metadata",
				removal{metadata_file},
				removal{distribution},
				null,
			);
		}

		plan{files} := plan{files}.sort(_remove_file_cmp);
		plan{shared_file_conflicts} :=
			plan{shared_file_conflicts}.sort(
				fn ( a, b ) -> a{path} cmp b{path},
			);
		return plan;
	}

	method plan_remove ( targets, options? ) {
		let roots := self.dependency_roots(options);
		let target_root := roots[0];
		let installed := _list_installed_in_root(target_root);
		let plan := {
			ok: true,
			target_root: target_root,
			targets: [],
			removals: [],
			files: [],
			shared_file_conflicts: [],
			skipped_duplicates: [],
			errors: [],
		};

		let removal_seen := {};
		for ( let target in _target_list(targets) ) {
			let record := _remove_target_record( target, options );
			if ( record{type} eq "dist" ) {
				record{type} := "distribution";
			}
			record{matches} := [];
			plan{targets}.push(record);

			if (
				(
					record{type} ne "module" and
					record{type} ne "distribution"
				) or
				record{value} eq ""
			) {
				plan{errors}.push(
					{
						code: "invalid-target",
						target: record,
						message: "remove target must be a module or distribution",
					},
				);
				next;
			}

			let matches := record{type} eq "module"
				? self._module_remove_matches(
					installed,
					record{value},
				)
				: self._distribution_remove_matches(
					installed,
					record{value},
				);
			for ( let match in matches ) {
				record{matches}.push(
					{
						name: match{name},
						version: match{version},
						metadata_file: match{metadata_file},
					},
				);
			}

			if ( matches.length() == 0 ) {
				plan{errors}.push(
					{
						code: "missing-target",
						target: record,
						message: "remove target is not installed",
					},
				);
				next;
			}
			if ( record{type} eq "module" and matches.length() > 1 ) {
				plan{errors}.push(
					{
						code: "ambiguous-target",
						target: record,
						message: "module target has multiple owners",
						matches: record{matches},
					},
				);
				next;
			}

			for ( let dist in matches ) {
				let added := self._add_removal(
					plan{removals},
					removal_seen,
					dist,
					target_root,
					record{type} eq "module"
						? "requested-module"
						: "requested-distribution",
				);
				if ( not added ) {
					plan{skipped_duplicates}.push(
						{
							target: record,
							name: dist{name},
							version: dist{version},
							metadata_file: dist{metadata_file},
						},
					);
				}
			}
		}

		plan{removals} := plan{removals}.sort(_removal_cmp);
		self._build_remove_files( plan, installed, target_root );
		plan{ok} := (
			plan{errors}.length() == 0 and
			plan{shared_file_conflicts}.length() == 0
		);
		return plan;
	}

	method plan_install ( targets, options? ) {
		let roots := self.dependency_roots(options);
		let target_root := roots[0];
		let plan := {
			target_root: target_root,
			dependency_roots: roots,
			installs: [],
			removals: [],
			satisfied_dependencies: [],
			dependency_graph: {
				nodes: [],
				edges: [],
			},
			ownership_conflicts: [],
		};

		let planned := [];
		let planned_by_name := {};
		let status_by_name := {};
		let seen_targets := {};
		let loaded_work := [];

		function resolve ( target, requested, dependency_of, min_version, stack ) {
			let target_text := "" _ target;
			if ( requested ) {
				return null if seen_targets.exists(target_text);
				seen_targets.add( target_text, true );
			}
			else {
				let found := _find_dependency_for_plan(
					planned,
					roots,
					target_text,
					min_version,
				);
				if ( not( found instanceof Null ) ) {
					if (
						found{source} eq "planned" and
						status_by_name.get(found{distribution}, "") eq "visiting"
					) {
						die "Dependency cycle detected: " _
							_cycle_path( stack, target_text );
					}
					let satisfied := found;
					satisfied{requested_by} := dependency_of instanceof Null
						? null
						: dependency_of{metadata}{name};
					plan{satisfied_dependencies}.push(satisfied);
					return null;
				}
				if ( _stack_contains( stack, target_text ) ) {
					die "Dependency cycle detected: " _
						_cycle_path( stack, target_text );
				}
			}

			let dist := self.load_distribution(
				target_text,
				_copy_options_with( options, "keep_work_dirs", true ),
			);
			loaded_work.push(dist);
			if (
				dist{source}{type} eq "module" and
				dist{metadata}.exists("status") and
				dist{metadata}{status} eq "trial"
			) {
				die(
					"Trial distributions are not available through " _
					"module-name endpoints"
				);
			}
			if (
				not requested and
				not _loaded_distribution_provides(
					dist,
					target_text,
					min_version,
				)
			) {
				let dep := {
					module_name: target_text,
					min_version: min_version,
				};
				_cleanup_source( dist{source}, options );
				_cleanup_path(dist{work_dir_obj})
					if not _opt( options, "keep_work_dirs", false );
				die _dependency_conflict_message(
					dep,
					dependency_of,
					stack,
					null,
					dist,
				);
			}

			let dist_name := dist{metadata}{name};
			if ( planned_by_name.exists(dist_name) ) {
				let existing := planned_by_name.get(dist_name);
				if (
					existing{metadata}{version} ne
					dist{metadata}{version}
				) {
					_cleanup_source( dist{source}, options );
					_cleanup_path(dist{work_dir_obj})
						if not _opt( options, "keep_work_dirs", false );
					if ( requested ) {
						die _planned_version_conflict_message(
							dist_name,
							existing,
							dist,
							target_text,
						);
					}
					let dep := {
						module_name: target_text,
						min_version: min_version,
					};
					die _dependency_conflict_message(
						dep,
						dependency_of,
						stack,
						existing,
						dist,
					);
				}
				_cleanup_source( dist{source}, options );
				_cleanup_path(dist{work_dir_obj})
					if not _opt( options, "keep_work_dirs", false );
				return existing;
			}

			let dependencies := _dependency_entries(dist{metadata});
			let install_action := {
				action: "install",
				target: target_text,
				requested: requested ? true : false,
				dependency_of: dependency_of instanceof Null
					? null
					: dependency_of{metadata}{name},
				source: dist{source},
				metadata: dist{metadata},
				modules: dist{modules},
				scripts: dist{scripts},
				tests: dist{tests},
				dependencies: dependencies,
				target_root: target_root,
				root: dist{root},
				work_dir: dist{work_dir},
				root_obj: dist{root_obj},
				work_dir_obj: dist{work_dir_obj},
			};
			planned.push(install_action);
			planned_by_name.add( dist_name, install_action );
			status_by_name.add( dist_name, "visiting" );
			plan{dependency_graph}{nodes}.push(
				{
					name: dist_name,
					version: dist{metadata}{version},
					target: target_text,
					requested: requested ? true : false,
				},
			);

			let next_stack := stack;
			if ( dist{source}{type} eq "module" ) {
				next_stack := [];
				for ( let item in stack ) {
					next_stack.push(item);
				}
				next_stack.push(target_text);
			}

			for ( let dep in dependencies ) {
				let found := _find_dependency_for_plan(
					planned,
					roots,
					dep{module_name},
					dep{min_version},
				);
				if ( not( found instanceof Null ) ) {
					if (
						found{source} eq "planned" and
						status_by_name.get(found{distribution}, "") eq "visiting"
					) {
						die "Dependency cycle detected: " _
							_cycle_path( next_stack, dep{module_name} );
					}
					let satisfied := found;
					satisfied{requested_by} := dist_name;
					plan{satisfied_dependencies}.push(satisfied);
					plan{dependency_graph}{edges}.push(
						{
							from: dist_name,
							module_name: dep{module_name},
							min_version: dep{min_version},
							status: found{source} eq "planned"
								? "planned"
								: "satisfied",
							to: found{distribution},
							root: found.exists("root") ? found{root} : null,
						},
					);
				}
				else {
					let dep_install := resolve(
						dep{module_name},
						false,
						install_action,
						dep{min_version},
						next_stack,
					);
					plan{dependency_graph}{edges}.push(
						{
							from: dist_name,
							module_name: dep{module_name},
							min_version: dep{min_version},
							status: "planned",
							to: dep_install instanceof Null
								? null
								: dep_install{metadata}{name},
							root: target_root,
						},
					);
				}
			}

			status_by_name.set( dist_name, "done" );
			plan{installs}.push(install_action);
			return install_action;
		}

		try {
			for ( let target in _target_list(targets) ) {
				resolve( target, true, null, "0", [] );
			}
		}
		catch ( Exception e ) {
			_cleanup_loaded_work_dirs(loaded_work, options);
			throw e;
		}

		self._plan_target_root_removals(
			plan,
			_list_installed_in_root(target_root),
			target_root,
		);

		return plan;
	}

	method run_distribution_tests ( install_action, options? ) {
		let results := [];
		let include_dirs := [];
		let seen_include_dirs := {};
		let own_modules := _path_child( install_action{root}, "modules" );
		_push_unique_string(
			include_dirs,
			seen_include_dirs,
			own_modules.to_String(),
		) if own_modules.exists() and own_modules.is_dir();
		for ( let include_dir in _opt( options, "test_include_dirs", [] ) ) {
			_push_unique_string(
				include_dirs,
				seen_include_dirs,
				include_dir,
			);
		}

		for ( let test in install_action{tests} ) {
			_progress(
				options,
				"testing " _ install_action{metadata}{name} _ " " _
					install_action{metadata}{version} _ ": " _ test,
			);
			let argv := include_dirs.map( fn d -> "-I" _ d );
			argv.push(test);
			let run_result := Proc.run(
				_opt( options, "zuzu_command", zuzu_command ),
				argv,
				{
					cwd: install_action{root},
					capture_stdout: true,
					capture_stderr: true,
				},
			);
			let parsed := parse_tap(run_result{stdout});
			results.push(
				{
					test: test,
					ok: _test_ok( parsed, run_result ),
					status: Proc.status_text(run_result),
					result: run_result,
					tap: parsed,
					stdout: run_result{stdout},
					stderr: run_result{stderr},
				},
			);
		}
		let ok := true;
		for ( let result in results ) {
			ok := false if not result{ok};
		}
		return {
			ok: ok,
			tests: results,
			distribution: install_action{metadata}{name},
			version: install_action{metadata}{version},
		};
	}

	method execute_removal ( removal_action, options? ) {
		_progress(
			options,
			"removing " _ removal_action{name} _ " " _
				removal_action{version},
		);
		let warnings := [];
		let removed := [];
		let dist := removal_action{distribution};
		let root := removal_action{root};

		function remove_file ( path, kind ) {
			if ( path.exists() ) {
				path.remove();
				removed.push(
					{
						kind: kind,
						path: path.to_String(),
					},
				);
			}
			else {
				warnings.push(
					{
						kind: kind,
						path: path.to_String(),
						message: "missing file",
					},
				);
			}
		}

		for ( let module in dist{installed}{modules} ) {
			remove_file(
				_path_child( root{lib_dir}, module{install_as} ),
				"module",
			);
		}
		for ( let script in dist{installed}{scripts} ) {
			remove_file(
				_path_child( root{bin_dir}, script{install_as} ),
				"script",
			);
			for ( let wrapper in script.get( "wrappers", [] ) ) {
				remove_file(
					_path_child( root{bin_dir}, wrapper ),
					"wrapper",
				);
			}
		}
		remove_file( new Path( removal_action{metadata_file} ), "metadata" );

		return {
			ok: true,
			name: removal_action{name},
			version: removal_action{version},
			removed: removed,
			warnings: warnings,
		};
	}

	method _install_action ( install_action, installed_at, options? ) {
		let root := install_action{target_root};
		let module_records := [];
		let script_records := [];

		for ( let module in install_action{modules} ) {
			let source := _path_child(
				install_action{root},
				module{source},
			);
			let destination := _path_child(
				root{lib_dir},
				module{install_as},
			);
			_progress(
				options,
				"installing module " _ module{install_as} _ " to " _
					destination.to_String(),
			);
			let written := _copy_file_atomic(source, destination, null);
			module_records.push(
				{
					source: module{source},
					install_as: module{install_as},
					sha256: written{sha256},
					size: written{size},
				},
			);
		}

		for ( let script in install_action{scripts} ) {
			let source := _path_child(
				install_action{root},
				script{source},
			);
			let destination := _path_child(
				root{bin_dir},
				script{install_as},
			);
			_progress(
				options,
				"installing script " _ script{install_as} _ " to " _
					destination.to_String(),
			);
			let written := _copy_file_atomic(
				source,
				destination,
				root{windows} ? null : 493,
			);

			let wrappers := [];
			if ( root{windows} ) {
				let wrapper_name := _replace_script_suffix(
					script{install_as},
					".cmd",
				);
				let wrapper := _path_child( root{bin_dir}, wrapper_name );
				let script_base := _relative_basename(script{install_as});
				_progress(
					options,
					"installing command wrapper " _ wrapper_name _
						" to " _ wrapper.to_String(),
				);
				_spew_utf8_atomic(
					wrapper,
					"@echo off\r\n" _
					"zuzu \"%~dp0" _ script_base _ "\" %*\r\n",
				);
				wrappers.push(wrapper_name);
			}

			script_records.push(
				{
					source: script{source},
					install_as: script{install_as},
					sha256: written{sha256},
					size: written{size},
					wrappers: wrappers,
				},
			);
		}

		let metadata := _copy_source_metadata(install_action{metadata});
		metadata{installed} := {
			zdf: "ZDF-1",
			lib_dir: root{lib_dir},
			bin_dir: root{bin_dir},
			meta_dir: root{meta_dir},
			installed_at: installed_at,
			source: _copy_source_record(install_action{source}),
			modules: module_records,
			scripts: script_records,
		};

		let metadata_file := _path_child(
			root{meta_dir},
			metadata{name} _ "-" _ metadata{version} _ ".json",
		);
		_progress(
			options,
			"writing metadata for " _ metadata{name} _ " " _
				metadata{version} _ " to " _ metadata_file.to_String(),
		);
		_atomic_json_write( metadata_file, metadata );

		return {
			name: metadata{name},
			version: metadata{version},
			metadata_file: metadata_file.to_String(),
			modules: module_records,
			scripts: script_records,
			metadata: metadata,
		};
	}

	method format_install_plan ( plan ) {
		let lines := [
			"Install target:",
			"  lib: " _ plan{target_root}{lib_dir},
			"  bin: " _ plan{target_root}{bin_dir},
			"  meta: " _ plan{target_root}{meta_dir},
			"",
			"Removals:",
		];

		let removal_lines := [];
		for ( let removal in plan{removals} ) {
			removal_lines.push(
				"  - " _ removal{name} _ " " _ removal{version} _
				" [" _ join(
					", ",
					removal{reasons}.sort( fn ( a, b ) -> a cmp b ),
				) _ "]"
			);
		}
		removal_lines := removal_lines.sort( fn ( a, b ) -> a cmp b );
		if ( removal_lines.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let line in removal_lines ) {
				lines.push(line);
			}
		}

			lines.push("");
			lines.push("Installs:");
			let install_lines := [];
			for ( let install_action in plan{installs} ) {
				install_lines.push(
					"  - " _ install_action{metadata}{name} _ " " _
					install_action{metadata}{version}
				);
				for ( let module in install_action{modules} ) {
					install_lines.push(
						"    module " _ module{install_as} _ " -> " _
					_path_join(
						plan{target_root}{lib_dir},
						module{install_as},
						plan{target_root}{windows},
					)
					);
				}
				for ( let script in install_action{scripts} ) {
					install_lines.push(
						"    script " _ script{install_as} _ " -> " _
					_path_join(
						plan{target_root}{bin_dir},
						script{install_as},
						plan{target_root}{windows},
					)
				);
			}
		}
		if ( install_lines.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let line in install_lines ) {
				lines.push(line);
			}
		}

		lines.push("");
		lines.push("Conflicts:");
		let conflict_lines := [];
		for ( let conflict in plan{ownership_conflicts} ) {
			conflict_lines.push(
				"  - " _ conflict{kind} _ " " _
				conflict{install_as} _ " owned by " _
				conflict{owner_distribution} _ " " _
				conflict{owner_version} _ "; replacing with " _
				conflict{planned_distribution} _ " " _
				conflict{planned_version} _ "; destination " _
				conflict{destination} _ "; owner metadata " _
				conflict{owner_metadata_file}
			);
		}
		conflict_lines := conflict_lines.sort( fn ( a, b ) -> a cmp b );
		if ( conflict_lines.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let line in conflict_lines ) {
				lines.push(line);
			}
		}

		return join( "\n", lines ) _ "\n";
	}

	method format_remove_plan ( plan ) {
		let lines := [
			"Remove target:",
			"  lib: " _ plan{target_root}{lib_dir},
			"  bin: " _ plan{target_root}{bin_dir},
			"  meta: " _ plan{target_root}{meta_dir},
			"",
			"Removals:",
		];

		if ( plan{removals}.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let removal in plan{removals} ) {
				lines.push(
					"  - " _ removal{name} _ " " _
					removal{version}
				);
			}
		}

		lines.push("");
		lines.push("Files:");
		if ( plan{files}.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let file in plan{files} ) {
				let status := file{blocked}
					? "blocked"
					: ( file{exists} ? "exists" : "missing" );
				lines.push(
					"  - " _ file{kind} _ " " _
					file{path} _ " [" _ status _ "]"
				);
			}
		}

		lines.push("");
		lines.push("Shared file conflicts:");
		if ( plan{shared_file_conflicts}.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let conflict in plan{shared_file_conflicts} ) {
				let kept := conflict{kept_owners}.map(
					fn o -> o{name} _ " " _ o{version},
				).sort( fn ( a, b ) -> a cmp b );
				lines.push(
					"  - " _ conflict{path} _
					" kept by " _ join( ", ", kept )
				);
			}
		}

		lines.push("");
		lines.push("Errors:");
		if ( plan{errors}.length() == 0 ) {
			lines.push("  none");
		}
		else {
			for ( let error in plan{errors} ) {
				lines.push(
					"  - " _ error{code} _ ": " _
					error{message}
				);
			}
		}

		return join( "\n", lines ) _ "\n";
	}

	method _install_unlocked ( targets, options? ) {
		_progress(
			options,
			"planning install for " _ join( ", ", _target_list(targets) ),
		);
		let plan := self.plan_install( targets, options );
		let plan_text := self.format_install_plan(plan);
		STDOUT.print(plan_text) if _opt( options, "print_plan", false );

		if ( _opt( options, "dry_run", false ) ) {
			_cleanup_plan_work_dirs(plan, options);
			return {
				ok: true,
				dry_run: true,
				plan: plan,
				plan_text: plan_text,
				tests: [],
				removals: [],
				installs: [],
				warnings: [],
			};
		}

		let test_results := [];
		let tests_ok := true;
		if ( not _opt( options, "no_test", false ) ) {
			let test_include_dirs := [];
			let seen_test_include_dirs := {};
			for ( let install_action in plan{installs} ) {
				let modules_dir := _path_child(
					install_action{root},
					"modules",
				);
				_push_unique_string(
					test_include_dirs,
					seen_test_include_dirs,
					modules_dir.to_String(),
				) if modules_dir.exists() and modules_dir.is_dir();
			}
			for ( let include_dir in _runtime_include_dirs() ) {
				_push_unique_string(
					test_include_dirs,
					seen_test_include_dirs,
					include_dir,
				);
			}
			for ( let root in self.dependency_roots(options) ) {
				_push_unique_string(
					test_include_dirs,
					seen_test_include_dirs,
					root{lib_dir},
				) if root{lib_dir} ne "";
			}
			let test_options := _copy_options_with(
				options,
				"test_include_dirs",
				test_include_dirs,
			);
			for ( let install_action in plan{installs} ) {
				let test_result := self.run_distribution_tests(
					install_action,
					test_options,
				);
				test_results.push(test_result);
				tests_ok := false if not test_result{ok};
			}
		}

		if ( not tests_ok and not _opt( options, "force", false ) ) {
			_cleanup_plan_work_dirs(plan, options);
			return {
				ok: false,
				error: "distribution tests failed",
				dry_run: false,
				plan: plan,
				plan_text: plan_text,
				tests: test_results,
				removals: [],
				installs: [],
				warnings: [],
			};
		}

		try {
			let removals := [];
			let warnings := [];
			for ( let removal in plan{removals} ) {
				let result := self.execute_removal( removal, options );
				removals.push(result);
				for ( let warning in result{warnings} ) {
					warnings.push(warning);
				}
			}

			let installs := [];
			let installed_at := _installed_at();
			for ( let install_action in plan{installs} ) {
				installs.push( self._install_action(
					install_action,
					installed_at,
					options,
				) );
			}

			_cleanup_plan_work_dirs(plan, options);
			return {
				ok: true,
				dry_run: false,
				forced: not tests_ok and _opt( options, "force", false ),
				plan: plan,
				plan_text: plan_text,
				tests: test_results,
				removals: removals,
				installs: installs,
				warnings: warnings,
			};
		}
		catch ( Exception e ) {
			_cleanup_plan_work_dirs(plan, options);
			throw e;
		}
	}

	method install ( targets, options? ) {
		let lock := self.acquire_lock( "install", options );
		try {
			let result := self._install_unlocked( targets, options );
			lock.release();
			return result;
		}
		catch ( Exception e ) {
			lock.release();
			throw e;
		}
	}

	method _remove_unlocked ( targets, options? ) {
		let plan := self.plan_remove( targets, options );
		let plan_text := self.format_remove_plan(plan);
		STDOUT.print(plan_text) if _opt( options, "print_plan", false );

		if ( not plan{ok} ) {
			return {
				ok: false,
				dry_run: false,
				plan: plan,
				plan_text: plan_text,
				removed: [],
				warnings: [],
				errors: plan{errors},
			};
		}

		if ( _opt( options, "dry_run", false ) ) {
			return {
				ok: true,
				dry_run: true,
				plan: plan,
				plan_text: plan_text,
				removed: [],
				warnings: [],
				errors: [],
			};
		}

		let removed := [];
		let warnings := [];
		for ( let file in plan{files} ) {
			let path := new Path(file{path});
			if ( path.exists() ) {
				path.remove();
				removed.push(
					{
						kind: file{kind},
						path: file{path},
					},
				);
			}
			else {
				warnings.push(
					{
						kind: file{kind},
						path: file{path},
						message: "missing file",
					},
				);
			}
		}

		return {
			ok: true,
			dry_run: false,
			plan: plan,
			plan_text: plan_text,
			removed: removed,
			warnings: warnings,
			errors: [],
		};
	}

	method remove ( targets, options? ) {
		let lock := self.acquire_lock( "remove", options );
		try {
			let result := self._remove_unlocked( targets, options );
			lock.release();
			return result;
		}
		catch ( Exception e ) {
			lock.release();
			throw e;
		}
	}
}

function _zoo ( options? ) {
	return new Zuzuzoo(
		lib_dir: _opt( options, "lib_dir", null ),
		bin_dir: _opt( options, "bin_dir", null ),
		meta_dir: _opt( options, "meta_dir", null ),
		global: _opt( options, "global", false ),
		windows: _opt( options, "windows", null ),
		home: _opt( options, "home", null ),
		userprofile: _opt( options, "userprofile", null ),
		base_url: _opt( options, "base_url", "https://zuzulang.org" ),
		user_agent: _opt( options, "user_agent", null ),
		zuzu_command: _opt( options, "zuzu_command", "zuzu" ),
		dependency_roots: _opt( options, "dependency_roots", [] ),
		global_root: _opt( options, "global_root", null ),
	);
}

function list_installed ( options? ) {
	return _zoo(options).list_installed(options);
}

function query ( module_name, options? ) {
	return _zoo(options).query( module_name, options );
}

function query_distribution ( distribution_name, options? ) {
	return _zoo(options).query_distribution( distribution_name, options );
}

function is_installed ( module_name, min_version?, options? ) {
	return _zoo(options).is_installed( module_name, min_version );
}

function installed_version ( module_name, options? ) {
	return _zoo(options).installed_version(module_name);
}

function pretty_json ( value, options? ) {
	return _zoo(options).pretty_json(value);
}

function format_json ( value, options? ) {
	return _zoo(options).format_json( value, options );
}

function fetch_source ( target, options? ) {
	return _zoo(options).fetch_source( target, options );
}

function load_distribution ( target, options? ) {
	return _zoo(options).load_distribution( target, options );
}

function dependency_roots ( options? ) {
	return _zoo(options).dependency_roots(options);
}

function find_dependency ( module_name, min_version?, options? ) {
	return _zoo(options).find_dependency(
		module_name,
		min_version,
		options,
	);
}

function plan_install ( targets, options? ) {
	return _zoo(options).plan_install( targets, options );
}

function plan_remove ( targets, options? ) {
	return _zoo(options).plan_remove( targets, options );
}

function verify ( targets, options? ) {
	return _zoo(options).verify( targets, options );
}

function latest ( module_name, options? ) {
	return _zoo(options).latest( module_name, options );
}

function can_upgrade ( module_name, options? ) {
	return _zoo(options).can_upgrade( module_name, options );
}

function install ( targets, options? ) {
	return _zoo(options).install( targets, options );
}

function remove ( targets, options? ) {
	return _zoo(options).remove( targets, options );
}

function run_distribution_tests ( install_action, options? ) {
	return _zoo(options).run_distribution_tests( install_action, options );
}

function execute_removal ( removal_action, options? ) {
	return _zoo(options).execute_removal( removal_action, options );
}

function format_install_plan ( plan, options? ) {
	return _zoo(options).format_install_plan(plan);
}

function format_remove_plan ( plan, options? ) {
	return _zoo(options).format_remove_plan(plan);
}