dprint 0.59.0

Binary for dprint code formatter—a pluggable and configurable code formatting platform.
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
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use deno_tower_lsp::CancellationToken;
use deno_tower_lsp::LanguageServer;
use deno_tower_lsp::LspService;
use deno_tower_lsp::Server;
use deno_tower_lsp::jsonrpc::Result as LspResult;
use deno_tower_lsp::lsp_types::CompletionList;
use deno_tower_lsp::lsp_types::CompletionParams;
use deno_tower_lsp::lsp_types::CompletionResponse;
use deno_tower_lsp::lsp_types::DidChangeNotebookDocumentParams;
use deno_tower_lsp::lsp_types::DidChangeTextDocumentParams;
use deno_tower_lsp::lsp_types::DidChangeWorkspaceFoldersParams;
use deno_tower_lsp::lsp_types::DidCloseNotebookDocumentParams;
use deno_tower_lsp::lsp_types::DidCloseTextDocumentParams;
use deno_tower_lsp::lsp_types::DidOpenNotebookDocumentParams;
use deno_tower_lsp::lsp_types::DidOpenTextDocumentParams;
use deno_tower_lsp::lsp_types::DocumentFormattingParams;
use deno_tower_lsp::lsp_types::DocumentRangeFormattingParams;
use deno_tower_lsp::lsp_types::FormattingOptions;
use deno_tower_lsp::lsp_types::FormattingProperty;
use deno_tower_lsp::lsp_types::Hover;
use deno_tower_lsp::lsp_types::HoverParams;
use deno_tower_lsp::lsp_types::InitializeParams;
use deno_tower_lsp::lsp_types::InitializeResult;
use deno_tower_lsp::lsp_types::InitializedParams;
use deno_tower_lsp::lsp_types::OneOf;
use deno_tower_lsp::lsp_types::Position;
use deno_tower_lsp::lsp_types::Registration;
use deno_tower_lsp::lsp_types::ServerCapabilities;
use deno_tower_lsp::lsp_types::ServerInfo;
use deno_tower_lsp::lsp_types::TextDocumentSyncCapability;
use deno_tower_lsp::lsp_types::TextDocumentSyncKind;
use deno_tower_lsp::lsp_types::TextDocumentSyncOptions;
use deno_tower_lsp::lsp_types::TextEdit;
use deno_tower_lsp::lsp_types::Uri;
use deno_tower_lsp::lsp_types::WorkspaceFolder;
use deno_tower_lsp::lsp_types::WorkspaceFoldersServerCapabilities;
use deno_tower_lsp::lsp_types::WorkspaceServerCapabilities;
use dprint_core::async_runtime::JoinHandle;
use dprint_core::plugins::FormatError;
use dprint_core::plugins::FormatRange;
use dprint_core::plugins::HostFormatRequest;
use dprint_core::plugins::process::start_parent_process_checker_task;
use parking_lot::Mutex;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::try_join;
use url::Url;

use crate::arg_parser::CliArgs;
use crate::environment::Environment;
use crate::format::EnsureStableFormat;
use crate::plugins::PluginResolver;
use crate::resolution::PluginConfigDiagnosticsError;

use self::client::ClientWrapper;
use self::config::LspPluginsScopeContainer;
use self::config_completion::ConfigCompletions;
use self::config_completion::get_config_file_capabilities;
use self::config_completion::is_config_uri;
use self::documents::Documents;
use self::notebook::get_notebook_cell_file_path;
use self::notebook::get_notebook_cell_format_registrations;
use self::notebook::get_notebook_document_sync_options;
use self::notebook::trim_formatted_cell_text;
use self::text::LineIndex;
use self::text::get_edits;
use self::text::normalize_to_source_line_endings;
use self::untitled::get_untitled_file_path;
use self::untitled::get_untitled_registrations;
use self::untitled::is_untitled_uri;

mod client;
mod config;
mod config_completion;
mod documents;
mod language;
mod notebook;
mod text;
mod untitled;

/// The formatting option a client provides in a format request to format a
/// document without a config file in an ancestor directory using the global
/// config file when the server doesn't use the global config file by default
/// (ex. for a command that explicitly formats using the global config file).
const USE_GLOBAL_CONFIG_OPTION: &str = "useGlobalConfig";

// deno_tower_lsp will drop the future on cancellation,
// so use this to cancel the containing token on drop.
struct DropToken {
  completed: bool,
  token: Arc<CancellationToken>,
}

impl DropToken {
  pub fn new(token: Arc<CancellationToken>) -> Self {
    Self { token, completed: false }
  }

  pub fn completed(&mut self) {
    self.completed = true;
  }
}

impl Drop for DropToken {
  fn drop(&mut self) {
    if !self.completed {
      self.token.cancel();
    }
  }
}

struct PendingTokenGuard {
  id: u16,
  tokens: Rc<RefCell<HashMap<u16, Arc<CancellationToken>>>>,
}

impl Drop for PendingTokenGuard {
  fn drop(&mut self) {
    self.tokens.borrow_mut().remove(&self.id);
  }
}

#[derive(Default)]
struct PendingTokens {
  next_id: u16,
  tokens: Rc<RefCell<HashMap<u16, Arc<CancellationToken>>>>,
}

impl PendingTokens {
  pub fn insert(&mut self, token: Arc<CancellationToken>) -> PendingTokenGuard {
    let id = self.next_id();
    self.tokens.borrow_mut().insert(id, token);
    PendingTokenGuard {
      id,
      tokens: self.tokens.clone(),
    }
  }

  pub fn cancel_all(&mut self) {
    let mut pending_tokens = self.tokens.borrow_mut();
    for token in pending_tokens.values() {
      token.cancel();
    }
    pending_tokens.clear();
    self.next_id = 0;
  }

  pub fn next_id(&mut self) -> u16 {
    if self.next_id == u16::MAX {
      self.next_id = 0;
    }
    let id = self.next_id;
    self.next_id += 1;
    id
  }
}

struct EditorFormatRequest {
  /// The file path to format the document's text as, which differs from the
  /// document's for documents that aren't on the file system (ex. notebook cells).
  pub file_path: PathBuf,
  /// The notebook file's path when the document is a notebook cell.
  pub notebook_path: Option<PathBuf>,
  pub file_text: String,
  pub maybe_line_index: Option<LineIndex>,
  pub range: FormatRange,
  /// Whether the client asked to use the global config file.
  pub use_global_config: bool,
  pub token: Arc<CancellationToken>,
}

struct ConfigEditorRequest {
  pub file_path: PathBuf,
  pub file_text: String,
  pub position: Position,
}

enum ChannelMessage {
  Format(EditorFormatRequest, oneshot::Sender<Result<Option<Vec<TextEdit>>>>),
  Completion(ConfigEditorRequest, oneshot::Sender<Option<CompletionList>>),
  Hover(ConfigEditorRequest, oneshot::Sender<Option<Hover>>),
  Shutdown(oneshot::Sender<()>),
  /// This message is used for testing.
  #[cfg(test)]
  HasPending(oneshot::Sender<bool>),
}

async fn handle_format_request<TEnvironment: Environment>(
  mut request: EditorFormatRequest,
  scope_container: Rc<LspPluginsScopeContainer<TEnvironment>>,
  ensure_stable_format: EnsureStableFormat,
  environment: &TEnvironment,
) -> Result<Option<Vec<TextEdit>>> {
  let Some(parent_dir) = request.file_path.parent() else {
    // the backend doesn't send this, so it's an error that also goes to the client
    bail!("Cannot format non-file path: {}", request.file_path.display());
  };
  if request.token.is_cancelled() {
    return Ok(None);
  }
  let Some(scope) = scope_container.resolve_by_path(parent_dir, request.use_global_config).await? else {
    log_stderr_info!(environment, "Path did not have a dprint config file: {}", request.file_path.display());
    return Ok(None);
  };
  if request.token.is_cancelled() {
    return Ok(None);
  }
  // canonicalize the paths
  request.file_path = canonicalize_path(environment, request.file_path);
  request.notebook_path = request.notebook_path.map(|path| canonicalize_path(environment, path));

  let can_format = match &request.notebook_path {
    // the cli formats a notebook's cells when a plugin (the jupyter plugin) formats
    // the notebook, so only format a cell when the notebook would be formatted
    Some(notebook_path) => {
      !scope.plugin_name_maps.get_plugin_names_from_file_path(notebook_path).into_names().is_empty() && scope.can_format_for_editor(notebook_path, None)
    }
    None => scope.can_format_for_editor(&request.file_path, Some(request.file_text.as_bytes())),
  };
  if !can_format {
    log_debug!(
      environment,
      "Excluded file: {}",
      request.notebook_path.as_ref().unwrap_or(&request.file_path).display()
    );
    return Ok(None);
  }

  // the range is given to the plugin, but is needed after for a notebook cell
  let maybe_cell_range = request.notebook_path.as_ref().map(|_| request.range.clone());
  let Some(result) = scope
    .format_stable(
      HostFormatRequest {
        file_path: request.file_path,
        file_bytes: request.file_text.as_bytes().to_vec(),
        range: request.range,
        override_config: Default::default(),
        token: request.token,
      },
      ensure_stable_format,
    )
    .await?
  else {
    return Ok(None);
  };
  dprint_core::async_runtime::spawn_blocking(move || {
    let new_text = String::from_utf8(result).context("Failed converting formatted text to utf-8.")?;
    // the editor owns the document's line endings, so match them rather than
    // imposing the plugin's configured newline kind (see #965)
    let new_text = normalize_to_source_line_endings(&request.file_text, new_text);
    let new_text = match maybe_cell_range {
      Some(range) => {
        let new_text = trim_formatted_cell_text(&request.file_text, new_text, &range);
        if new_text == request.file_text {
          return Ok(None);
        }
        new_text
      }
      None => new_text,
    };
    let line_index = request.maybe_line_index.unwrap_or_else(|| LineIndex::new(&request.file_text));
    Ok(Some(get_edits(&request.file_text, &new_text, &line_index)))
  })
  .await?
}

pub async fn run_language_server<TEnvironment: Environment>(
  args: &CliArgs,
  environment: &TEnvironment,
  plugin_resolver: &Rc<PluginResolver<TEnvironment>>,
) -> anyhow::Result<()> {
  let stdin = tokio::io::stdin();
  let stdout = tokio::io::stdout();
  let (tx, rx) = mpsc::unbounded_channel();

  let config_path = args.config.as_ref().map(|config| environment.cwd().join(config));
  let recv_task = start_message_handler(environment, plugin_resolver, config_path, rx);

  let environment = environment.clone();
  let lsp_task = dprint_core::async_runtime::spawn(async move {
    let (service, socket, pending) = LspService::new(|client| {
      let client = ClientWrapper::new(Arc::new(client));
      Backend::new(client.clone(), environment.clone(), tx)
    });
    Server::new(stdin, stdout, socket, pending).serve(service).await;
  });

  let (shutdown_received, _) = try_join!(recv_task, lsp_task)?;

  // the plugins are only shut down on a shutdown request, so ensure that's
  // done before exiting when the client exited or disconnected without one
  plugin_resolver.clear_and_shutdown_initialized().await;

  // Exit the process instead of returning. The framework reads stdin on a
  // blocking task that stays parked in a read while the client keeps the pipe
  // open and dropping the tokio runtime waits for that task, so returning would
  // keep the process alive until the client closes stdin.
  std::process::exit(get_exit_code(shutdown_received))
}

/// Starts the task that handles the messages sent by the `Backend`, which
/// resolves to whether it stopped because of a shutdown request rather than
/// because the `Backend` was dropped.
fn start_message_handler<TEnvironment: Environment>(
  environment: &TEnvironment,
  plugin_resolver: &Rc<PluginResolver<TEnvironment>>,
  config_override: Option<PathBuf>,
  mut rx: mpsc::UnboundedReceiver<ChannelMessage>,
) -> JoinHandle<bool> {
  // tower_lsp required Backend to implement Send and Sync, but
  // we use a single threaded runtime. So spawn some tasks and
  // communicate over a channel.
  // todo: deno_tower_lsp doesn't require this, so the channel could be removed
  let max_cores = environment.max_threads();
  let concurrency_limiter = Rc::new(Semaphore::new(std::cmp::max(1, max_cores - 1)));
  let ensure_stable_format = EnsureStableFormat::for_editor(environment);
  let environment = environment.clone();
  let scope_container = Rc::new(LspPluginsScopeContainer::new(environment.clone(), plugin_resolver.clone(), config_override));
  let config_completions = Rc::new(ConfigCompletions::new(environment.clone(), scope_container.clone()));
  dprint_core::async_runtime::spawn(async move {
    let mut pending_tokens = PendingTokens::default();
    while let Some(message) = rx.recv().await {
      match message {
        ChannelMessage::Format(request, sender) => {
          let token_guard = pending_tokens.insert(request.token.clone());
          let concurrency_limiter = concurrency_limiter.clone();
          let scope_container = scope_container.clone();
          let environment = environment.clone();
          dprint_core::async_runtime::spawn(async move {
            let _permit = concurrency_limiter.acquire().await;
            let result = handle_format_request(request, scope_container, ensure_stable_format, &environment).await;
            let _ = sender.send(result);
            drop(token_guard); // remove the token from the pending tokens
          });
        }
        ChannelMessage::Completion(request, sender) => {
          let config_completions = config_completions.clone();
          dprint_core::async_runtime::spawn(async move {
            let result = config_completions.completions(&request.file_path, &request.file_text, request.position).await;
            let _ = sender.send(result);
          });
        }
        ChannelMessage::Hover(request, sender) => {
          let config_completions = config_completions.clone();
          dprint_core::async_runtime::spawn(async move {
            let result = config_completions.hover(&request.file_path, &request.file_text, request.position).await;
            let _ = sender.send(result);
          });
        }
        ChannelMessage::Shutdown(sender) => {
          pending_tokens.cancel_all();
          scope_container.shutdown().await;
          let _ = sender.send(());
          return true; // exit
        }
        #[cfg(test)]
        ChannelMessage::HasPending(sender) => {
          let is_empty = pending_tokens.tokens.borrow().is_empty();
          let _ = sender.send(!is_empty);
        }
      }
    }
    false
  })
}

/// Gets the exit code the language server protocol specifies for the server,
/// which is 0 when a shutdown request was received and 1 otherwise.
fn get_exit_code(shutdown_received: bool) -> i32 {
  if shutdown_received { 0 } else { 1 }
}

struct State<TEnvironment: Environment> {
  documents: Documents<TEnvironment>,
  /// Registrations to send to the client once it says it's initialized.
  pending_registrations: Vec<Registration>,
  /// The paths of the client's workspace folders on the file system.
  workspace_folders: Vec<PathBuf>,
}

struct Backend<TEnvironment: Environment> {
  client: ClientWrapper,
  environment: TEnvironment,
  sender: mpsc::UnboundedSender<ChannelMessage>,
  state: Mutex<State<TEnvironment>>,
}

impl<TEnvironment: Environment> Backend<TEnvironment> {
  pub fn new(client: ClientWrapper, environment: TEnvironment, sender: mpsc::UnboundedSender<ChannelMessage>) -> Self {
    Backend {
      client,
      environment: environment.clone(),
      sender,
      state: Mutex::new(State {
        documents: Documents::new(environment),
        pending_registrations: Vec::new(),
        workspace_folders: Vec::new(),
      }),
    }
  }

  async fn send_format_request(&self, uri: &Uri, request: EditorFormatRequest) -> LspResult<Option<Vec<TextEdit>>> {
    let start_time = std::time::Instant::now();
    log_debug!(self.environment, "Received format request for {}", uri.as_str());
    let mut drop_token = DropToken::new(request.token.clone());
    let result = self.send_format_request_inner(request).await;
    drop_token.completed();
    let result = match result {
      Ok(value) => Ok(value),
      Err(err) => {
        // Not a response error or a shown message because failing to format is
        // what happens for a file with a syntax error, which would notify the
        // user on every format on save.
        let mut message = format!("Failed formatting '{}': {:#}", uri.as_str(), err);
        log_error!(self.environment, "{}", message);
        // the text of a plugin's config diagnostics is only logged to stderr
        // the first time the plugin is used, so tell the client each time
        for diagnostic in get_plugin_config_diagnostics(&err) {
          message.push('\n');
          message.push_str(diagnostic);
        }
        self.client.log_error(message);
        Ok(None)
      }
    };
    log_debug!(
      self.environment,
      "Finished format request for {} in {}ms",
      uri.as_str(),
      start_time.elapsed().as_millis()
    );
    result
  }

  /// Resolves the file path to format the document as along with the path of
  /// its notebook when the document is a notebook cell, which fails with the
  /// message to log when the document can't be formatted.
  fn resolve_format_paths(&self, uri: &Uri) -> Result<(PathBuf, Option<PathBuf>)> {
    if is_untitled_uri(uri) {
      return Ok((self.resolve_untitled_file_path(uri)?, None));
    }
    let Some((notebook_uri, language_id)) = self.state.lock().documents.get_notebook_cell(uri) else {
      let Some(file_path) = uri_to_file_path(uri) else {
        bail!(
          "Cannot format document that is not a file, an untitled document or a cell of an open notebook: {}",
          uri.as_str()
        );
      };
      // the document is formatted with the config file for its directory
      if file_path.parent().is_none() {
        bail!("Cannot format non-file path: {}", file_path.display());
      }
      return Ok((file_path, None));
    };
    // the cli only formats notebooks on the file system
    let Some(notebook_path) = uri_to_file_path(&notebook_uri) else {
      bail!("Cannot format cell of a notebook that is not on the file system: {}", uri.as_str());
    };
    let Some(file_path) = get_notebook_cell_file_path(&notebook_path, &language_id) else {
      bail!("Could not determine a file path to format the notebook cell with language: {}", language_id);
    };
    Ok((file_path, Some(notebook_path)))
  }

  /// An untitled document is formatted as a file in the first workspace
  /// folder or otherwise the home directory.
  fn resolve_untitled_file_path(&self, uri: &Uri) -> Result<PathBuf> {
    let (language_id, workspace_folder) = {
      let state = self.state.lock();
      let Some(language_id) = state.documents.get_language_id(uri) else {
        bail!("Missing document: {}", uri.as_str());
      };
      (language_id, state.workspace_folders.first().cloned())
    };
    let Some(dir_path) = workspace_folder.or_else(|| self.environment.get_home_dir().map(|dir| dir.into_path_buf())) else {
      bail!("Cannot format untitled document without a workspace folder or home directory: {}", uri.as_str());
    };
    let Some(file_path) = get_untitled_file_path(&dir_path, &language_id) else {
      bail!("Could not determine a file path to format the untitled document with language: {}", language_id);
    };
    Ok(file_path)
  }

  /// Gets the value or otherwise logs to stderr and the client why the format
  /// request does nothing, which the client can't tell from the response.
  fn ok_or_log_format_warning<T>(&self, result: Result<T>) -> Option<T> {
    match result {
      Ok(value) => Some(value),
      Err(err) => {
        let message = format!("{:#}", err);
        log_warn!(self.environment, "{}", message);
        self.client.log_warn(message);
        None
      }
    }
  }

  /// Gets the text of a config file document for the completion and hover requests.
  fn get_config_content(&self, uri: &Uri) -> Option<(String, Option<LineIndex>)> {
    match self.state.lock().documents.get_content(uri) {
      Ok(content) => Some(content),
      Err(err) => {
        log_warn!(self.environment, "{:#}", err);
        None
      }
    }
  }

  async fn send_format_request_inner(&self, request: EditorFormatRequest) -> Result<Option<Vec<TextEdit>>> {
    let (sender, receiver) = oneshot::channel();
    self.sender.send(ChannelMessage::Format(request, sender))?;
    receiver.await?
  }

  /// This is used in the test code to ensure there are no pending requests.
  #[cfg(test)]
  pub async fn has_pending(&self) -> bool {
    let (sender, receiver) = oneshot::channel();
    if self.sender.send(ChannelMessage::HasPending(sender)).is_ok() {
      receiver.await.unwrap_or(false)
    } else {
      false
    }
  }
}

#[deno_tower_lsp::async_trait(?Send)]
impl<TEnvironment: Environment> LanguageServer for Backend<TEnvironment> {
  async fn initialize(&self, params: InitializeParams) -> LspResult<InitializeResult> {
    if let Some(parent_id) = params.process_id {
      start_parent_process_checker_task(parent_id);
    }
    let config_file_capabilities = get_config_file_capabilities(&params.capabilities);
    {
      let mut state = self.state.lock();
      state.pending_registrations = get_notebook_cell_format_registrations(&params.capabilities);
      state.pending_registrations.extend(get_untitled_registrations(&params.capabilities));
      state.pending_registrations.extend(config_file_capabilities.registrations);
      state.workspace_folders = get_workspace_folder_paths(params.workspace_folders.as_deref().unwrap_or_default());
    }

    Ok(InitializeResult {
      server_info: Some(ServerInfo {
        name: "dprint".to_string(),
        version: Some(self.environment.cli_version()),
      }),
      capabilities: ServerCapabilities {
        text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
          // todo: incremental should work now, but let's try out full to start
          change: Some(TextDocumentSyncKind::FULL),
          open_close: Some(true),
          save: None,
          will_save: None,
          will_save_wait_until: None,
        })),
        notebook_document_sync: Some(OneOf::Left(get_notebook_document_sync_options())),
        document_formatting_provider: Some(OneOf::Left(true)),
        document_range_formatting_provider: Some(OneOf::Left(true)),
        completion_provider: config_file_capabilities.completion_provider,
        hover_provider: config_file_capabilities.hover_provider,
        workspace: Some(WorkspaceServerCapabilities {
          workspace_folders: Some(WorkspaceFoldersServerCapabilities {
            supported: Some(true),
            change_notifications: Some(OneOf::Left(true)),
          }),
          file_operations: None,
        }),
        ..ServerCapabilities::default()
      },
    })
  }

  async fn initialized(&self, _: InitializedParams) {
    self.client.log_info(format!(
      "dprint {} ({}-{})",
      self.environment.cli_version(),
      self.environment.os(),
      self.environment.cpu_arch()
    ));
    self.client.log_info("Server ready.".to_string());
    let registrations = std::mem::take(&mut self.state.lock().pending_registrations);
    if !registrations.is_empty() {
      self.client.register_capabilities(registrations);
    }
  }

  async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
    let removed = get_workspace_folder_paths(&params.event.removed);
    let added = get_workspace_folder_paths(&params.event.added);
    let mut state = self.state.lock();
    state.workspace_folders.retain(|folder| !removed.contains(folder));
    state.workspace_folders.extend(added);
  }

  async fn did_open(&self, params: DidOpenTextDocumentParams) {
    self.state.lock().documents.open(params.text_document);
  }

  async fn did_change(&self, params: DidChangeTextDocumentParams) {
    self.state.lock().documents.changed(params);
  }

  async fn did_close(&self, params: DidCloseTextDocumentParams) {
    self.state.lock().documents.closed(&params.text_document.uri);
  }

  async fn notebook_did_open(&self, params: DidOpenNotebookDocumentParams) {
    let mut state = self.state.lock();
    for cell_document in params.cell_text_documents {
      state.documents.open_notebook_cell(&params.notebook_document.uri, cell_document);
    }
  }

  async fn notebook_did_change(&self, params: DidChangeNotebookDocumentParams) {
    let Some(cells) = params.change.cells else {
      return;
    };
    let mut state = self.state.lock();
    if let Some(structure) = cells.structure {
      for cell_document in structure.did_close.unwrap_or_default() {
        state.documents.closed(&cell_document.uri);
      }
      for cell_document in structure.did_open.unwrap_or_default() {
        state.documents.open_notebook_cell(&params.notebook_document.uri, cell_document);
      }
    }
    for change in cells.text_content.unwrap_or_default() {
      state.documents.changed(DidChangeTextDocumentParams {
        text_document: change.document,
        content_changes: change.changes,
      });
    }
  }

  async fn notebook_did_close(&self, params: DidCloseNotebookDocumentParams) {
    self.state.lock().documents.closed_notebook(&params.notebook_document.uri);
  }

  async fn formatting(&self, params: DocumentFormattingParams, token: CancellationToken) -> LspResult<Option<Vec<TextEdit>>> {
    let Some((file_path, notebook_path)) = self.ok_or_log_format_warning(self.resolve_format_paths(&params.text_document.uri)) else {
      return Ok(None);
    };
    let content = self.state.lock().documents.get_content(&params.text_document.uri);
    let Some((file_text, maybe_line_index)) = self.ok_or_log_format_warning(content) else {
      return Ok(None);
    };
    self
      .send_format_request(
        &params.text_document.uri,
        EditorFormatRequest {
          file_path,
          notebook_path,
          file_text,
          range: None,
          use_global_config: has_use_global_config_option(&params.options),
          maybe_line_index,
          token: Arc::new(token),
        },
      )
      .await
  }

  async fn range_formatting(&self, params: DocumentRangeFormattingParams, token: CancellationToken) -> LspResult<Option<Vec<TextEdit>>> {
    let Some((file_path, notebook_path)) = self.ok_or_log_format_warning(self.resolve_format_paths(&params.text_document.uri)) else {
      return Ok(None);
    };
    let content = self.state.lock().documents.get_content_with_range(&params.text_document.uri, params.range);
    let Some((file_text, range, line_index)) = self.ok_or_log_format_warning(content) else {
      return Ok(None);
    };
    self
      .send_format_request(
        &params.text_document.uri,
        EditorFormatRequest {
          file_path,
          notebook_path,
          file_text,
          range,
          use_global_config: has_use_global_config_option(&params.options),
          maybe_line_index: Some(line_index),
          token: Arc::new(token),
        },
      )
      .await
  }

  async fn completion(&self, params: CompletionParams, _token: CancellationToken) -> LspResult<Option<CompletionResponse>> {
    let uri = params.text_document_position.text_document.uri;
    if !is_config_uri(&uri) {
      return Ok(None);
    }
    let Some(file_path) = uri_to_file_path(&uri) else {
      return Ok(None);
    };
    let Some((file_text, _)) = self.get_config_content(&uri) else {
      return Ok(None);
    };
    let (sender, receiver) = oneshot::channel();
    let request = ConfigEditorRequest {
      file_path,
      file_text,
      position: params.text_document_position.position,
    };
    if self.sender.send(ChannelMessage::Completion(request, sender)).is_err() {
      return Ok(None);
    }
    Ok(receiver.await.ok().flatten().map(CompletionResponse::List))
  }

  async fn hover(&self, params: HoverParams, _token: CancellationToken) -> LspResult<Option<Hover>> {
    let uri = params.text_document_position_params.text_document.uri;
    if !is_config_uri(&uri) {
      return Ok(None);
    }
    let Some(file_path) = uri_to_file_path(&uri) else {
      return Ok(None);
    };
    let Some((file_text, _)) = self.get_config_content(&uri) else {
      return Ok(None);
    };
    let (sender, receiver) = oneshot::channel();
    let request = ConfigEditorRequest {
      file_path,
      file_text,
      position: params.text_document_position_params.position,
    };
    if self.sender.send(ChannelMessage::Hover(request, sender)).is_err() {
      return Ok(None);
    }
    Ok(receiver.await.ok().flatten())
  }

  async fn shutdown(&self) -> LspResult<()> {
    let (sender, receiver) = oneshot::channel();
    if self.sender.send(ChannelMessage::Shutdown(sender)).is_ok() {
      let _ = receiver.await;
    };
    Ok(())
  }
}

/// Attempts to convert a uri to a file path. By default, uses the Url
/// crate's `to_file_path()` method, but falls back to try and resolve unix-style
/// paths on Windows.
///
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Lifted from code I wrote here:
// https://github.com/denoland/deno/blob/8702894feb480181040152a06e7c3eaf38619629/cli/util/path.rs#L85
pub fn uri_to_file_path(uri: &Uri) -> Option<PathBuf> {
  let specifier = Url::parse(uri.as_str()).ok()?;
  if specifier.scheme() != "file" {
    return None;
  }

  match specifier.to_file_path() {
    Ok(path) => Some(path),
    Err(()) => {
      if cfg!(windows) {
        // This might be a unix-style path which is used in the tests even on Windows.
        // Attempt to see if we can convert it to a `PathBuf`. This code should be removed
        // once/if https://github.com/servo/rust-url/issues/730 is implemented.
        if specifier.scheme() == "file" && specifier.host().is_none() && specifier.port().is_none() && specifier.path_segments().is_some() {
          let path_str = specifier.path();
          String::from_utf8(percent_encoding::percent_decode(path_str.as_bytes()).collect())
            .ok()
            .map(PathBuf::from)
        } else {
          None
        }
      } else {
        None
      }
    }
  }
}

/// Gets the text of the plugin's configuration diagnostics when the format
/// request failed because of them.
fn get_plugin_config_diagnostics(err: &anyhow::Error) -> &[String] {
  err
    .downcast_ref::<FormatError>()
    .and_then(|err| err.downcast_ref::<PluginConfigDiagnosticsError>())
    .map(|err| err.diagnostics.as_slice())
    .unwrap_or_default()
}

fn has_use_global_config_option(options: &FormattingOptions) -> bool {
  matches!(options.properties.get(USE_GLOBAL_CONFIG_OPTION), Some(FormattingProperty::Bool(true)))
}

fn get_workspace_folder_paths(folders: &[WorkspaceFolder]) -> Vec<PathBuf> {
  folders.iter().filter_map(|folder| uri_to_file_path(&folder.uri)).collect()
}

fn canonicalize_path(environment: &impl Environment, path: PathBuf) -> PathBuf {
  environment.canonicalize_maybe_not_exists(&path).map(|p| p.into_path_buf()).unwrap_or(path)
}

#[cfg(test)]
mod test {
  use std::str::FromStr;
  use std::time::Duration;

  use deno_tower_lsp::lsp_types::ClientCapabilities;
  use deno_tower_lsp::lsp_types::DynamicRegistrationClientCapabilities;
  use deno_tower_lsp::lsp_types::MessageType;
  use deno_tower_lsp::lsp_types::NotebookCellArrayChange;
  use deno_tower_lsp::lsp_types::NotebookDocument;
  use deno_tower_lsp::lsp_types::NotebookDocumentCellChange;
  use deno_tower_lsp::lsp_types::NotebookDocumentCellChangeStructure;
  use deno_tower_lsp::lsp_types::NotebookDocumentChangeEvent;
  use deno_tower_lsp::lsp_types::NotebookDocumentChangeTextContent;
  use deno_tower_lsp::lsp_types::NotebookDocumentIdentifier;
  use deno_tower_lsp::lsp_types::Position;
  use deno_tower_lsp::lsp_types::Range;
  use deno_tower_lsp::lsp_types::Registration;
  use deno_tower_lsp::lsp_types::TextDocumentClientCapabilities;
  use deno_tower_lsp::lsp_types::TextDocumentContentChangeEvent;
  use deno_tower_lsp::lsp_types::TextDocumentIdentifier;
  use deno_tower_lsp::lsp_types::TextDocumentItem;
  use deno_tower_lsp::lsp_types::TextDocumentPositionParams;
  use deno_tower_lsp::lsp_types::VersionedNotebookDocumentIdentifier;
  use deno_tower_lsp::lsp_types::VersionedTextDocumentIdentifier;
  use deno_tower_lsp::lsp_types::WorkspaceFoldersChangeEvent;
  use dprint_core::async_runtime::future;

  use crate::environment::TestConfigFileBuilder;
  use crate::environment::TestEnvironment;
  use crate::environment::TestEnvironmentBuilder;
  use crate::plugins::PluginCache;

  use super::client::ClientTrait;
  use super::*;

  macro_rules! did_open {
    ($backend:expr, $uri:expr, $text:expr) => {
      $backend
        .did_open(DidOpenTextDocumentParams {
          text_document: TextDocumentItem {
            uri: $uri.clone(),
            language_id: "txt".to_string(),
            version: 0,
            text: $text.to_string(),
          },
        })
        .await;
    };
  }

  macro_rules! did_close {
    ($backend:expr, $uri:expr) => {
      $backend
        .did_close(DidCloseTextDocumentParams {
          text_document: TextDocumentIdentifier { uri: $uri.clone() },
        })
        .await;
    };
  }

  macro_rules! assert_format {
    ($backend:expr, $uri:expr, $expected:expr) => {
      let result = $backend
        .formatting(
          DocumentFormattingParams {
            text_document: TextDocumentIdentifier { uri: $uri.clone() },
            options: Default::default(),
            work_done_progress_params: Default::default(),
          },
          CancellationToken::new(),
        )
        .await;
      assert_eq!(result.unwrap(), $expected);
    };
  }

  #[test]
  fn should_format_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .add_remote_process_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin()
          .add_remote_process_plugin()
          .add_includes("**/*.{txt,ts}")
          .add_excludes("ignored_file.txt")
          .add_excludes("ignored-dir");
      })
      .initialize()
      .build();
    environment.write_file(".gitignore", "gitignored_file.txt\ngitignored_dir").unwrap();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          let file_uri = Uri::from_str("file:///file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 7), Position::new(0, 7)),
              new_text: "_formatted".to_string()
            }])
          );

          // update the document
          backend
            .did_change(DidChangeTextDocumentParams {
              text_document: VersionedTextDocumentIdentifier {
                uri: file_uri.clone(),
                version: 1,
              },
              content_changes: vec![TextDocumentContentChangeEvent {
                range: Some(Range::new(Position::new(0, 7), Position::new(0, 7))),
                range_length: None,
                text: "_formatted".to_string(),
              }],
            })
            .await;

          // format again, but it should be formatted now
          assert_format!(backend, file_uri, None);

          // change the text to an error
          backend
            .did_change(DidChangeTextDocumentParams {
              text_document: VersionedTextDocumentIdentifier {
                uri: file_uri.clone(),
                version: 1,
              },
              content_changes: vec![TextDocumentContentChangeEvent {
                range: Some(Range::new(Position::new(0, 0), Position::new(0, 17))),
                range_length: None,
                text: "plugin: should_error".to_string(),
              }],
            })
            .await;
          assert_format!(backend, file_uri, None);
          assert_eq!(
            environment.take_stderr_messages(),
            vec!["Failed formatting 'file:///file.txt': Did error.".to_string()],
          );

          let mut handles = Vec::new();
          for i in 0..50 {
            let file_uri = Uri::from_str(&format!("file:///file_{}.txt", i)).unwrap();
            let backend = backend.clone();
            handles.push(dprint_core::async_runtime::spawn(async move {
              let file_text = format!("testing_{}", i);
              backend
                .did_open(DidOpenTextDocumentParams {
                  text_document: TextDocumentItem {
                    uri: file_uri.clone(),
                    language_id: "txt".to_string(),
                    version: 0,
                    text: file_text.clone(),
                  },
                })
                .await;
              let result = backend
                .formatting(
                  DocumentFormattingParams {
                    text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                    options: Default::default(),
                    work_done_progress_params: Default::default(),
                  },
                  CancellationToken::new(),
                )
                .await;
              assert_eq!(
                result.unwrap().unwrap(),
                vec![TextEdit {
                  range: Range::new(Position::new(0, file_text.len() as u32), Position::new(0, file_text.len() as u32),),
                  new_text: "_formatted".to_string()
                }]
              );

              // test closing too
              backend
                .did_close(DidCloseTextDocumentParams {
                  text_document: TextDocumentIdentifier { uri: file_uri },
                })
                .await;
            }))
          }

          // ensure nothing panicked
          let results = future::join_all(handles).await;
          for result in results {
            result.unwrap();
          }

          // ignores excluded files
          let file_uri = Uri::from_str("file:///ignored_file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);

          // ignores gitignored files
          let file_uri = Uri::from_str("file:///gitignored_file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);

          // ignores file in gitignored dir
          let file_uri = Uri::from_str("file:///gitignored_dir/file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);

          // ignores excluded directory files
          let file_uri = Uri::from_str("file:///ignored-dir/file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);

          // ignores non-included files
          let file_uri = Uri::from_str("file:///file.txt_ps").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);

          // now update the config file to include it by removing the includes,
          // which it should in the range formatting
          {
            let mut config_file = TestConfigFileBuilder::new(environment.clone());
            config_file.add_remote_wasm_plugin().add_remote_process_plugin();
            environment.write_file("/dprint.json", &config_file.to_string()).unwrap();
          }

          // range formatting
          let result = backend
            .range_formatting(
              DocumentRangeFormattingParams {
                text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                range: Range {
                  start: Position { line: 0, character: 1 },
                  end: Position { line: 0, character: 2 },
                },
                options: Default::default(),
                work_done_progress_params: Default::default(),
              },
              CancellationToken::new(),
            )
            .await;
          assert_eq!(
            result.unwrap().unwrap(),
            vec![
              TextEdit {
                range: Range::new(Position::new(0, 1), Position::new(0, 1)),
                new_text: "_formatted_proc".to_string()
              },
              TextEdit {
                range: Range::new(Position::new(0, 3), Position::new(0, 3)),
                new_text: "s_s".to_string()
              },
              TextEdit {
                range: Range::new(Position::new(0, 7), Position::new(0, 7)),
                new_text: "_formatted_process".to_string()
              },
            ]
          );

          // cancellation via a drop
          let file_uri = Uri::from_str("file:///file_cancellation.txt_ps").unwrap();
          did_open!(backend, file_uri, "wait_cancellation");

          let token = Arc::new(CancellationToken::new());
          dprint_core::async_runtime::spawn({
            let backend = backend.clone();
            let token = token.clone();
            async move {
              let future = backend.formatting(
                DocumentFormattingParams {
                  text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                  options: Default::default(),
                  work_done_progress_params: Default::default(),
                },
                CancellationToken::new(),
              );
              // this token's cancellation will drop the future which
              // will cancel the formatting request internally
              tokio::select! {
                _ = future => {},
                _ = token.cancelled() => {}
              }
            }
          });

          // give some time for the message to be sent
          tokio::time::sleep(Duration::from_millis(50)).await;
          assert!(backend.has_pending().await);
          token.cancel();
          // give some time for the message to be cancelled
          tokio::time::sleep(Duration::from_millis(50)).await;
          assert!(!backend.has_pending().await);

          // create a config file with associations
          {
            let mut config_file = TestConfigFileBuilder::new(environment.clone());
            config_file
              .add_remote_wasm_plugin()
              .add_remote_process_plugin()
              .add_config_section(
                "test-plugin",
                r#"{
                "associations": [
                  "**/*.{txt,txt_ps}",
                  "some_file_name",
                  "test-process-plugin-exact-file"
                ],
                "ending": "wasm"
              }"#,
              )
              .add_config_section(
                "testProcessPlugin",
                r#"{
                "associations": [
                  "**/*.{txt,txt_ps,other}",
                  "test-process-plugin-exact-file"
                ]
                "ending": "ps"
              }"#,
              );
            environment.write_file("/dprint.json", &config_file.to_string()).unwrap();
          }

          // format using it
          let file_uri = Uri::from_str("file:///associations1.txt").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_wasm_ps".to_string()
            }])
          );
          backend
            .did_change(DidChangeTextDocumentParams {
              text_document: VersionedTextDocumentIdentifier {
                uri: file_uri.clone(),
                version: 1,
              },
              content_changes: vec![TextDocumentContentChangeEvent {
                range: Some(Range::new(Position::new(0, 0), Position::new(0, 4))),
                range_length: None,
                text: "plugin: text6".to_string(),
              }],
            })
            .await;
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 13), Position::new(0, 13)),
              new_text: "_wasm_ps_wasm_ps_ps".to_string()
            }])
          );

          // try .txt_ps file, which should act the same as above because
          // of the associations
          let file_uri = Uri::from_str("file:///associations1.txt_ps").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_wasm_ps".to_string()
            }])
          );

          // try the .other extension
          let file_uri = Uri::from_str("file:///dir/file.other").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_ps".to_string()
            }])
          );

          // try the exact file with no extension
          let file_uri = Uri::from_str("file:///dir/some_file_name").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_wasm".to_string()
            }])
          );

          // now try this special file name
          let file_uri = Uri::from_str("file:///dir/test-process-plugin-exact-file").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_wasm_ps".to_string()
            }])
          );

          // rewrite config with an override for package.txt
          {
            let mut config_file = TestConfigFileBuilder::new(environment.clone());
            config_file.add_remote_wasm_plugin().add_config_section(
              "test-plugin",
              r#"{
                "ending": "base",
                "overrides": {
                  "files": "**/package.txt",
                  "ending": "package"
                }
              }"#,
            );
            environment.write_file("/dprint.json", &config_file.to_string()).unwrap();
          }

          let file_uri = Uri::from_str("file:///package.txt").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_package".to_string()
            }])
          );

          // now ensure formatting works with a sub folder config file that has different config
          {
            let mut config_file = TestConfigFileBuilder::new(environment.clone());
            config_file.add_remote_wasm_plugin().add_remote_process_plugin();
            environment.mk_dir_all("/other_config").unwrap();
            environment.write_file("/other_config/dprint.json", &config_file.to_string()).unwrap();
            let mut config_file = TestConfigFileBuilder::new(environment.clone());
            config_file
              .add_remote_wasm_plugin()
              .add_remote_process_plugin()
              .add_config_section("test-plugin", r#"{"ending": "asdf"}"#)
              .add_config_section("testProcessPlugin", r#"{"ending": "asdf_ps"}"#);
            environment.mk_dir_all("/other_config/sub").unwrap();
            environment.write_file("/other_config/sub/dprint.json", &config_file.to_string()).unwrap();
          }

          for _ in 0..2 {
            let file_uri = Uri::from_str("file:///other_config/file.txt").unwrap();
            did_open!(backend, file_uri, "text");
            assert_format!(
              backend,
              file_uri,
              Some(vec![TextEdit {
                range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                new_text: "_formatted".to_string()
              }])
            );
            did_close!(backend, file_uri);
            // switching to a different config should still work fine
            let file_uri = Uri::from_str("file:///other_config/sub/file.txt").unwrap();
            did_open!(backend, file_uri, "text");
            assert_format!(
              backend,
              file_uri,
              Some(vec![TextEdit {
                range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                new_text: "_asdf".to_string()
              }])
            );
            did_close!(backend, file_uri);

            // now try with a process plugin
            let file_uri = Uri::from_str("file:///other_config/file.txt_ps").unwrap();
            did_open!(backend, file_uri, "text");
            assert_format!(
              backend,
              file_uri,
              Some(vec![TextEdit {
                range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                new_text: "_formatted_process".to_string()
              }])
            );
            did_close!(backend, file_uri);
            // switching to a different config should work fine as well
            let file_uri = Uri::from_str("file:///other_config/sub/file.txt_ps").unwrap();
            did_open!(backend, file_uri, "text");
            assert_format!(
              backend,
              file_uri,
              Some(vec![TextEdit {
                range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                new_text: "_asdf_ps".to_string()
              }])
            );
            did_close!(backend, file_uri);
          }

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string()),
          // the client is told about the formatting failure
          (MessageType::ERROR, "Failed formatting 'file:///file.txt': Did error.".to_string()),
        ]
      );
    });
  }

  #[test]
  fn should_inherit_ancestor_config_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin().add_config_section("test-plugin", r#"{ "ending": "root" }"#);
      })
      .with_local_config("/inherits/dprint.json", |c| {
        c.set_inherit(true);
      })
      .with_local_config("/inherits/overrides/dprint.json", |c| {
        c.set_inherit(true).add_config_section("test-plugin", r#"{ "ending": "nested" }"#);
      })
      .with_local_config("/no_inherit/dprint.json", |_| {})
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          macro_rules! assert_ending {
            ($uri:expr, $ending:expr) => {
              let file_uri = Uri::from_str($uri).unwrap();
              did_open!(backend, file_uri, "text");
              assert_format!(
                backend,
                file_uri,
                Some(vec![TextEdit {
                  range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                  new_text: $ending.to_string(),
                }])
              );
            };
          }

          assert_ending!("file:///file.txt", "_root");
          // inherits the plugins and their configuration from the ancestor config
          assert_ending!("file:///inherits/file.txt", "_root");
          // inherits through a config that also inherits and overrides the configuration
          assert_ending!("file:///inherits/overrides/file.txt", "_nested");

          // a config that doesn't inherit has no plugins
          let file_uri = Uri::from_str("file:///no_inherit/file.txt").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(backend, file_uri, None);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_format_with_other_configs_after_a_config_changes_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .add_remote_process_plugin()
      .with_local_config("/a/dprint.json", |c| {
        c.add_remote_process_plugin();
      })
      .with_local_config("/b/dprint.json", |c| {
        c.add_remote_process_plugin();
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          macro_rules! assert_ending {
            ($uri:expr, $ending:expr) => {
              let result = tokio::time::timeout(
                Duration::from_secs(10),
                backend.formatting(
                  DocumentFormattingParams {
                    text_document: TextDocumentIdentifier { uri: $uri.clone() },
                    options: Default::default(),
                    work_done_progress_params: Default::default(),
                  },
                  CancellationToken::new(),
                ),
              )
              .await
              .expect("timed out formatting");
              assert_eq!(
                result.unwrap(),
                Some(vec![TextEdit {
                  range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                  new_text: $ending.to_string(),
                }])
              );
            };
          }

          let a_uri = Uri::from_str("file:///a/file.txt_ps").unwrap();
          did_open!(backend, a_uri, "text");
          let b_uri = Uri::from_str("file:///b/file.txt_ps").unwrap();
          did_open!(backend, b_uri, "text");
          assert_ending!(a_uri, "_formatted_process");
          assert_ending!(b_uri, "_formatted_process");
          assert_eq!(environment.take_stderr_messages(), vec!["Extracting zip for test-process-plugin".to_string()]);

          // change one of the configs
          {
            let mut config_file = TestConfigFileBuilder::new(environment.clone());
            config_file
              .add_remote_process_plugin()
              .add_config_section("testProcessPlugin", r#"{ "ending": "changed" }"#);
            environment.write_file("/a/dprint.json", &config_file.to_string()).unwrap();
          }
          assert_ending!(a_uri, "_changed");

          // the other config's plugins were shut down along with the changed one's,
          // so ensure formatting with it still works and keeps working
          assert_ending!(b_uri, "_formatted_process");
          assert_ending!(b_uri, "_formatted_process");
          assert_ending!(a_uri, "_changed");
          assert_eq!(environment.take_stderr_messages(), Vec::<String>::new());

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_pick_up_gitignore_changes_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin();
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          macro_rules! assert_formats {
            ($uri:expr, $formats:expr) => {
              let expected = if $formats {
                Some(vec![TextEdit {
                  range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                  new_text: "_formatted".to_string(),
                }])
              } else {
                None
              };
              assert_format!(backend, $uri, expected);
            };
          }

          let dist_uri = Uri::from_str("file:///dist/file.txt").unwrap();
          did_open!(backend, dist_uri, "text");
          let src_uri = Uri::from_str("file:///src/file.txt").unwrap();
          did_open!(backend, src_uri, "text");
          let nested_uri = Uri::from_str("file:///src/nested/file.txt").unwrap();
          did_open!(backend, nested_uri, "text");

          // no gitignore yet
          assert_formats!(dist_uri, true);
          assert_formats!(src_uri, true);
          assert_formats!(nested_uri, true);

          // adding a gitignore without touching the dprint config
          environment.write_file("/.gitignore", "dist/").unwrap();
          assert_formats!(dist_uri, false);
          assert_formats!(src_uri, true);
          assert_formats!(nested_uri, true);

          // changing its entries
          environment.write_file("/.gitignore", "src/file.txt").unwrap();
          assert_formats!(dist_uri, true);
          assert_formats!(src_uri, false);
          assert_formats!(nested_uri, true);

          // adding a nested gitignore
          environment.mk_dir_all("/src/nested").unwrap();
          environment.write_file("/src/nested/.gitignore", "file.txt").unwrap();
          assert_formats!(dist_uri, true);
          assert_formats!(src_uri, false);
          assert_formats!(nested_uri, false);

          // removing the gitignores
          environment.remove_file("/.gitignore").unwrap();
          assert_formats!(src_uri, true);
          assert_formats!(nested_uri, false);
          environment.remove_file("/src/nested/.gitignore").unwrap();
          assert_formats!(nested_uri, true);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_pick_up_repo_root_gitignore_changes_above_config_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_local_config("/repo/sub/dprint.json", |c| {
        c.add_remote_wasm_plugin();
      })
      .initialize()
      .build();
    // the repository root is above the directory of the config
    environment.mk_dir_all("/repo/.git/info").unwrap();
    environment.write_file("/repo/.gitignore", "other/").unwrap();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          macro_rules! assert_formats {
            ($uri:expr, $formats:expr) => {
              let expected = if $formats {
                Some(vec![TextEdit {
                  range: Range::new(Position::new(0, 4), Position::new(0, 4)),
                  new_text: "_formatted".to_string(),
                }])
              } else {
                None
              };
              assert_format!(backend, $uri, expected);
            };
          }

          let dist_uri = Uri::from_str("file:///repo/sub/dist/file.txt").unwrap();
          did_open!(backend, dist_uri, "text");
          let src_uri = Uri::from_str("file:///repo/sub/src/file.txt").unwrap();
          did_open!(backend, src_uri, "text");

          assert_formats!(dist_uri, true);
          assert_formats!(src_uri, true);
          assert_eq!(
            environment.take_stderr_messages(),
            vec!["Compiling https://plugins.dprint.dev/test-plugin.wasm".to_string()]
          );

          // changing the gitignore at the repository root
          environment.write_file("/repo/.gitignore", "sub/dist/").unwrap();
          assert_formats!(dist_uri, false);
          assert_formats!(src_uri, true);

          // adding and then changing the repository's exclude file
          environment.write_file("/repo/.git/info/exclude", "sub/src/").unwrap();
          assert_formats!(dist_uri, false);
          assert_formats!(src_uri, false);
          environment.write_file("/repo/.git/info/exclude", "sub/other/").unwrap();
          assert_formats!(dist_uri, false);
          assert_formats!(src_uri, true);

          // a gitignore above the repository root doesn't apply
          environment.write_file("/.gitignore", "file.txt").unwrap();
          assert_formats!(dist_uri, false);
          assert_formats!(src_uri, true);

          // removing the gitignore at the repository root
          environment.remove_file("/repo/.gitignore").unwrap();
          assert_formats!(dist_uri, true);
          assert_formats!(src_uri, true);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_format_shebang_file_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin().add_config_section(
          "shebangs",
          r##"{
            "#!/bin/sh": "txt"
          }"##,
        );
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          // extensionless file with a matching shebang
          let file_uri = Uri::from_str("file:///scripts/build").unwrap();
          did_open!(backend, file_uri, "#!/bin/sh\ntext");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(1, 4), Position::new(1, 4)),
              new_text: "_formatted".to_string()
            }])
          );

          // extensionless file without a shebang
          let file_uri = Uri::from_str("file:///scripts/notes").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(backend, file_uri, None);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_format_notebook_cells_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .add_remote_process_plugin()
      .with_default_config(|c| {
        // the process plugin stands in for the jupyter plugin
        c.add_remote_wasm_plugin()
          .add_remote_process_plugin()
          .add_config_section("test-plugin", r#"{ "ending": "formatted\n" }"#)
          .add_config_section("testProcessPlugin", r#"{ "associations": ["**/*.ipynb"] }"#)
          .add_excludes("ignored-dir");
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          let result = backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              capabilities: ClientCapabilities {
                notebook_document: Some(Default::default()),
                text_document: Some(TextDocumentClientCapabilities {
                  formatting: Some(DynamicRegistrationClientCapabilities {
                    dynamic_registration: Some(true),
                  }),
                  range_formatting: Some(DynamicRegistrationClientCapabilities {
                    dynamic_registration: Some(true),
                  }),
                  ..Default::default()
                }),
                ..Default::default()
              },
              ..Default::default()
            })
            .await
            .unwrap();
          assert!(result.capabilities.notebook_document_sync.is_some());
          backend.initialized(InitializedParams {}).await;

          fn cell_document(uri: &Uri, language_id: &str, text: &str) -> TextDocumentItem {
            TextDocumentItem {
              uri: uri.clone(),
              language_id: language_id.to_string(),
              version: 0,
              text: text.to_string(),
            }
          }

          macro_rules! open_notebook {
            ($uri:expr, $cell_documents:expr) => {
              backend
                .notebook_did_open(DidOpenNotebookDocumentParams {
                  notebook_document: NotebookDocument {
                    uri: $uri.clone(),
                    notebook_type: "jupyter-notebook".to_string(),
                    version: 0,
                    metadata: None,
                    // the server only uses the documents of the cells
                    cells: Vec::new(),
                  },
                  cell_text_documents: $cell_documents,
                })
                .await;
            };
          }

          macro_rules! change_notebook {
            ($uri:expr, $cells:expr) => {
              backend
                .notebook_did_change(DidChangeNotebookDocumentParams {
                  notebook_document: VersionedNotebookDocumentIdentifier {
                    version: 1,
                    uri: $uri.clone(),
                  },
                  change: NotebookDocumentChangeEvent {
                    metadata: None,
                    cells: Some($cells),
                  },
                })
                .await;
            };
          }

          let notebook_uri = Uri::from_str("file:///dir/notebook.ipynb").unwrap();
          let cell_uri = Uri::from_str("vscode-notebook-cell:/dir/notebook.ipynb#W0sZmlsZQ%3D%3D").unwrap();
          let range_cell_uri = Uri::from_str("vscode-notebook-cell:/dir/notebook.ipynb#W1sZmlsZQ%3D%3D").unwrap();
          let python_cell_uri = Uri::from_str("vscode-notebook-cell:/dir/notebook.ipynb#W2sZmlsZQ%3D%3D").unwrap();
          open_notebook!(
            notebook_uri,
            vec![
              cell_document(&cell_uri, "txt", "text"),
              cell_document(&range_cell_uri, "txt", "text  "),
              cell_document(&python_cell_uri, "python", "text"),
            ]
          );

          // formats as the cell's language and trims the final newline
          assert_format!(
            backend,
            cell_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_formatted".to_string()
            }])
          );

          // range formatting before the end of the cell keeps the trailing whitespace
          let result = backend
            .range_formatting(
              DocumentRangeFormattingParams {
                text_document: TextDocumentIdentifier { uri: range_cell_uri.clone() },
                range: Range::new(Position::new(0, 1), Position::new(0, 2)),
                options: Default::default(),
                work_done_progress_params: Default::default(),
              },
              CancellationToken::new(),
            )
            .await;
          assert_eq!(
            result.unwrap(),
            Some(vec![
              TextEdit {
                range: Range::new(Position::new(0, 1), Position::new(0, 1)),
                new_text: "_formatt".to_string()
              },
              TextEdit {
                range: Range::new(Position::new(0, 2), Position::new(0, 2)),
                new_text: "d\n_".to_string()
              },
              TextEdit {
                range: Range::new(Position::new(0, 6), Position::new(0, 6)),
                new_text: "_formatted  ".to_string()
              },
            ])
          );

          // language without a plugin
          assert_format!(backend, python_cell_uri, None);

          // changing a cell's text
          change_notebook!(
            notebook_uri,
            NotebookDocumentCellChange {
              structure: None,
              data: None,
              text_content: Some(vec![NotebookDocumentChangeTextContent {
                document: VersionedTextDocumentIdentifier {
                  uri: cell_uri.clone(),
                  version: 1,
                },
                changes: vec![TextDocumentContentChangeEvent {
                  range: Some(Range::new(Position::new(0, 0), Position::new(0, 4))),
                  range_length: None,
                  text: "changed".to_string(),
                }],
              }]),
            }
          );
          assert_format!(
            backend,
            cell_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 7), Position::new(0, 7)),
              new_text: "_formatted".to_string()
            }])
          );

          // adding and removing cells
          let added_cell_uri = Uri::from_str("vscode-notebook-cell:/dir/notebook.ipynb#W3sZmlsZQ%3D%3D").unwrap();
          change_notebook!(
            notebook_uri,
            NotebookDocumentCellChange {
              structure: Some(NotebookDocumentCellChangeStructure {
                array: NotebookCellArrayChange {
                  start: 1,
                  delete_count: 1,
                  cells: None,
                },
                did_open: Some(vec![cell_document(&added_cell_uri, "txt", "added")]),
                did_close: Some(vec![TextDocumentIdentifier { uri: range_cell_uri.clone() }]),
              }),
              data: None,
              text_content: None,
            }
          );
          assert_format!(
            backend,
            added_cell_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 5), Position::new(0, 5)),
              new_text: "_formatted".to_string()
            }])
          );
          assert_format!(backend, range_cell_uri, None);

          // excluded notebook
          let other_notebook_uri = Uri::from_str("file:///ignored-dir/notebook.ipynb").unwrap();
          let other_cell_uri = Uri::from_str("vscode-notebook-cell:/ignored-dir/notebook.ipynb#W0sZmlsZQ%3D%3D").unwrap();
          open_notebook!(other_notebook_uri, vec![cell_document(&other_cell_uri, "txt", "text")]);
          assert_format!(backend, other_cell_uri, None);

          // notebook without a plugin
          let other_notebook_uri = Uri::from_str("file:///dir/notebook.other").unwrap();
          let other_cell_uri = Uri::from_str("vscode-notebook-cell:/dir/notebook.other#W0sZmlsZQ%3D%3D").unwrap();
          open_notebook!(other_notebook_uri, vec![cell_document(&other_cell_uri, "txt", "text")]);
          assert_format!(backend, other_cell_uri, None);

          // notebook that's not on the file system
          let other_notebook_uri = Uri::from_str("untitled:Untitled-1.ipynb").unwrap();
          let other_cell_uri = Uri::from_str("vscode-notebook-cell:Untitled-1.ipynb#W0sdW50aXRsZWQ%3D").unwrap();
          open_notebook!(other_notebook_uri, vec![cell_document(&other_cell_uri, "txt", "text")]);
          assert_format!(backend, other_cell_uri, None);

          // closing the notebook closes its cells
          backend
            .notebook_did_close(DidCloseNotebookDocumentParams {
              notebook_document: NotebookDocumentIdentifier { uri: notebook_uri.clone() },
              cell_text_documents: vec![
                TextDocumentIdentifier { uri: cell_uri.clone() },
                TextDocumentIdentifier { uri: python_cell_uri.clone() },
                TextDocumentIdentifier { uri: added_cell_uri.clone() },
              ],
            })
            .await;
          assert_format!(backend, cell_uri, None);
          assert_format!(backend, added_cell_uri, None);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      // the cells that were closed and the cell of the notebook that's not on the file system
      let closed_cell_warning = |cell_uri: &str| {
        format!(
          "Cannot format document that is not a file, an untitled document or a cell of an open notebook: {}",
          cell_uri
        )
      };
      let warnings = vec![
        closed_cell_warning("vscode-notebook-cell:/dir/notebook.ipynb#W1sZmlsZQ%3D%3D"),
        "Cannot format cell of a notebook that is not on the file system: vscode-notebook-cell:Untitled-1.ipynb#W0sdW50aXRsZWQ%3D".to_string(),
        closed_cell_warning("vscode-notebook-cell:/dir/notebook.ipynb#W0sZmlsZQ%3D%3D"),
        closed_cell_warning("vscode-notebook-cell:/dir/notebook.ipynb#W3sZmlsZQ%3D%3D"),
      ];
      assert_eq!(environment.take_stderr_messages(), warnings);
      assert_eq!(
        test_client.take_messages(),
        [
          vec![
            (
              MessageType::INFO,
              format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
            ),
            (MessageType::INFO, "Server ready.".to_string())
          ],
          warnings.into_iter().map(|message| (MessageType::WARNING, message)).collect(),
        ]
        .concat()
      );
      // the server has the client send it format requests for notebook cells
      assert_eq!(
        test_client.take_registered_methods(),
        vec!["textDocument/formatting", "textDocument/rangeFormatting"]
      );
    });
  }

  #[test]
  fn should_format_with_lsp_using_global_config() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_global_config(|c| {
        c.add_remote_wasm_plugin().add_includes("**/*.txt").add_excludes("ignored_file.txt");
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          // Test that global config is being used
          let file_uri = Uri::from_str("file:///file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 7), Position::new(0, 7)),
              new_text: "_formatted".to_string()
            }])
          );

          // Test that excluded file is not formatted
          let ignored_uri = Uri::from_str("file:///ignored_file.txt").unwrap();
          did_open!(backend, ignored_uri, "testing");
          assert_format!(backend, ignored_uri, None);

          // Test that non-matching file is not formatted
          let other_uri = Uri::from_str("file:///file.js").unwrap();
          did_open!(backend, other_uri, "testing");
          assert_format!(backend, other_uri, None);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_format_files_outside_cwd_with_lsp_using_global_config() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_global_config(|c| {
        c.add_remote_wasm_plugin().add_includes("**/*.txt").add_excludes("**/ignored_file.txt");
      })
      .initialize()
      .write_file("/project/file.txt", "")
      .set_cwd("/project")
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          let formatted = Some(vec![TextEdit {
            range: Range::new(Position::new(0, 7), Position::new(0, 7)),
            new_text: "_formatted".to_string(),
          }]);

          // file in the cwd
          let file_uri = Uri::from_str("file:///project/file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, formatted.clone());

          // file outside the cwd
          let file_uri = Uri::from_str("file:///other/dir/file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, formatted);

          // the excludes still apply outside the cwd
          let file_uri = Uri::from_str("file:///other/dir/ignored_file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_not_use_global_config_with_lsp_when_opted_out() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_global_config(|c| {
        c.add_remote_wasm_plugin().add_includes("**/*.txt");
      })
      .initialize()
      .build();
    environment.set_env_var("DPRINT_EDITOR_USE_GLOBAL_CONFIG", Some("false"));

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          let file_uri = Uri::from_str("file:///file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(backend, file_uri, None);
          assert_eq!(
            environment.take_stderr_messages(),
            vec!["Path did not have a dprint config file: /file.txt".to_string()]
          );

          // uses the global config when the client asks to
          let options = FormattingOptions {
            properties: HashMap::from([("useGlobalConfig".to_string(), FormattingProperty::Bool(true))]),
            ..Default::default()
          };
          let formatted = Some(vec![TextEdit {
            range: Range::new(Position::new(0, 7), Position::new(0, 7)),
            new_text: "_formatted".to_string(),
          }]);
          let result = backend
            .formatting(
              DocumentFormattingParams {
                text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                options: options.clone(),
                work_done_progress_params: Default::default(),
              },
              CancellationToken::new(),
            )
            .await;
          assert_eq!(result.unwrap(), formatted);
          let result = backend
            .range_formatting(
              DocumentRangeFormattingParams {
                text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                range: Range::new(Position::new(0, 0), Position::new(0, 7)),
                options,
                work_done_progress_params: Default::default(),
              },
              CancellationToken::new(),
            )
            .await;
          assert!(result.unwrap().is_some());

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_retry_failed_plugin_schema_download_with_lsp() {
    const SCHEMA_URL: &str = "https://plugins.dprint.dev/test/schema.json";
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_local_config("/project/dprint.json", |c| {
        c.add_remote_wasm_plugin();
      })
      .initialize()
      .set_cwd("/project")
      .build();
    environment.set_fs_time(1_000);

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          let file_uri = Uri::from_str("file:///project/dprint.json").unwrap();
          did_open!(backend, file_uri, "{\"test-plugin\":{}}");
          // gets the labels of the completions in the plugin's section
          let complete = || async {
            let result = backend
              .completion(
                CompletionParams {
                  text_document_position: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                    position: Position::new(0, 16),
                  },
                  work_done_progress_params: Default::default(),
                  partial_result_params: Default::default(),
                  context: None,
                },
                CancellationToken::new(),
              )
              .await
              .unwrap();
            let Some(CompletionResponse::List(list)) = result else {
              panic!("expected completion items");
            };
            // nothing is being downloaded once a request was answered here
            assert!(!list.is_incomplete);
            list.items.into_iter().map(|item| item.label).collect::<Vec<_>>()
          };

          // the schema can't be downloaded, so only what's in the base schema
          let labels = complete().await;
          assert!(labels.contains(&"locked".to_string()), "{:?}", labels);
          assert!(!labels.contains(&"ending".to_string()), "{:?}", labels);
          assert_eq!(
            environment.take_stderr_messages(),
            vec!["Compiling https://plugins.dprint.dev/test-plugin.wasm"]
          );

          // not attempted again right away
          environment.add_remote_file_bytes(SCHEMA_URL, br#"{ "properties": { "ending": { "type": "string" } } }"#.to_vec());
          environment.set_fs_time(1_030);
          let labels = complete().await;
          assert!(!labels.contains(&"ending".to_string()), "{:?}", labels);

          // but it is later on
          environment.set_fs_time(1_090);
          let labels = complete().await;
          assert!(labels.contains(&"locked".to_string()), "{:?}", labels);
          assert!(labels.contains(&"ending".to_string()), "{:?}", labels);

          // and then the downloaded schema is kept
          environment.add_remote_file_bytes(SCHEMA_URL, br#"{ "properties": { "other": { "type": "string" } } }"#.to_vec());
          environment.set_fs_time(10_000);
          let labels = complete().await;
          assert!(labels.contains(&"ending".to_string()), "{:?}", labels);
          assert!(!labels.contains(&"other".to_string()), "{:?}", labels);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_mark_completions_incomplete_while_plugin_schema_downloads_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_local_config("/project/dprint.json", |c| {
        c.add_remote_wasm_plugin();
      })
      .initialize()
      .set_cwd("/project")
      .build();
    environment.add_unresponsive_remote_file("https://plugins.dprint.dev/test/schema.json");

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          let file_uri = Uri::from_str("file:///project/dprint.json").unwrap();
          did_open!(backend, file_uri, "{\"test-plugin\":{}}");
          // the first request gives up on the download and the second one
          // doesn't wait on it
          for _ in 0..2 {
            let result = backend
              .completion(
                CompletionParams {
                  text_document_position: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: file_uri.clone() },
                    // in the plugin's section
                    position: Position::new(0, 16),
                  },
                  work_done_progress_params: Default::default(),
                  partial_result_params: Default::default(),
                  context: None,
                },
                CancellationToken::new(),
              )
              .await
              .unwrap();
            let Some(CompletionResponse::List(list)) = result else {
              panic!("expected completion items");
            };
            assert!(list.is_incomplete);
            assert!(list.items.iter().any(|item| item.label == "locked"));
          }
          assert_eq!(
            environment.take_stderr_messages(),
            vec!["Compiling https://plugins.dprint.dev/test-plugin.wasm"]
          );
          assert_eq!(environment.remote_file_request_count("https://plugins.dprint.dev/test/schema.json"), 1);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_format_with_lsp_using_config_override() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      // default config with a custom ending so we can tell which config is used
      .with_default_config(|c| {
        c.add_remote_wasm_plugin()
          .add_includes("**/*.txt")
          .add_config_section("test-plugin", r#"{"ending": "default"}"#);
      })
      // override config at a non-default path with a different ending
      .with_local_config("/custom/dprint.json", |c| {
        c.add_remote_wasm_plugin()
          .add_includes("**/*.txt")
          .add_config_section("test-plugin", r#"{"ending": "custom"}"#);
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      // pass the override config path
      let (backend, recv_task, test_client) = setup_backend_with_config(environment.clone(), Some(PathBuf::from("/custom/dprint.json")));
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          // should format using the overridden config (ending "custom"), not the default (ending "default")
          let file_uri = Uri::from_str("file:///custom/file.txt").unwrap();
          did_open!(backend, file_uri, "testing");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 7), Position::new(0, 7)),
              new_text: "_custom".to_string()
            }])
          );

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
    });
  }

  #[test]
  fn should_format_untitled_documents_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin().add_excludes("ignored-dir");
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        async move {
          fn workspace_folder(uri: &str) -> WorkspaceFolder {
            WorkspaceFolder {
              uri: Uri::from_str(uri).unwrap(),
              name: "folder".to_string(),
            }
          }

          let result = backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              capabilities: serde_json::from_value(serde_json::json!({
                "textDocument": {
                  "synchronization": { "dynamicRegistration": true },
                  "formatting": { "dynamicRegistration": true },
                  "rangeFormatting": { "dynamicRegistration": true },
                }
              }))
              .unwrap(),
              workspace_folders: Some(vec![workspace_folder("file:///workspace")]),
              ..Default::default()
            })
            .await
            .unwrap();
          // the client tells the server when the workspace folders change
          assert_eq!(
            serde_json::to_value(result.capabilities.workspace).unwrap(),
            serde_json::json!({ "workspaceFolders": { "supported": true, "changeNotifications": true } })
          );
          backend.initialized(InitializedParams {}).await;

          macro_rules! did_open_untitled {
            ($uri:expr, $language_id:expr) => {
              backend
                .did_open(DidOpenTextDocumentParams {
                  text_document: TextDocumentItem {
                    uri: $uri.clone(),
                    language_id: $language_id.to_string(),
                    version: 0,
                    text: "text".to_string(),
                  },
                })
                .await;
            };
          }

          // formats as a file of the language in the workspace folder
          let file_uri = Uri::from_str("untitled:Untitled-1").unwrap();
          did_open_untitled!(file_uri, "txt");
          assert_format!(
            backend,
            file_uri,
            Some(vec![TextEdit {
              range: Range::new(Position::new(0, 4), Position::new(0, 4)),
              new_text: "_formatted".to_string()
            }])
          );

          // language without a plugin
          let other_file_uri = Uri::from_str("untitled:Untitled-2").unwrap();
          did_open_untitled!(other_file_uri, "python");
          assert_format!(backend, other_file_uri, None);

          // uses the first workspace folder after they change, which is excluded
          backend
            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
              event: WorkspaceFoldersChangeEvent {
                added: vec![workspace_folder("file:///ignored-dir")],
                removed: vec![workspace_folder("file:///workspace")],
              },
            })
            .await;
          assert_format!(backend, file_uri, None);

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();

      assert_eq!(
        test_client.take_messages(),
        vec![
          (
            MessageType::INFO,
            format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
          ),
          (MessageType::INFO, "Server ready.".to_string())
        ]
      );
      // the server has the client send it untitled documents
      assert_eq!(
        test_client.take_registered_methods(),
        vec![
          "textDocument/didOpen",
          "textDocument/didChange",
          "textDocument/didClose",
          "textDocument/formatting",
          "textDocument/rangeFormatting",
        ]
      );
    });
  }

  #[test]
  fn should_only_provide_completion_and_hover_for_config_files_with_lsp() {
    // (client capabilities, has static completion, has static hover, registered methods)
    let cases: Vec<(serde_json::Value, bool, bool, Vec<&str>)> = vec![
      (
        serde_json::json!({
          "textDocument": {
            "completion": { "dynamicRegistration": true },
            "hover": { "dynamicRegistration": true },
          }
        }),
        false,
        false,
        vec!["textDocument/completion", "textDocument/hover"],
      ),
      // a client that can only register one of them
      (
        serde_json::json!({
          "textDocument": {
            "completion": { "dynamicRegistration": false },
            "hover": { "dynamicRegistration": true },
          }
        }),
        true,
        false,
        vec!["textDocument/hover"],
      ),
      (
        serde_json::json!({
          "textDocument": {
            "completion": { "dynamicRegistration": true },
          }
        }),
        false,
        true,
        vec!["textDocument/completion"],
      ),
      // a client that can't register them has them for every document
      (serde_json::json!({}), true, true, vec![]),
    ];

    for (capabilities, has_static_completion, has_static_hover, registered_methods) in cases {
      let environment = TestEnvironmentBuilder::new().build();
      environment.clone().run_in_runtime(async move {
        let (backend, recv_task, test_client) = setup_backend(environment.clone());
        let result = backend
          .initialize(InitializeParams {
            process_id: Some(std::process::id()),
            capabilities: serde_json::from_value(capabilities.clone()).unwrap(),
            ..Default::default()
          })
          .await
          .unwrap();
        assert_eq!(
          serde_json::to_value(&result.capabilities.completion_provider).unwrap(),
          if has_static_completion {
            serde_json::json!({ "triggerCharacters": ["\"", ":"] })
          } else {
            serde_json::Value::Null
          },
          "completion for {}",
          capabilities
        );
        assert_eq!(
          serde_json::to_value(&result.capabilities.hover_provider).unwrap(),
          if has_static_hover { serde_json::json!(true) } else { serde_json::Value::Null },
          "hover for {}",
          capabilities
        );
        // nothing is registered until the client is initialized
        assert_eq!(test_client.take_registered_methods(), Vec::<String>::new());
        backend.initialized(InitializedParams {}).await;
        backend.shutdown().await.unwrap();
        recv_task.await.unwrap();

        assert_eq!(
          test_client.take_messages(),
          vec![
            (
              MessageType::INFO,
              format!("dprint {} ({}-{})", environment.cli_version(), environment.os(), environment.cpu_arch())
            ),
            (MessageType::INFO, "Server ready.".to_string())
          ]
        );
        assert_eq!(test_client.take_registered_methods(), registered_methods, "registrations for {}", capabilities);
      });
    }
  }

  #[test]
  fn should_log_format_failures_to_client_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin().add_includes("**/*.txt");
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        let test_client = test_client.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;
          test_client.take_messages();

          macro_rules! assert_range_format {
            ($uri:expr, $range:expr, $expected:expr) => {
              let result = backend
                .range_formatting(
                  DocumentRangeFormattingParams {
                    text_document: TextDocumentIdentifier { uri: $uri.clone() },
                    range: $range,
                    options: Default::default(),
                    work_done_progress_params: Default::default(),
                  },
                  CancellationToken::new(),
                )
                .await;
              assert_eq!(result.unwrap(), $expected);
            };
          }
          macro_rules! assert_logged {
            ($message_type:expr, $message:expr) => {
              assert_eq!(environment.take_stderr_messages(), vec![$message.to_string()]);
              assert_eq!(test_client.take_messages(), vec![($message_type, $message.to_string())]);
            };
          }

          // the plugin failing to format the file, which is not a json-rpc
          // error because that's what happens for a file with a syntax error
          let file_uri = Uri::from_str("file:///file.txt").unwrap();
          did_open!(backend, file_uri, "should_error");
          assert_format!(backend, file_uri, None);
          assert_logged!(MessageType::ERROR, "Failed formatting 'file:///file.txt': Did error.");

          // range with its start after its end
          assert_range_format!(file_uri, Range::new(Position::new(0, 2), Position::new(0, 1)), None);
          assert_logged!(
            MessageType::WARNING,
            "Invalid range for 'file:///file.txt'. The start of the range was after its end."
          );

          // document that's not open
          let not_open_uri = Uri::from_str("file:///not_open.txt").unwrap();
          assert_format!(backend, not_open_uri, None);
          assert_logged!(MessageType::WARNING, "Missing document: file:///not_open.txt");
          let valid_range = Range::new(Position::new(0, 0), Position::new(0, 1));
          assert_range_format!(not_open_uri, valid_range, None);
          assert_logged!(MessageType::WARNING, "Missing document: file:///not_open.txt");
          let not_open_uri = Uri::from_str("untitled:Untitled-1").unwrap();
          assert_format!(backend, not_open_uri, None);
          assert_logged!(MessageType::WARNING, "Missing document: untitled:Untitled-1");

          // document that's not on the file system
          let other_uri = Uri::from_str("other:/file.txt").unwrap();
          did_open!(backend, other_uri, "text");
          assert_format!(backend, other_uri, None);
          assert_logged!(
            MessageType::WARNING,
            "Cannot format document that is not a file, an untitled document or a cell of an open notebook: other:/file.txt"
          );
          assert_range_format!(other_uri, valid_range, None);
          assert_logged!(
            MessageType::WARNING,
            "Cannot format document that is not a file, an untitled document or a cell of an open notebook: other:/file.txt"
          );

          // path without a parent directory
          let root_uri = Uri::from_str("file:///").unwrap();
          did_open!(backend, root_uri, "text");
          assert_format!(backend, root_uri, None);
          assert_logged!(MessageType::WARNING, "Cannot format non-file path: /");
          assert_range_format!(root_uri, valid_range, None);
          assert_logged!(MessageType::WARNING, "Cannot format non-file path: /");

          // untitled document in a language without a known file extension
          let untitled_uri = Uri::from_str("untitled:Untitled-2").unwrap();
          backend
            .did_open(DidOpenTextDocumentParams {
              text_document: TextDocumentItem {
                uri: untitled_uri.clone(),
                language_id: "some language".to_string(),
                version: 0,
                text: "text".to_string(),
              },
            })
            .await;
          assert_format!(backend, untitled_uri, None);
          assert_logged!(
            MessageType::WARNING,
            "Could not determine a file path to format the untitled document with language: some language"
          );

          // config file that fails to resolve
          environment.write_file("/dprint.json", "{").unwrap();
          did_close!(backend, file_uri);
          did_open!(backend, file_uri, "text");
          assert_format!(backend, file_uri, None);
          assert_logged!(
            MessageType::ERROR,
            "Failed formatting 'file:///file.txt': Error deserializing. Unterminated object on line 1 column 2\n    at /dprint.json"
          );

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();
    });
  }

  #[test]
  fn should_log_plugin_config_diagnostics_to_client_with_lsp() {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin()
          .add_config_section("test-plugin", r#"{ "non-existent": 1 }"#)
          .add_includes("**/*.txt");
      })
      .initialize()
      .build();

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        let test_client = test_client.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;
          test_client.take_messages();

          // stderr only has the text of the diagnostics the first time the
          // plugin is used, but the client is told for every failure
          let file_uri = Uri::from_str("file:///file.txt").unwrap();
          did_open!(backend, file_uri, "text");
          let client_message = (
            MessageType::ERROR,
            concat!(
              "Failed formatting 'file:///file.txt': Had 1 configuration errors.\n",
              "[test-plugin]: Unknown property in configuration (non-existent)"
            )
            .to_string(),
          );
          assert_format!(backend, file_uri, None);
          assert_eq!(
            environment.take_stderr_messages(),
            vec![
              "[test-plugin]: Unknown property in configuration (non-existent)",
              "[test-plugin]: Error initializing from configuration file. Had 1 diagnostic(s).",
              "Failed formatting 'file:///file.txt': Had 1 configuration errors.",
            ]
          );
          assert_eq!(test_client.take_messages(), vec![client_message.clone()]);
          assert_format!(backend, file_uri, None);
          assert_eq!(
            environment.take_stderr_messages(),
            vec!["Failed formatting 'file:///file.txt': Had 1 configuration errors."]
          );
          assert_eq!(test_client.take_messages(), vec![client_message]);

          // diagnostics in a plugin's overrides
          let mut config_file = TestConfigFileBuilder::new(environment.clone());
          config_file.add_remote_wasm_plugin().add_config_section(
            "test-plugin",
            r#"{
              "overrides": {
                "files": "**/other.txt",
                "unknownProperty": true
              }
            }"#,
          );
          environment.mk_dir_all("/overrides").unwrap();
          environment.write_file("/overrides/dprint.json", &config_file.to_string()).unwrap();
          let file_uri = Uri::from_str("file:///overrides/file.txt").unwrap();
          did_open!(backend, file_uri, "text");
          assert_format!(backend, file_uri, None);
          assert_eq!(
            environment.take_stderr_messages(),
            vec![
              "[test-plugin]: Unknown property in configuration (unknownProperty)",
              "[test-plugin]: Error initializing from configuration file. Had 1 diagnostic(s).",
              "Failed formatting 'file:///overrides/file.txt': Had 1 configuration errors.",
            ]
          );
          assert_eq!(
            test_client.take_messages(),
            vec![(
              MessageType::ERROR,
              concat!(
                "Failed formatting 'file:///overrides/file.txt': Had 1 configuration errors.\n",
                "[test-plugin]: Unknown property in configuration (unknownProperty)"
              )
              .to_string()
            )]
          );

          backend.shutdown().await.unwrap();
        }
      });

      try_join!(recv_task, run_test_task).unwrap();
    });
  }

  #[test]
  fn should_ensure_stable_format_with_lsp() {
    // formats once by default
    let (edits, stderr_messages) = format_unstable_text_with_lsp(None);
    assert_eq!(
      edits,
      Some(vec![
        TextEdit {
          range: Range::new(Position::new(0, 13), Position::new(0, 14)),
          new_text: "false_fo".to_string()
        },
        TextEdit {
          range: Range::new(Position::new(0, 15), Position::new(0, 16)),
          new_text: "matt".to_string()
        },
        TextEdit {
          range: Range::new(Position::new(0, 17), Position::new(0, 17)),
          new_text: "d".to_string()
        },
      ])
    );
    assert_eq!(stderr_messages, Vec::<String>::new());

    // formats again until the output is stable, like `dprint fmt`, when opted in
    let (edits, stderr_messages) = format_unstable_text_with_lsp(Some("true"));
    assert_eq!(edits, None);
    assert_eq!(
      stderr_messages,
      vec![concat!(
        "Failed formatting 'file:///file.txt': Formatting not stable. Bailed after 5 tries. ",
        "This indicates a bug in the plugin where it formats the file differently each time."
      )],
    );
  }

  fn format_unstable_text_with_lsp(stable_format_env_var: Option<&str>) -> (Option<Vec<TextEdit>>, Vec<String>) {
    let environment = TestEnvironmentBuilder::new()
      .add_remote_wasm_plugin()
      .with_default_config(|c| {
        c.add_remote_wasm_plugin().add_includes("**/*.txt");
      })
      .initialize()
      .build();
    environment.set_env_var("DPRINT_EDITOR_STABLE_FORMAT", stable_format_env_var);

    environment.clone().run_in_runtime(async move {
      let (backend, recv_task, test_client) = setup_backend(environment.clone());
      let backend = Rc::new(backend);
      let run_test_task = dprint_core::async_runtime::spawn({
        let environment = environment.clone();
        async move {
          backend
            .initialize(InitializeParams {
              process_id: Some(std::process::id()),
              ..Default::default()
            })
            .await
            .unwrap();
          backend.initialized(InitializedParams {}).await;

          let file_uri = Uri::from_str("file:///file.txt").unwrap();
          did_open!(backend, file_uri, "unstable_fmt_true");
          let edits = backend
            .formatting(
              DocumentFormattingParams {
                text_document: TextDocumentIdentifier { uri: file_uri },
                options: Default::default(),
                work_done_progress_params: Default::default(),
              },
              CancellationToken::new(),
            )
            .await
            .unwrap();
          let stderr_messages = environment.take_stderr_messages();

          backend.shutdown().await.unwrap();
          (edits, stderr_messages)
        }
      });

      let (_, result) = try_join!(recv_task, run_test_task).unwrap();
      test_client.take_messages();
      result
    })
  }

  #[test]
  fn exit_code_for_shutdown_request() {
    // the message handler says a shutdown request was received
    let environment = TestEnvironmentBuilder::new().build();
    let shutdown_received = environment.clone().run_in_runtime(async move {
      let (backend, recv_task, _test_client) = setup_backend(environment.clone());
      backend.shutdown().await.unwrap();
      // a second one after the message handler stopped should not hang
      backend.shutdown().await.unwrap();
      recv_task.await.unwrap()
    });
    assert!(shutdown_received);
    assert_eq!(get_exit_code(shutdown_received), 0);

    // and that one wasn't when the client exits or disconnects without one,
    // which drops the backend
    let environment = TestEnvironmentBuilder::new().build();
    let shutdown_received = environment.clone().run_in_runtime(async move {
      let (backend, recv_task, _test_client) = setup_backend(environment.clone());
      drop(backend);
      recv_task.await.unwrap()
    });
    assert!(!shutdown_received);
    assert_eq!(get_exit_code(shutdown_received), 1);
  }

  fn setup_backend(environment: TestEnvironment) -> (Backend<TestEnvironment>, JoinHandle<bool>, Arc<TestClient>) {
    setup_backend_with_config(environment, None)
  }

  fn setup_backend_with_config(
    environment: TestEnvironment,
    config_override: Option<PathBuf>,
  ) -> (Backend<TestEnvironment>, JoinHandle<bool>, Arc<TestClient>) {
    let plugin_cache = PluginCache::new(environment.clone());
    let plugin_resolver = Rc::new(PluginResolver::new(environment.clone(), plugin_cache));
    let (tx, rx) = mpsc::unbounded_channel();
    let recv_task = start_message_handler(&environment, &plugin_resolver, config_override, rx);
    let test_client = Arc::new(TestClient::default());
    (Backend::new(ClientWrapper::new(test_client.clone()), environment, tx), recv_task, test_client)
  }

  #[derive(Debug, Default)]
  struct TestClient {
    logged_messages: Mutex<Vec<(MessageType, String)>>,
    registrations: Mutex<Vec<Registration>>,
  }

  impl Drop for TestClient {
    fn drop(&mut self) {
      // If this panics that means the logged messages weren't inspected for a test.
      if !std::thread::panicking() {
        let logged_messages = self.logged_messages.lock().clone();
        assert_eq!(
          logged_messages,
          Vec::<(MessageType, String)>::new(),
          "should not have logged messages left on drop"
        );
      }
    }
  }

  impl TestClient {
    pub fn take_messages(&self) -> Vec<(MessageType, String)> {
      self.logged_messages.lock().drain(..).collect()
    }

    pub fn take_registered_methods(&self) -> Vec<String> {
      self.registrations.lock().drain(..).map(|r| r.method).collect()
    }
  }

  impl ClientTrait for TestClient {
    fn log(&self, message_type: MessageType, message: String) {
      self.logged_messages.lock().push((message_type, message));
    }

    fn register_capabilities(&self, registrations: Vec<Registration>) {
      self.registrations.lock().extend(registrations);
    }
  }
}