larust-cli 0.13.0

A Laravel-shaped web framework for Rust.
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
use crate::config_template;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

const APP_DIRS: &[&str] = &[
    ".vscode",
    "app/Http/Controllers",
    "app/Http/Middleware",
    "app/Http/Requests",
    "app/Models",
    "app/Policies",
    "app/Providers",
    "app/Jobs",
    "app/Events",
    "app/Console/Commands",
    "app/Wire",
    "app/Mail",
    "app/Services",
    "config",
    "database/migrations",
    "database/factories",
    "database/seeders",
    "public",
    "resources/views/layouts",
    "resources/views/posts",
    "resources/views/emails",
    "resources/assets",
    "resources/lang",
    "routes",
    "storage/app",
    "tests",
];

/// Crates every generated app currently depends on, resolved as `path`
/// dependencies onto this workspace checkout (Larust isn't published yet).
const FRAMEWORK_CRATES: &[&str] = &["larust-core", "larust-http", "larust-support"];
// Dev-only: never shipped, so not subject to the "one dependency surface"
// rule above - `larust-testing` is added to `[dev-dependencies]`, not
// `[dependencies]`.
const DEV_FRAMEWORK_CRATES: &[&str] = &["larust-testing"];

const CONTROLLERS_MOD_RS: &str =
    "pub mod post_controller;\n\npub use post_controller::PostController;\n";

const POST_CONTROLLER_RS: &str = r#"use larust_http::session::Session;
use larust_support::axum::response::IntoResponse;
use larust_support::view;
use larust_support::AppError;

use crate::models::{NewPost, Post};
use crate::requests::StorePostRequest;

pub struct PostController;

impl PostController {
    pub async fn index(session: Session) -> Result<impl IntoResponse, AppError> {
        let posts = Post::all().await?;
        let flash_success = larust_http::session::take::<String>(&session, "success")
            .await
            .ok()
            .flatten()
            .unwrap_or_default();
        let csrf_token = larust_http::csrf::token(&session).await;
        let is_authenticated = larust_support::auth::check(&session).await?;
        let nav_active = "posts";
        Ok(view!("posts.index", { posts, flash_success, csrf_token, is_authenticated, nav_active }))
    }

    pub async fn create(session: Session) -> Result<impl IntoResponse, AppError> {
        let csrf_token = larust_http::csrf::token(&session).await;
        let is_authenticated = true;
        let nav_active = "create";
        Ok(view!("posts.create", { csrf_token, is_authenticated, nav_active }))
    }

    pub async fn show(post: Post) -> String {
        format!("{} (id {})", post.title, post.id)
    }

    pub async fn store(
        session: Session,
        request: StorePostRequest,
    ) -> Result<impl IntoResponse, AppError> {
        let validated = request.validated();
        let post = Post::create(NewPost {
            title: validated.title,
        })
        .await?;

        Ok(larust_support::redirect()
            .route("posts.index")?
            .with(
                &session,
                "success",
                format!("Post \"{}\" (id {}) created.", post.title, post.id),
            )
            .await)
    }
}
"#;

const POST_CONTROLLER_RS_WITH_AUTH: &str = r#"use larust_http::session::Session;
use larust_support::auth::Auth;
use larust_support::axum::response::IntoResponse;
use larust_support::view;
use larust_support::AppError;

use crate::models::{Comment, NewPost, Post, User};
use crate::requests::StorePostRequest;

/// A post plus its author's display name - `view!`'s `@foreach` binds a
/// single identifier per iteration (no tuple destructuring), so the
/// author name a `belongs_to` lookup resolves is flattened onto a small
/// per-view struct rather than passing `(Post, String)` pairs.
struct PostWithAuthor {
    title: String,
    author_name: String,
}

/// Same flattening as `PostWithAuthor` above, for a comment's author.
struct CommentWithAuthor {
    author_name: String,
    body: String,
}

pub struct PostController;

impl PostController {
    pub async fn index(session: Session) -> Result<impl IntoResponse, AppError> {
        let posts = Post::all().await?;

        // Batch-loaded (eager) rather than one `post.user()` lookup per
        // post - `Post::load_user` is `#[belongs_to(...)]`'s generated
        // batch loader, fetching every author in one query instead of one
        // query per post.
        let authors = Post::load_user(&posts).await?;
        let posts_with_author: Vec<PostWithAuthor> = posts
            .into_iter()
            .map(|post| {
                let author_name = authors
                    .get(&post.user_id)
                    .map(|user| user.name.clone())
                    .unwrap_or_else(|| "Unknown".to_string());
                PostWithAuthor {
                    title: post.title,
                    author_name,
                }
            })
            .collect();

        let flash_success = larust_http::session::take::<String>(&session, "success")
            .await
            .ok()
            .flatten()
            .unwrap_or_default();
        let csrf_token = larust_http::csrf::token(&session).await;
        let is_authenticated = larust_support::auth::check(&session).await?;
        let nav_active = "posts";
        Ok(view!("posts.index", { posts: posts_with_author, flash_success, csrf_token, is_authenticated, nav_active }))
    }

    pub async fn create(session: Session) -> Result<impl IntoResponse, AppError> {
        let csrf_token = larust_http::csrf::token(&session).await;
        let is_authenticated = true;
        let nav_active = "create";
        Ok(view!("posts.create", { csrf_token, is_authenticated, nav_active }))
    }

    pub async fn show(session: Session, post: Post) -> Result<impl IntoResponse, AppError> {
        let author_name = post
            .user()
            .await?
            .map(|author| author.name)
            .unwrap_or_else(|| "Unknown".to_string());

        // Live-updated by `CommentController::store`'s
        // `reverb::broadcast_event` for every *other* open tab on this
        // page - this initial load is only what already existed when the
        // page was requested.
        let comments = post.comments().await?;
        let comment_authors = Comment::load_user(&comments).await?;
        let comments: Vec<CommentWithAuthor> = comments
            .into_iter()
            .map(|comment| {
                let author_name = comment_authors
                    .get(&comment.user_id)
                    .map(|user| user.name.clone())
                    .unwrap_or_else(|| "Unknown".to_string());
                CommentWithAuthor {
                    author_name,
                    body: comment.body,
                }
            })
            .collect();

        let csrf_token = larust_http::csrf::token(&session).await;
        let is_authenticated = larust_support::auth::check(&session).await?;
        let nav_active = "posts";
        Ok(view!("posts.show", {
            id: post.id,
            title: post.title,
            author_name,
            comments,
            csrf_token,
            is_authenticated,
            nav_active,
        }))
    }

    pub async fn store(
        session: Session,
        Auth(user): Auth<User>,
        request: StorePostRequest,
    ) -> Result<impl IntoResponse, AppError> {
        let validated = request.validated();
        let post = Post::create(NewPost {
            user_id: user.id,
            title: validated.title,
        })
        .await?;

        Ok(larust_support::redirect()
            .route("posts.index")?
            .with(
                &session,
                "success",
                format!("Post \"{}\" (id {}) created.", post.title, post.id),
            )
            .await)
    }
}
"#;

const COMMENT_MODEL_RS: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;

use crate::models::User;

#[derive(Model, sqlx::FromRow)]
#[table("comments")]
#[belongs_to(User, foreign_key = "user_id")]
pub struct Comment {
    #[primary_key]
    pub id: i64,
    pub post_id: i64,
    pub user_id: i64,
    pub body: String,
}
"#;

const STORE_COMMENT_REQUEST_RS: &str = r#"use larust_support::FormRequest;

#[derive(FormRequest)]
pub struct StoreCommentRequest {
    #[validate(required, length(max = 2000))]
    pub body: String,
}
"#;

const COMMENT_CONTROLLER_RS: &str = r#"use larust_support::auth::Auth;
use larust_support::axum::response::IntoResponse;
use larust_support::AppError;

use crate::models::{Comment, NewComment, Post, User};
use crate::requests::StoreCommentRequest;

pub struct CommentController;

impl CommentController {
    /// A plain POST + redirect back to the post page, same shape as
    /// `PostController::store` - the "no reload needed" half of live
    /// comments isn't this handler's job at all: it's
    /// `larust_support::reverb::broadcast_event` below, which pushes the
    /// new comment to every *other* open tab on this post's page over
    /// `posts.{post_id}.comments`. The submitting browser gets there the
    /// ordinary way (this redirect); everyone else's tab gets there via
    /// `LarustReverb.channel(...).listen('CommentCreated', ...)`
    /// (`resources/views/posts/show.blade.xr`) appending the same data as
    /// a DOM node with no page load at all.
    pub async fn store(
        Auth(user): Auth<User>,
        post: Post,
        request: StoreCommentRequest,
    ) -> Result<impl IntoResponse, AppError> {
        let validated = request.validated();
        let comment = Comment::create(NewComment {
            post_id: post.id,
            user_id: user.id,
            body: validated.body,
        })
        .await?;

        larust_support::reverb::broadcast_event(
            &format!("posts.{}.comments", post.id),
            "CommentCreated",
            &larust_support::serde_json::json!({
                "author": user.name,
                "body": comment.body,
            }),
        )?;

        larust_support::redirect().to(&format!("/posts/{}", post.id))
    }
}
"#;

const LAYOUT_APP_BLADE_XR: &str = r##"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#f4513d">
    <meta name="view-transition" content="same-origin">
    <meta name="csrf-token" content="{{ csrf_token }}">
    <script>(function(){try{var t=localStorage.getItem('larust-theme');document.documentElement.dataset.theme=t||(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(_){}})()</script>
    <title>Larust - ship with confidence</title>
    <style>
        :root { --ink: #202124; --muted: #6b6d73; --paper: #fffdf9; --canvas: #f4f0e8; --line: #e4ddd2; --brand: #f4513d; --brand-dark: #cf3628; --mint: #b9e4d0; } [data-theme="dark"] { --ink: #f6f1e8; --muted: #b8b1a8; --paper: #272522; --canvas: #181716; --line: #45413b; --brand: #ff735f; --brand-dark: #ff8a79; }
        * { box-sizing: border-box; }
        body { margin: 0; color: var(--ink); background: var(--canvas); font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; line-height: 1.5; }
        a { color: inherit; text-decoration: none; }
        .site-header { width: min(1120px, calc(100% - 40px)); margin: 0 auto; padding: 22px 0; display: flex; justify-content: space-between; align-items: center; }
        .brand { display: inline-flex; gap: 10px; align-items: center; font-size: 1.15rem; font-weight: 800; letter-spacing: -.04em; }
        .brand-mark { display: grid; place-items: center; width: 30px; height: 30px; color: white; background: var(--brand); border-radius: 9px 9px 9px 2px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .9rem; }
        .nav { display: flex; gap: 18px; align-items: center; font-size: .9rem; font-weight: 650; }.nav form { margin: 0; }
        .nav-link { color: var(--muted); }.nav-link:hover { color: var(--brand-dark); }.nav-link.is-active { color: var(--ink); position: relative; }.nav-link.is-active::after { content: ""; position: absolute; right: 0; bottom: -7px; left: 0; height: 2px; background: var(--brand); border-radius: 2px; }
        .nav-cta, .button { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 10px; padding: 11px 16px; background: var(--brand); color: white; font: inherit; font-weight: 750; cursor: pointer; box-shadow: 0 6px 14px rgba(244, 81, 61, .18); transition: transform .15s ease, background .15s ease; }
        .nav-cta:hover, .button:hover { background: var(--brand-dark); color: white; transform: translateY(-1px); }.nav-cta.is-active { box-shadow: inset 0 0 0 2px white, 0 6px 14px rgba(244, 81, 61, .18); }.logout-button { border: 0; padding: 0; background: transparent; color: var(--muted); font: inherit; font-weight: 650; cursor: pointer; }.logout-button:hover { color: var(--brand-dark); }.theme-toggle { display: grid; place-items: center; width: 34px; height: 34px; padding: 0; color: var(--muted); background: transparent; border: 1px solid var(--line); border-radius: 9px; cursor: pointer; }.theme-toggle:hover { color: var(--ink); background: var(--paper); }.theme-toggle svg { width: 17px; height: 17px; }.theme-toggle .moon { display: none; } [data-theme="dark"] .theme-toggle .sun { display: none; } [data-theme="dark"] .theme-toggle .moon { display: block; } [data-theme="dark"] input { background: #201e1c; border-color: var(--line); color: var(--ink); } [data-theme="dark"] .button-secondary { background: #33302c; color: var(--ink); } [data-theme="dark"] .button-secondary:hover { background: #3a3733; }
        .page { width: min(1120px, calc(100% - 40px)); margin: 0 auto 52px; }.page-narrow { width: min(520px, calc(100% - 40px)); margin: 42px auto 70px; }
        .display { margin: 8px 0 12px; max-width: 700px; font-size: clamp(2.35rem, 6vw, 4.5rem); line-height: .98; letter-spacing: -.07em; }.lead { max-width: 560px; color: var(--muted); font-size: 1.08rem; }
        .hero { padding: 68px 0 50px; }.hero-actions { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 28px; margin-bottom: 20px; }.button-secondary { background: var(--paper); color: var(--ink); box-shadow: inset 0 0 0 1px var(--line); }.button-secondary:hover { background: #fff; color: var(--ink); }
        .feature-grid, .post-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }.feature, .post-card, .form-card { background: var(--paper); border: 1px solid var(--line); border-radius: 18px; }.feature { padding: 22px; }.feature strong { display: block; margin-bottom: 8px; font-size: 1.05rem; }.feature p { margin: 0; color: var(--muted); font-size: .92rem; }
        .page-heading { display: flex; align-items: end; justify-content: space-between; gap: 18px; margin: 38px 0 24px; }.page-title { margin: 4px 0 0; font-size: clamp(2rem, 4vw, 3rem); letter-spacing: -.055em; }.flash-success, .flash-error { margin: 22px 0; padding: 13px 16px; border-radius: 12px; font-weight: 650; }.flash-success { color: #155b41; background: #dff5e9; }.flash-error { color: #8c3028; background: #ffebe7; }
        .post-card { min-height: 170px; padding: 22px; display: flex; flex-direction: column; justify-content: space-between; }.post-title { margin: 0 0 10px; font-size: 1.2rem; letter-spacing: -.03em; }.post-meta { margin: 0; color: var(--muted); font-size: .9rem; }.tag-line { margin-top: 16px; color: var(--brand-dark); font-size: .8rem; font-weight: 750; }.empty-state { grid-column: 1 / -1; padding: 42px 24px; border: 1px dashed #cfc5b6; border-radius: 18px; color: var(--muted); text-align: center; }
        .form-card { padding: 30px; box-shadow: 0 18px 48px rgba(47, 38, 26, .07); }.form-card + .form-card { margin-top: 20px; }.form-card h1 { margin: 6px 0 8px; font-size: 2rem; letter-spacing: -.05em; }.form-card > p { margin: 0 0 25px; color: var(--muted); }.field { display: grid; gap: 7px; margin-bottom: 16px; }.field label { font-size: .86rem; font-weight: 750; } input, textarea { width: 100%; padding: 12px 13px; border: 1px solid #d7d0c5; border-radius: 10px; background: #fff; color: var(--ink); font: inherit; outline: none; } textarea { min-height: 80px; resize: vertical; } input:focus, textarea:focus { border-color: var(--brand); box-shadow: 0 0 0 4px rgba(244, 81, 61, .12); }.form-card .button { margin-bottom: 8px; }.form-footer { margin: 20px 0 0; color: var(--muted); font-size: .92rem; }.form-footer a { color: var(--brand-dark); font-weight: 750; }.comment-list { list-style: none; margin: 16px 0; padding: 0; display: grid; gap: 10px; }.comment { padding: 12px 14px; background: var(--canvas); border-radius: 10px; }.comment-body { margin: 0 0 4px; }.comment-meta { margin: 0; color: var(--muted); font-size: .82rem; }.comment-form { margin-top: 8px; }
        .site-footer { width: min(1120px, calc(100% - 40px)); margin: 0 auto; padding: 24px 0 34px; color: var(--muted); font-size: .82rem; border-top: 1px solid var(--line); } @media (max-width: 680px) { .site-header { padding: 16px 0; }.nav { gap: 12px; }.nav a:first-child { display: none; }.feature-grid, .post-grid { grid-template-columns: 1fr; }.hero { padding-top: 40px; }.page-heading { align-items: start; flex-direction: column; }.page, .page-narrow { width: min(100% - 28px, 1120px); } }
    </style>
</head>
<body>
    <header class="site-header" id="__larust_spa_header"><a class="brand" href="/"><span class="brand-mark">&gt;_</span><span>larust</span></a><nav class="nav"><a class="{{ if nav_active == "home" { "nav-link is-active" } else { "nav-link" } }}" href="/">Home</a><a class="{{ if nav_active == "posts" { "nav-link is-active" } else { "nav-link" } }}" href="/posts">Posts</a>@if(is_authenticated)<form method="POST" action="/logout">@csrf<button class="logout-button" type="submit">Log out</button></form> <a class="{{ if nav_active == "create" { "nav-cta is-active" } else { "nav-cta" } }}" href="/posts/create">New Post</a>@else <a class="{{ if nav_active == "login" { "nav-link is-active" } else { "nav-link" } }}" href="/login">Log in</a> <a class="nav-cta" href="/register">Start building</a>@endif <button class="theme-toggle" type="button" aria-label="Toggle color theme"><svg class="sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg><svg class="moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg></button></nav></header>
    @spa
    @yield('content')
    @endspa
    <footer class="site-footer">Larust by <a href="https://wallabydesigns.com" class="wallaby" target="_blank" rel="noopener noreferrer">Wallaby Designs</a> · familiar conventions, Rust certainty.</footer>
    <script>(function(){function s(){var b=document.querySelector('.theme-toggle');if(!b)return;b.setAttribute('aria-label',document.documentElement.dataset.theme==='dark'?'Use light theme':'Use dark theme')}document.addEventListener('click',function(e){if(!e.target.closest('.theme-toggle'))return;var t=document.documentElement.dataset.theme==='dark'?'light':'dark';document.documentElement.dataset.theme=t;try{localStorage.setItem('larust-theme',t)}catch(_){}s()});document.addEventListener('larust:spa:navigated',s);s()})()</script>
    @larustscripts
</body>
</html>
"##;

/// One example key, deliberately not wired into any generated template -
/// `t("messages.welcome")` in a `{{ }}` expression is enough to use it
/// (see `docs/digging-deeper/localization.md`); forcing every scaffolded
/// page through a translation call would add friction to the common
/// single-locale case this file exists to demonstrate leaving, not adopt.
const LANG_EN_JSON: &str = r#"{
    "messages.welcome": "Welcome to :app!"
}
"#;

const WELCOME_BLADE_XR: &str = r#"@extends('layouts.app')

@section('content')
<main class="page">
    <section class="hero"><h1 class="display">Ship the pleasant parts.</h1><p class="lead">Larust brings the clarity of Laravel conventions to a fast, strongly typed Rust foundation.</p><div class="hero-actions"><a class="button" href="/register">Start building <span>&rarr;</span></a><a class="button button-secondary" href="/posts">Explore Posts</a></div></section>
    <section class="feature-grid"><article class="feature"><strong>Conventions first</strong><p>Routes, controllers, requests, and views find their natural home.</p></article><article class="feature"><strong>Rust where it counts</strong><p>Lean on compile-time confidence without losing momentum.</p></article><article class="feature"><strong>Built to make things</strong><p>Start with a small journal and grow toward the product in your head.</p></article></section>
</main>
@endsection
"#;

const POSTS_INDEX_BLADE_XR: &str = r#"@extends('layouts.app')

@section('content')
<main class="page">
    <div class="page-heading"><div><h1 class="page-title">Small notes. Fast ideas.</h1></div><a class="button" href="/posts/create">Write a post <span>&rarr;</span></a></div>
    @if(!flash_success.is_empty())<p class="flash-success">{{ flash_success }}</p>@endif
    <section class="post-grid">
    @foreach(post in posts)
        <article class="post-card"><div><h2 class="post-title">{{ post.title }}</h2><p class="post-meta">A fresh note from your application.</p></div><div class="tag-line"># larust</div></article>
    @endforeach
    </section>
</main>
@endsection
"#;

const POSTS_INDEX_BLADE_XR_WITH_AUTH: &str = r#"@extends('layouts.app')

@section('content')
<main class="page">
    <div class="page-heading"><div><h1 class="page-title">Small notes. Fast ideas.</h1></div><a class="button" href="/posts/create">Write a post <span>&rarr;</span></a></div>
    @if(!flash_success.is_empty())<p class="flash-success">{{ flash_success }}</p>@endif
    <section class="post-grid">
    @foreach(post in posts)
        <article class="post-card"><div><h2 class="post-title">{{ post.title }}</h2><p class="post-meta">By {{ post.author_name }}</p></div><div class="tag-line"># larust</div></article>
    @endforeach
    </section>
</main>
@endsection
"#;

const POSTS_CREATE_BLADE_XR: &str = r#"@extends('layouts.app')

@section('content')
<main class="page-narrow"><section class="form-card"><h1>Put the idea on the page.</h1><p>Write something worth returning to.</p><form method="POST" action="/posts">
        @csrf
        <div class="field"><label for="title">Title</label><input id="title" type="text" name="title" placeholder="An excellent thought" required></div>
        <button class="button" type="submit">Publish post <span>&rarr;</span></button>
    </form><p class="form-footer"><a href="/posts">&larr; Back to the journal</a></p></section></main>
@endsection
"#;

// Auth-only - see `scaffold()`'s own `if auth { ... }` block. The comments
// section here is the one piece of this starter app that demonstrates
// `larust_support::reverb`: every *other* open tab on this exact page
// sees a new comment the instant `CommentController::store` broadcasts
// it, with nobody in that tab doing anything - the one thing neither an
// ordinary form POST nor a `@wire(...)` reactive component can do (both
// are request/response, scoped to the one visitor who acted).
const POSTS_SHOW_BLADE_XR_WITH_AUTH: &str = r#"@extends('layouts.app')

@section('content')
<main class="page-narrow">
    <p class="form-footer"><a href="/posts">&larr; Back to posts</a></p>
    <section class="form-card">
        <h1>{{ title }}</h1>
        <p class="post-meta">By {{ author_name }}</p>
    </section>

    <section class="form-card">
        <h2>Comments</h2>
        <ul class="comment-list" id="comment-list">
            @foreach(comment in comments)
                <li class="comment"><p class="comment-body">{{ comment.body }}</p><p class="comment-meta">&mdash; {{ comment.author_name }}</p></li>
            @endforeach
        </ul>

        @if(is_authenticated)
            <form method="POST" action="/posts/{{ id }}/comments" class="comment-form">
                @csrf
                <div class="field"><label for="body">Add a comment</label><textarea id="body" name="body" required></textarea></div>
                <button class="button" type="submit">Post comment</button>
            </form>
        @else
            <p class="form-footer"><a href="/login">Log in</a> to leave a comment.</p>
        @endif
    </section>
</main>

<script src="/__larust_reverb/runtime.js"></script>
<script>
    // Real-time comments: every *other* open tab on this same post's page
    // appends a new comment the instant `CommentController::store`
    // broadcasts it. The tab that actually submitted the form gets here
    // the ordinary way (redirect + a fresh render of the list above);
    // this listener is purely for everyone else.
    LarustReverb.channel('posts.{{ id }}.comments').listen('CommentCreated', function (comment) {
        var list = document.getElementById('comment-list');
        var item = document.createElement('li');
        item.className = 'comment';
        var body = document.createElement('p');
        body.className = 'comment-body';
        body.textContent = comment.body;
        var meta = document.createElement('p');
        meta.className = 'comment-meta';
        meta.textContent = '- ' + comment.author;
        item.appendChild(body);
        item.appendChild(meta);
        list.appendChild(item);
    });
</script>
@endsection
"#;

const CONTROLLERS_MOD_RS_WITH_AUTH: &str = r#"pub mod auth_controller;
pub mod comment_controller;
pub mod post_controller;

pub use auth_controller::AuthController;
pub use comment_controller::CommentController;
pub use post_controller::PostController;
"#;

const AUTH_CONTROLLER_RS: &str = r#"use larust_http::session::Session;
use larust_support::axum::response::IntoResponse;
use larust_support::view;
use larust_support::AppError;

use crate::models::{NewUser, User};
use crate::requests::{LoginRequest, RegisterRequest};

pub struct AuthController;

impl AuthController {
    pub async fn show_register(session: Session) -> Result<impl IntoResponse, AppError> {
        let csrf_token = larust_http::csrf::token(&session).await;
        let flash_error = flash_error(&session).await;
        let is_authenticated = false;
        let nav_active = "register";
        Ok(view!("auth.register", { csrf_token, flash_error, is_authenticated, nav_active }))
    }

    pub async fn register(
        session: Session,
        request: RegisterRequest,
    ) -> Result<impl IntoResponse, AppError> {
        let validated = request.validated();

        let existing = User::query()
            .where_eq(User::EMAIL, validated.email.clone())
            .first()
            .await?;
        if existing.is_some() {
            return Ok(larust_support::redirect()
                .route("register")?
                .with(&session, "error", "That email is already registered.")
                .await);
        }

        let password_hash = larust_support::auth::hash_password(&validated.password)?;
        let user = User::create(NewUser {
            name: validated.name,
            email: validated.email,
            password_hash,
        })
        .await?;

        larust_support::auth::login(&session, &user).await?;
        Ok(larust_support::redirect()
            .route("posts.index")?
            .with(
                &session,
                "success",
                format!("Welcome, {} ({})!", user.name, user.email),
            )
            .await)
    }

    pub async fn show_login(session: Session) -> Result<impl IntoResponse, AppError> {
        let csrf_token = larust_http::csrf::token(&session).await;
        let flash_error = flash_error(&session).await;
        let is_authenticated = false;
        let nav_active = "login";
        Ok(view!("auth.login", { csrf_token, flash_error, is_authenticated, nav_active }))
    }

    pub async fn login(
        session: Session,
        request: LoginRequest,
    ) -> Result<impl IntoResponse, AppError> {
        let validated = request.validated();

        let user = User::query()
            .where_eq(User::EMAIL, validated.email.clone())
            .first()
            .await?;

        // Always run the (deliberately expensive) password verification,
        // even when no user was found, against a fixed dummy hash - a
        // nonexistent email would otherwise short-circuit here and be
        // distinguishable from a real one by response latency alone, even
        // though the error message shown to the client is identical
        // either way (see the `!authenticated` branch below).
        let authenticated = match &user {
            Some(user) => {
                larust_support::auth::verify_password(&user.password_hash, &validated.password)?
            }
            None => {
                larust_support::auth::verify_password(dummy_password_hash(), &validated.password)?;
                false
            }
        };

        if !authenticated {
            return Ok(larust_support::redirect()
                .route("login")?
                .with(
                    &session,
                    "error",
                    "Those credentials don't match our records.",
                )
                .await);
        }

        let user = user.expect("checked above");
        larust_support::auth::login(&session, &user).await?;
        Ok(larust_support::redirect()
            .route("posts.index")?
            .with(&session, "success", format!("Welcome back, {}!", user.name))
            .await)
    }

    pub async fn logout(session: Session) -> Result<impl IntoResponse, AppError> {
        larust_support::auth::logout(&session).await?;
        larust_support::redirect().to("/")
    }
}

async fn flash_error(session: &Session) -> String {
    larust_http::session::take::<String>(session, "error")
        .await
        .ok()
        .flatten()
        .unwrap_or_default()
}

/// A fixed Argon2 hash nothing will ever match, computed once per process
/// (not per request) - used only to give the "no such user" login path the
/// same Argon2 CPU cost as a real password check.
fn dummy_password_hash() -> &'static str {
    static HASH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    HASH.get_or_init(|| {
        larust_support::auth::hash_password("not-a-real-account-timing-equalizer")
            .expect("hashing a fixed literal string never fails")
    })
}
"#;

const AUTH_REGISTER_BLADE_XR: &str = r#"@extends('layouts.app')

@section('content')
<main class="page-narrow"><section class="form-card"><h1>Build your next thing.</h1><p>One account, a clean place to begin.</p>
    @if(!flash_error.is_empty())<p class="flash-error">{{ flash_error }}</p>@endif
    <form method="POST" action="/register">
        @csrf
        <div class="field"><label for="name">Your name</label><input id="name" type="text" name="name" placeholder="Ada Lovelace" required></div>
        <div class="field"><label for="email">Email address</label><input id="email" type="email" name="email" placeholder="ada@example.com" required></div>
        <div class="field"><label for="password">Password</label><input id="password" type="password" name="password" placeholder="At least 8 characters" required></div>
        <div class="field"><label for="password-confirmation">Confirm password</label><input id="password-confirmation" type="password" name="password_confirmation" placeholder="Repeat your password" required></div>
        <button class="button" type="submit">Create account <span>&rarr;</span></button>
    </form>
    <p class="form-footer">Already have an account? <a href="/login">Log in</a></p></section></main>
@endsection
"#;

const AUTH_LOGIN_BLADE_XR: &str = r#"@extends('layouts.app')

@section('content')
<main class="page-narrow"><section class="form-card"><h1>Pick up where you left off.</h1><p>Your journal is ready when you are.</p>
    @if(!flash_error.is_empty())<p class="flash-error">{{ flash_error }}</p>@endif
    <form method="POST" action="/login">
        @csrf
        <div class="field"><label for="email">Email address</label><input id="email" type="email" name="email" placeholder="ada@example.com" required></div>
        <div class="field"><label for="password">Password</label><input id="password" type="password" name="password" placeholder="Your password" required></div>
        <button class="button" type="submit">Log in <span>&rarr;</span></button>
    </form>
    <p class="form-footer">New here? <a href="/register">Create an account</a></p></section></main>
@endsection
"#;

const CREATE_USERS_TABLE_SQL: &str = "CREATE TABLE users (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    name TEXT NOT NULL,\n    email TEXT NOT NULL UNIQUE,\n    password_hash TEXT NOT NULL\n);\n";

const REQUESTS_MOD_RS: &str =
    "pub mod store_post_request;\n\npub use store_post_request::StorePostRequest;\n";

const REQUESTS_MOD_RS_WITH_AUTH: &str = r#"pub mod login_request;
pub mod register_request;
pub mod store_comment_request;
pub mod store_post_request;

pub use login_request::LoginRequest;
pub use register_request::RegisterRequest;
pub use store_comment_request::StoreCommentRequest;
pub use store_post_request::StorePostRequest;
"#;

const STORE_POST_REQUEST_RS: &str = r#"use larust_support::FormRequest;

#[derive(FormRequest)]
pub struct StorePostRequest {
    #[validate(required, length(max = 255))]
    pub title: String,
}
"#;

const REGISTER_REQUEST_RS: &str = r#"use larust_support::FormRequest;

#[derive(FormRequest)]
pub struct RegisterRequest {
    #[validate(required, length(max = 255))]
    pub name: String,
    #[validate(required, email)]
    pub email: String,
    #[validate(required, length(min = 8), confirmed)]
    pub password: String,
}
"#;

const LOGIN_REQUEST_RS: &str = r#"use larust_support::FormRequest;

#[derive(FormRequest)]
pub struct LoginRequest {
    #[validate(required, email)]
    pub email: String,
    #[validate(required)]
    pub password: String,
}
"#;

const MODELS_MOD_RS: &str = "pub mod post;\n\npub use post::{NewPost, Post};\n";

const MODELS_MOD_RS_WITH_AUTH: &str = r#"pub mod comment;
pub mod post;
pub mod user;

pub use comment::{Comment, NewComment};
pub use post::{NewPost, Post};
pub use user::{NewUser, User};
"#;

const USER_MODEL_RS: &str = r#"use larust_support::orm::sqlx;
use larust_support::{AppError, Model};

use crate::models::Post;

#[derive(Model, sqlx::FromRow)]
#[table("users")]
#[has_many(Post, foreign_key = "user_id")]
pub struct User {
    #[primary_key]
    pub id: i64,
    pub name: String,
    pub email: String,
    pub password_hash: String,
}

impl larust_support::auth::Authenticatable for User {
    fn auth_id(&self) -> i64 {
        self.id
    }

    async fn find_for_auth(id: i64) -> Result<Option<Self>, AppError> {
        Self::find(id).await
    }
}
"#;

// Empty (no middleware generated yet) but still declared as a real module
// in `main.rs` from the start - `xr make:middleware` only appends to this
// file, it never creates the module wiring itself, so without this a
// generated middleware file would sit on disk uncompiled and unverified.
const MIDDLEWARE_MOD_RS: &str =
    "// Middleware generated by `xr make:middleware` is registered here.\n";

// Same shape as `MIDDLEWARE_MOD_RS` above, and for the same reason. Written
// unconditionally regardless of `--auth`: plain `xr new` has no `User`
// model either way, so there's nothing a policy could be written against
// at scaffold time - only a later `xr make:policy` call, once a `User`
// model exists, ever puts real content here.
const POLICIES_MOD_RS: &str = "// Policies generated by `xr make:policy` are registered here.\n";

// Empty (no `xr make:mail` generator exists yet - v1 is a real, usable
// `Mailable` trait + sender, hand-authored per email like `app/Policies`
// was before its generator landed) but still declared as a real module
// from the start, same reasoning as `MIDDLEWARE_MOD_RS` above.
const MAIL_MOD_RS: &str =
    "// Mailable types live here - see docs/ARCHITECTURE.md's \"Mail\" section.\n\
     // mail().to(...).send(...) delivers immediately; .queue(...) defers\n\
     // delivery - see the \"Job types\" note in app/Jobs/mod.rs.\n";

// Same shape as `MAIL_MOD_RS` above - no `xr make:job`/`xr make:event`
// generator yet, but a real, declared module from day one.
const JOBS_MOD_RS: &str = "// Job types (`larust_support::queue::Job`) live here - register each\n\
     // with `main.rs`'s `queue:work` branch so `xr queue:work` can run it.\n\
     // See docs/ARCHITECTURE.md's \"Events + Jobs/Queues\" section.\n\
     //\n\
     // main.rs's queue:work branch already registers the framework-owned\n\
     // larust_support::mail::MailJob by default, so Mail::queue(...)\n\
     // (app/Mail/mod.rs) works out of the box - remove that line if your\n\
     // app never uses .queue().\n";

// Laravel's own `app/Console/Commands/` convention, verbatim - unlike its
// `Jobs`/`Events` neighbors above, this one does have a generator
// (`xr make:command`), since a named `Command` is a single, uniformly-
// shaped file (see `MAKE_COMMAND_TEMPLATE`).
const COMMANDS_MOD_RS: &str = "// Command types (`larust_support::console::Command`) live here -\n\
     // register each with `routes/console.rs`'s `commands()` function so\n\
     // `xr <name>` can run it. `xr make:command` generates a new one.\n";
const EVENTS_MOD_RS: &str = "// Event types (any plain `Clone` struct) live here - register\n\
     // listeners for them in `main.rs` via `larust_support::event::listeners()`.\n\
     // See docs/ARCHITECTURE.md's \"Events + Jobs/Queues\" section.\n";

// Same shape as `MAIL_MOD_RS`/`JOBS_MOD_RS` above - no `xr make:wire`
// generator yet, but a real, declared module from day one. `main.rs`'s
// `larust_support::wire::components()` call is where each type here gets
// registered under its own `WireComponent::NAME`.
const WIRE_MOD_RS: &str = "// Reactive components (`larust_support::wire::WireComponent`) live\n\
     // here - register each with `main.rs`'s `larust_support::wire::components()`\n\
     // call so `@wire('name', ...)` in a template can mount it. See\n\
     // docs/ARCHITECTURE.md's \"Reactive components\" section.\n";

const FACTORIES_MOD_RS: &str = "// Model factories (`larust_support::orm::Factory`) live here -\n\
     // `xr make:factory Post` generates a new one. Used from tests\n\
     // (`PostFactory::new().create().await?`) and from `database/seeders`.\n";

// No `Seeder` trait - just a plain async function, same reasoning as
// `MAIL_MOD_RS`'s own "real, usable shape from the start, no generator
// needed for a one-function module" comment. `xr db:seed` (and
// `migrate:fresh --seed`) call this directly.
const SEEDERS_MOD_RS: &str = "// Populates the database with starter/demo data - called by\n\
     // `xr db:seed` and `xr migrate:fresh --seed`. Add whatever this app\n\
     // needs here, e.g.:\n\
     // PostFactory::new().create_many(10).await?;\n\
     pub async fn run() -> Result<(), larust_core::AppError> {\n    \
         Ok(())\n\
     }\n";

const POST_MODEL_RS: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;

#[derive(Model, sqlx::FromRow)]
#[table("posts")]
pub struct Post {
    #[primary_key]
    pub id: i64,
    pub title: String,
}
"#;

const POST_MODEL_RS_WITH_AUTH: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;

use crate::models::{Comment, User};

#[derive(Model, sqlx::FromRow)]
#[table("posts")]
#[belongs_to(User, foreign_key = "user_id")]
#[has_many(Comment, foreign_key = "post_id")]
pub struct Post {
    #[primary_key]
    pub id: i64,
    pub user_id: i64,
    pub title: String,
}
"#;

const CREATE_POSTS_TABLE_SQL: &str = "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    title TEXT NOT NULL\n);\n";

const CREATE_POSTS_TABLE_SQL_WITH_AUTH: &str = "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    user_id INTEGER NOT NULL REFERENCES users(id),\n    title TEXT NOT NULL\n);\n";

// Auth-only (comments need a `User` to attribute authorship to - see
// `scaffold()`'s own `if auth { ... }` block) - `0003`, after `0002`'s
// `users` table since this one references it.
const CREATE_COMMENTS_TABLE_SQL: &str = "CREATE TABLE comments (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    post_id INTEGER NOT NULL REFERENCES posts(id),\n    user_id INTEGER NOT NULL REFERENCES users(id),\n    body TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_comments_post_id ON comments(post_id);\n";

// `main.rs` is pure bootstrap now - CLI-subcommand dispatch, DB connect,
// session wiring, `.serve()` - identical regardless of `--auth`, since
// every auth-specific difference (imports, middleware groups, the route
// table itself) lives in `routes/web.rs` instead (see
// `ROUTES_WEB_HEADER`/`ROUTES_WEB_HEADER_WITH_AUTH` below). One shared
// constant, not two, avoids the "two independent strings can silently
// drift out of sync" problem the previous two-constant design had.
const MAIN_RS_HEADER: &str = r#"use larust_http::Router;

#[tokio::main]
async fn main() -> Result<(), larust_core::AppError> {
    let command = std::env::args().nth(1);

    if command.as_deref() == Some("migrate") {
        __CRATE__::connect_database().await?;
        larust_support::orm::migrate(&__CRATE__::paths().migrations()).await?;
        return Ok(());
    }

    if command.as_deref() == Some("migrate:fresh") {
        __CRATE__::connect_database().await?;
        larust_support::orm::migrate_fresh(&__CRATE__::paths().migrations()).await?;
        if std::env::args().any(|arg| arg == "--seed") {
            __CRATE__::seeders::run().await?;
        }
        return Ok(());
    }

    if command.as_deref() == Some("db:seed") {
        __CRATE__::connect_database().await?;
        __CRATE__::seeders::run().await?;
        return Ok(());
    }

    if command.as_deref() == Some("queue:work") {
        __CRATE__::connect_database().await?;
        // MailJob is the framework's own job type for Mail::queue(...) -
        // registered by default so queued mail works out of the box;
        // remove this line if your app never calls .queue().
        let registry = larust_support::queue::JobRegistry::new()
            .register::<larust_support::mail::MailJob>();
        // Register your app's own Job types here, e.g.:
        // let registry = registry.register::<__CRATE__::jobs::MyJob>();
        return larust_support::queue::work(registry).await;
    }

    if command.as_deref() == Some("schedule:work") {
        __CRATE__::connect_database().await?;
        return larust_support::schedule::work(__CRATE__::routes::console::schedule()).await;
    }

    __DB_MAIN_RS_SNIPPET__if command.as_deref() == Some("route:list") {
        let app = __CRATE__::application()?;
        let route = __CRATE__::router(&app);
        print_routes(&route);
        return Ok(());
    }

    if command.as_deref() == Some("command:list") {
        for info in __CRATE__::routes::console::commands().list() {
            println!("{:<24} {}", info.name, info.description);
        }
        return Ok(());
    }

    // Anything else typed after `xr` (or `cargo run --`) that isn't one of
    // the fixed subcommands above is looked up against your own
    // `routes/console.rs::commands()` registry - `xr make:command` scaffolds
    // a new one. A name matching neither is a loud, immediate error rather
    // than silently falling through to `serve()` below - a typo'd
    // subcommand accidentally starting the web server instead of failing
    // is exactly the kind of silent gap this framework avoids elsewhere.
    if let Some(name) = command.as_deref() {
        // App-defined commands often query models, so they need the same
        // database initialization the built-in database-backed commands do.
        __CRATE__::connect_database().await?;
        let args: Vec<String> = std::env::args().skip(2).collect();
        if __CRATE__::routes::console::commands()
            .dispatch(name, &args)
            .await?
        {
            return Ok(());
        }
        eprintln!("error: unknown command {name:?} (see `command:list`)");
        std::process::exit(1);
    }

    __CRATE__::serve().await
}
"#;

const MAIN_RS_TAIL: &str = r#"
fn print_routes(route: &Router) {
    for info in route.routes() {
        println!(
            "{:<7} {:<24} {}",
            info.method,
            info.path,
            info.name.as_deref().unwrap_or("")
        );
    }
}
"#;

// Spliced into `MAIN_RS_HEADER` at the `__DB_MAIN_RS_SNIPPET__` token, only
// when `"db"` was selected (see `scaffold()`'s `resolved_support_features`)
// - the same "presence/absence of a fixed snippet at generation time"
// mechanism `ROUTES_WEB_HEADER` vs. `ROUTES_WEB_HEADER_WITH_AUTH` already
// establishes for `--auth`, not `#[cfg]` (the generated app has no Cargo
// `db` feature of its own to gate on - `larust-support`'s `db` feature,
// baked into its dependency line at scaffold time, is the only toggle).
// Every call here goes through `larust_support::db::...`, never a bare
// `serde_json::...` path, so this needs no new direct Cargo dependency on
// the generated app's own `Cargo.toml`.
const DB_MAIN_RS_SNIPPET: &str = r#"if command.as_deref() == Some("db:list") {
        larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
        for key in larust_support::db::keys().await? {
            println!("{key}");
        }
        return Ok(());
    }

    if command.as_deref() == Some("db:get") {
        larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
        let key = std::env::args().nth(2).expect("usage: xr db:get <key>");
        match larust_support::db::get_raw(&key).await? {
            Some(value) => println!("{value}"),
            None => println!("(no value for {key})"),
        }
        return Ok(());
    }

    if command.as_deref() == Some("db:put") {
        larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
        let key = std::env::args().nth(2).expect("usage: xr db:put <key> <value>");
        let raw = std::env::args().nth(3).expect("usage: xr db:put <key> <value>");
        larust_support::db::put_raw(&key, larust_support::db::parse_cli_value(&raw)).await?;
        return Ok(());
    }

    if command.as_deref() == Some("db:forget") {
        larust_support::db::connect(&__CRATE__::paths().join("database/db.redb")).await?;
        let key = std::env::args().nth(2).expect("usage: xr db:forget <key>");
        larust_support::db::forget(&key).await?;
        return Ok(());
    }

    "#;

// Spliced at `__DB_SERVE_SNIPPET__` in `lib.rs`'s `serve()`, right before
// the `.with_sessions(...)` call - every `if command == Some("db:...")` arm
// above (in `main.rs`) connects the store itself before returning early,
// but the dashboard route (`DbPlugin`, registered in `routes/web.rs`) is
// reached from `serve()`'s path, which otherwise never calls
// `larust_support::db::connect()` at all. A real bug caught by this crate's
// own live sanity check, not a hypothetical: without this, every request
// to `/__larust_db` 500s with "embedded db not connected", every single
// time, since the serving process itself never touches the CLI-only
// connect calls above.
const DB_SERVE_SNIPPET: &str =
    "larust_support::db::connect(&paths().join(\"database/db.redb\")).await?;\n    ";

/// `crate_ident` is the app's library crate name as `use`-able Rust syntax
/// (see [`crate_ident`]) - `main.rs` is a separate crate from `lib.rs`
/// even within one package, so it reaches `connect_database`/`application`/
/// `router`/`serve`/`routes`/etc. via `use {crate_ident}::...`, not a `mod`
/// declaration of its own. `has_db` splices in [`DB_MAIN_RS_SNIPPET`] (see
/// its own doc comment) only when the `db` optional feature was selected -
/// [`DB_SERVE_SNIPPET`] is [`lib_rs`]'s concern, not this function's.
fn main_rs(crate_ident: &str, has_db: bool) -> String {
    let db_main_snippet = if has_db { DB_MAIN_RS_SNIPPET } else { "" };
    // `__DB_MAIN_RS_SNIPPET__` first, `__CRATE__` second - the snippet
    // itself now contains its own `__CRATE__` token (for `paths()`), which
    // would never get substituted if the crate-name pass ran first and
    // only saw the *outer* template, before the snippet was ever spliced
    // in. A real bug, caught by generating a real app with `--features
    // db` and reading the output rather than assumed from the code alone.
    format!("{MAIN_RS_HEADER}{MAIN_RS_TAIL}")
        .replace("__DB_MAIN_RS_SNIPPET__", db_main_snippet)
        .replace("__CRATE__", crate_ident)
}

/// The app modules (`controllers`/`middleware`/`models`/`policies`/
/// `requests`/`mail`/`jobs`/`events`), declared once in `lib.rs` rather
/// than duplicated between `main.rs` and `tests/*.rs` - giving the
/// generated app a library target is what lets `tests/*.rs` (compiled as
/// its own separate crate) reach them at all via `use {crate_ident}::...`,
/// the same way `main.rs` now does. Also carries the shared server-
/// bootstrap functions (`connect_database`/`port`/`application`/`router`/
/// `serve`) - split out of `main.rs` so an embedded host (a Tauri desktop
/// shell, when `xr new --tauri`/`xr add tauri` scaffolds `src-tauri/`) can
/// call `serve()` from its own binary without duplicating the bootstrap
/// sequence or pulling in `main.rs`'s CLI-subcommand dispatch.
const LIB_RS: &str = r#"#[path = "../config/mod.rs"]
pub mod config;
#[path = "../app/Http/Controllers/mod.rs"]
pub mod controllers;
#[path = "../app/Http/Middleware/mod.rs"]
pub mod middleware;
#[path = "../app/Mail/mod.rs"]
pub mod mail;
#[path = "../app/Jobs/mod.rs"]
pub mod jobs;
#[path = "../app/Events/mod.rs"]
pub mod events;
#[path = "../app/Console/Commands/mod.rs"]
pub mod commands;
#[path = "../app/Wire/mod.rs"]
pub mod wire_components;
#[path = "../app/Models/mod.rs"]
pub mod models;
#[path = "../app/Policies/mod.rs"]
pub mod policies;
#[path = "../app/Http/Requests/mod.rs"]
pub mod requests;
#[path = "../database/factories/mod.rs"]
pub mod factories;
#[path = "../database/seeders/mod.rs"]
pub mod seeders;
#[path = "../routes/mod.rs"]
pub mod routes;

/// This app's own root directory, independent of the process's current
/// working directory - `env!("CARGO_MANIFEST_DIR")` is a compile-time
/// constant Cargo sets per-*package*, so it resolves identically whether
/// read from this library target or from `main.rs`'s separate binary
/// target. Threading this through `.env`/migrations/database resolution
/// (below, and in `main.rs`'s own CLI dispatch) is what makes `cargo run
/// -p __CRATE__` from the *workspace* root behave identically to `cd`-ing
/// into this app's own directory first - `Application::new()`/a bare
/// relative `Path::new("database/migrations")` would each silently
/// resolve against the wrong directory otherwise.
///
/// `LARUST_APP_ROOT` (a real environment variable - never read from
/// `.env`, since `.env`'s own location is exactly what this decides)
/// overrides that compile-time default, the same `xr upgrade`/
/// `LARUST_CHECKOUT_ROOT` pattern: without it, a binary built on one
/// machine and *copied* elsewhere to actually run - rather than built
/// in place there, the way `xr deploy` does it - would still look for
/// `.env`/`storage/`/`database/` at the build machine's own path. Set
/// it (e.g. a systemd unit's own `Environment=LARUST_APP_ROOT=...`
/// line) for a minimal deployment that's nothing but the compiled
/// binary and an `.env` file next to wherever it's actually run from.
pub fn paths() -> larust_core::AppPaths {
    larust_core::AppPaths::new(larust_core::resolve_app_root(env!("CARGO_MANIFEST_DIR")))
}

pub async fn connect_database() -> Result<(), larust_core::AppError> {
    larust_support::orm::connect(&database_url()?).await
}

/// Resolves `config/database.rs`'s active connection to the URL
/// `larust_support::orm::connect()` needs - with one extra step
/// `ConnectionConfig::to_url()` itself can't do: a *relative* sqlite path
/// (`config/database.rs`'s own default, `database/database.sqlite`) needs
/// resolving against this app's own root ([`paths`]), not the process's
/// current working directory, so `xr dev`/`cargo run` behave identically
/// regardless of where they're invoked from. An absolute path or
/// `:memory:` is left untouched.
fn database_url() -> Result<String, larust_core::AppError> {
    let url = config::database::config().default_connection_url()?;
    let relative_sqlite_path = url
        .strip_prefix("sqlite://")
        .filter(|path| !path.starts_with('/') && !path.starts_with(":memory:"))
        .map(str::to_string);

    Ok(match relative_sqlite_path {
        Some(relative) => {
            let path = paths().join(relative);
            format!("sqlite:///{}", path.to_string_lossy().replace('\\', "/"))
        }
        None => url,
    })
}

/// The app's configured HTTP port (`APP_PORT`, default 34187) - reads the
/// raw `config/app.rs` JSON directly rather than `larust_core::config()`,
/// since the latter panics until `Application::new()`/`at_root()` has
/// run, and an embedded host needs this *before* it can call `serve()`
/// (typically on its own background thread) to know what URL to point
/// its webview at.
pub fn port() -> u16 {
    config::app::config()["app_port"]
        .as_u64()
        .and_then(|value| u16::try_from(value).ok())
        .unwrap_or(34187)
}

/// Loads config and registers error pages - the first half of `serve()`,
/// split out so `route:list` can build just enough to print the route
/// table without connecting the database or attaching sessions.
/// `at_root`, not `new()` - see [`paths`]'s own doc comment for why a
/// real binary should always prefer it. Resolves the root the identical
/// `LARUST_APP_ROOT`-overridable way `paths()` itself does - this is
/// the function that actually constructs the live, serving
/// `Application`, so it's exactly the one call site where getting this
/// wrong would silently defeat the whole point of that override.
pub fn application() -> Result<larust_core::Application, larust_core::AppError> {
    let app = larust_core::Application::at_root(
        larust_core::resolve_app_root(env!("CARGO_MANIFEST_DIR")),
        config::app::config,
    )?;
    // Renders once here, not per request - drop `resources/views/errors/
    // 404.blade.xr`/`500.blade.xr` into your own app to override either;
    // with no file there, this compiles to Larust's own built-in default.
    Ok(app.with_error_pages(larust_core::ErrorPages {
        not_found: larust_support::error_view!("404"),
        internal: larust_support::error_view!("500"),
    }))
}

/// The merged `web` + `api` route table - no sessions attached yet, since
/// `route:list` needs this much without a database. `.merge`, not
/// `.group` - keeps `routes::api`'s own middleware stack independent of
/// `routes::web`'s (CSRF among others); see `Router::merge`'s own doc
/// comment.
pub fn router(app: &larust_core::Application) -> larust_http::Router {
    larust_support::wire::components()
        // Register your app's own reactive components here, e.g.:
        // .register::<crate::wire_components::MyComponent>()
        .publish();

    routes::web::routes().merge(&app.config().api_prefix, routes::api::routes())
}

/// Connects the database, attaches sessions, and serves - the shared core
/// both `main.rs`'s default (no-subcommand) path and any embedded host
/// need. Does NOT handle the `migrate`/`db:*`/`queue:work`/`schedule:work`/
/// `route:list` CLI subcommands - those stay in `main.rs`, CLI-only.
pub async fn serve() -> Result<(), larust_core::AppError> {
    let app = application()?;
    let route = router(&app);

    connect_database().await?;
    __DB_SERVE_SNIPPET__let route = route
        .with_sessions(larust_support::orm::pool()?, app.config().session_secure_cookie)
        .await?;
    app.router(route.into_axum_router()).serve().await
}
"#;

/// `has_db` splices in [`DB_SERVE_SNIPPET`] (see its own doc comment) only
/// when the `db` optional feature was selected - mirrors [`main_rs`]'s
/// identical `__DB_MAIN_RS_SNIPPET__` handling for its own token.
fn lib_rs(has_db: bool) -> String {
    let db_serve_snippet = if has_db { DB_SERVE_SNIPPET } else { "" };
    LIB_RS.replace("__DB_SERVE_SNIPPET__", db_serve_snippet)
}

/// Cargo's own rule for deriving a library crate's `use`-path identifier
/// from a package name: hyphens become underscores, nothing else changes
/// (no case conversion) - needed because `validate_app_name` allows
/// hyphens (`xr new my-app`), but `use my-app::...` isn't valid Rust
/// syntax.
pub(crate) fn crate_ident(app_name: &str) -> String {
    app_name.replace('-', "_")
}

// A real, passing example - not just an empty directory - so `xr new`
// produces a genuinely working test out of the box. Builds its own small
// router for just the one route under test (the same pattern this
// framework's own internal test suites already use, e.g.
// `larust-auth/tests/guard.rs`), rather than trying to replicate the
// route table in `src/main.rs` (which lives outside the library crate
// this file can `use`).
const TESTS_EXAMPLE_RS: &str = r#"use __CRATE__::controllers::PostController;
use larust_http::Route;
use larust_support::axum::http::StatusCode;
use larust_testing::{test_db, TestClient};

#[tokio::test]
async fn posts_index_loads() {
    let pool = test_db(std::path::Path::new("database/migrations"))
        .await
        .unwrap();
    let router = Route::get("/posts", PostController::index)
        .with_sessions(&pool, false)
        .await
        .unwrap()
        .into_axum_router();
    let mut client = TestClient::new(router, &pool);

    client.get("/posts").await.assert_status(StatusCode::OK);
}
"#;

// Mirrors `MAIN_RS_HEADER`'s own "one shared tail" reasoning: `index()` is
// identical regardless of `--auth`, only the route table itself (and its
// imports) differs, so it lives in one shared tail rather than being
// duplicated between two full-file constants.
const ROUTES_WEB_HEADER: &str = r#"use crate::controllers::PostController;
use larust_http::session::Session;
use larust_http::{Route, Router};

pub fn routes() -> Router {
    let route = Route::get("/", index)
        .get("/posts", PostController::index)
        .name("posts.index")
        .get("/posts/create", PostController::create)
        .name("posts.create")
        .get("/posts/{post}", PostController::show)
        .name("posts.show")
        .post("/posts", PostController::store)
        .name("posts.store")
        .plugin(larust_support::wire::WirePlugin)
        .plugin(larust_support::spa::SpaPlugin)
        .plugin(larust_support::image::ImagePlugin);
    __DB_ROUTE_SNIPPET__route
        .middleware(larust_http::axum::middleware::from_fn(
            larust_http::csrf::verify,
        ))
        .middleware(larust_http::axum::middleware::from_fn(
            larust_http::locale::negotiate,
        ))
}
"#;

const ROUTES_WEB_HEADER_WITH_AUTH: &str = r#"use crate::controllers::{AuthController, CommentController, PostController};
use larust_http::session::Session;
use larust_http::{Route, Router};
use larust_support::auth::{redirect_authenticated, require_auth};

pub fn routes() -> Router {
    let route = Route::get("/", index)
        .get("/posts", PostController::index)
        .name("posts.index")
        .get("/posts/{post}", PostController::show)
        .name("posts.show")
        .plugin(larust_support::wire::WirePlugin)
        .plugin(larust_support::spa::SpaPlugin)
        .plugin(larust_support::image::ImagePlugin)
        // Public read (anyone can watch a post's comments live); only
        // *posting* one requires login, gated below inside the
        // `require_auth` group like `posts.store`. Registered before
        // `.with_sessions(...)` runs (in `main.rs`, after this function
        // returns) so `reverb::socket`'s `Session` extractor actually has
        // a session layer to read from.
        .plugin(larust_support::reverb::ReverbPlugin)
        // Creating a post requires login (Laravel's
        // `Route::middleware('auth')->group(...)`) - group-scoped
        // middleware only wraps the routes registered inside this closure,
        // it never affects the read-only routes above.
        .group("", |r: Router| {
            r.middleware(larust_http::axum::middleware::from_fn(require_auth))
                .get("/posts/create", PostController::create)
                .name("posts.create")
                .post("/posts", PostController::store)
                .name("posts.store")
                .post("/posts/{post}/comments", CommentController::store)
                .name("posts.comments.store")
        })
        // The inverse: an already-logged-in user is bounced away from
        // register/login (Laravel's `guest` middleware).
        .group("", |r: Router| {
            r.middleware(larust_http::axum::middleware::from_fn(
                redirect_authenticated,
            ))
            .get("/register", AuthController::show_register)
            .name("register")
            .post("/register", AuthController::register)
            .name("register.store")
            .get("/login", AuthController::show_login)
            .name("login")
            .post("/login", AuthController::login)
            .name("login.store")
        })
        .post("/logout", AuthController::logout)
        .name("logout");
    // CSRF is a web-routes-only concern (it protects cookie-
    // authenticated browser form submissions) - it must never reach
    // `routes/api.rs`'s entries. That isolation comes from
    // `src/main.rs` combining this router with `routes::api::routes()`
    // via `Router::merge` (not `.group`, which deliberately shares a
    // parent's top-level middleware with whatever it registers) - this
    // call itself doesn't need to know or care where in the chain it
    // sits relative to that.
    __DB_ROUTE_SNIPPET__route
        .middleware(larust_http::axum::middleware::from_fn(
            larust_http::csrf::verify,
        ))
        .middleware(larust_http::axum::middleware::from_fn(
            larust_http::locale::negotiate,
        ))
}
"#;

const ROUTES_WEB_TAIL: &str = r#"
async fn index(session: Session) -> Result<impl larust_support::axum::response::IntoResponse, larust_core::AppError> {
    let csrf_token = larust_http::csrf::token(&session).await;
    let is_authenticated = larust_support::auth::check(&session).await?;
    let nav_active = "home";
    Ok(larust_support::view!("welcome", { csrf_token, is_authenticated, nav_active }))
}
"#;

const ROUTES_API_RS: &str = r#"// Mounted under the configured API prefix (`config/app.rs`'s
// `api_prefix`, `"/api"` by default) by `src/lib.rs`'s `router()` function's
// `Router::merge(&app.config().api_prefix, ...)` call, which keeps this
// router's own top-level middleware independent of `routes::web`'s (see
// `Router::merge`'s own doc comment for why that has to be `.merge`, not
// `.group`). Empty of app routes for now - add them here the same way
// `routes/web.rs` does, e.g. `Route::get("/posts", ApiPostController::index)`.
//
// Deliberately does *not* apply `.middleware(csrf::verify)` the way
// `routes/web.rs` does - CSRF protects cookie-authenticated browser form
// submissions specifically, which an API consumer doesn't participate in.
//
// Rate-limited by default (60 requests/minute per caller, keyed by their
// real IP address) - Laravel's own `throttle:60,1` default. Adjust or
// remove via `larust_http::throttle::per(max_requests, window)`.
//
// `locale::negotiate_from_header` is `routes/web.rs`'s session-based
// `locale::negotiate` for a router with no session at all - it reads the
// caller's `Accept-Language` header instead, so any translated error
// message returned from here still resolves through whatever locale the
// caller actually asked for.
use larust_http::Router;

pub fn routes() -> Router {
    Router::new()
        .middleware(larust_http::throttle::per_minute(60))
        .middleware(larust_http::axum::middleware::from_fn(
            larust_http::locale::negotiate_from_header,
        ))
}
"#;

const ROUTES_CONSOLE_RS: &str = r#"// Home for schedule declarations and named CLI commands - `src/main.rs`
// calls `schedule()`/`commands()` and hands the result to
// `larust_support::schedule::work`/`CommandRegistry::dispatch`.
use larust_support::console::CommandRegistry;
use larust_support::schedule::Schedule;

pub fn schedule() -> Schedule {
    Schedule::new()
    // Add your own scheduled tasks here, e.g.:
    // .daily(|| async { ... Ok(()) })
}

pub fn commands() -> CommandRegistry {
    CommandRegistry::new()
    // Register your app's own Command types here, e.g.:
    // .register::<crate::commands::ReportPosts>()
}
"#;

const ROUTES_MOD_RS: &str = "pub mod api;\npub mod console;\npub mod web;\n";

// Spliced into `ROUTES_WEB_HEADER`/`ROUTES_WEB_HEADER_WITH_AUTH` at the
// `__DB_ROUTE_SNIPPET__` token, only when `"db"` was selected - see
// `DB_MAIN_RS_SNIPPET`'s own doc comment for why this is presence/absence
// of a fixed snippet rather than `#[cfg]`. Router-build-time, not
// per-request: read once, when `routes()` runs. `try_config()`, not
// `config()` - the latter panics if `Application::new()` hasn't run yet,
// and `routes()` needs to stay callable standalone (a route-listing test
// building the router directly, with no `Application::new()` call
// anywhere, is a real pattern this codebase already uses - confirmed by a
// real panic caught in exactly that shape of test). Missing config reads
// as "not debug", matching `larust_http::session::cookie_name()`'s own
// `try_config()` precedent for the identical situation. Never reachable
// in a deployment that leaves `APP_DEBUG` at its production-safe `false`
// default - this is a dev tool (see `larust-db`'s own `DbPlugin` doc
// comment for the *second*, independent password gate that still applies
// regardless).
const DB_ROUTE_SNIPPET: &str = r#"let route = if larust_core::try_config().is_some_and(|c| c.app_debug) {
        route.plugin(larust_support::db::DbPlugin)
    } else {
        route
    };
    "#;

fn routes_web_rs(auth: bool, crate_ident: &str, has_db: bool) -> String {
    let header = if auth {
        ROUTES_WEB_HEADER_WITH_AUTH
    } else {
        ROUTES_WEB_HEADER
    };
    let db_snippet = if has_db { DB_ROUTE_SNIPPET } else { "" };
    format!("{header}{ROUTES_WEB_TAIL}")
        .replace("__CRATE__", crate_ident)
        .replace("__DB_ROUTE_SNIPPET__", db_snippet)
}

// `/storage/logs`/`/storage/releases` - both written to lazily at runtime
// (`crate::logging`'s rotating file writer, `release_slots::publish`), not
// pre-created by `APP_DIRS` above; a fresh app's own git repo (this
// template's gitignore, not this workspace's own broader one - see the
// repo root's own `.gitignore` for the equivalent Laravel-style `storage/`
// section that already covers `demo/`) would otherwise risk committing
// rotated log files or built release binaries the first time either
// actually gets used.
//
// `/database/*.sqlite-*` (alongside plain `*.sqlite`) is not optional
// hygiene - reported directly, from a real production incident: SQLite's
// WAL journal mode, which `larust_orm::pool::connect` enables
// unconditionally for every app (`PRAGMA journal_mode = WAL` - see that
// function's own doc comment), creates `database.sqlite-wal`/
// `database.sqlite-shm` sidecar files alongside the main database file
// during completely ordinary operation, not just in some unusual
// configuration. Without this line, a `git add .` happening to run while
// those files exist commits them - and since they only make sense
// alongside the *exact* main database file that produced them, a later
// `git pull` on a *different* running instance (a server whose own
// database has since diverged) overwrites its WAL/SHM state with a
// mismatched snapshot from the committing machine, corrupting it (`PRAGMA
// integrity_check` reporting "database disk image is malformed" is
// exactly what this looks like). Plain `*.sqlite` alone doesn't match
// either suffix at all - `-wal`/`-shm` are appended to the *whole*
// filename, not swapped in as a different extension - so this gap was
// there from this template's very first version, not a regression.
const GITIGNORE: &str = "/target\n.env\n.env.local\n/database/*.sqlite\n/database/*.sqlite-*\n\
                          /storage/logs\n/storage/releases\n";

// VS Code has no built-in language mode for `.blade.xr` - without this,
// every template opens as plain text with zero syntax highlighting.
// "blade" (registered by the recommended `onecentlin.laravel-blade`
// extension - see VSCODE_EXTENSIONS_JSON below) gives real `@if`/
// `@foreach`/`{{ }}` directive highlighting, not just the surrounding
// HTML. If that extension isn't installed, VS Code falls back to treating
// the file as plain text (no highlighting at all) rather than erroring -
// the `extensions.json` recommendation is what makes declining that a
// deliberate choice instead of a silent downgrade.
// `material-icon-theme.files.associations` maps `.blade.xr` onto that
// extension's own built-in "laravel" icon (confirmed against its source -
// it ships a Laravel icon, but keys it on `.blade.php`/`.inky.php` only,
// so `.blade.xr` gets a generic file icon without this override). A no-op
// if that particular icon theme isn't installed/active - same soft,
// additive shape as the syntax-highlighting recommendation below.
const VSCODE_SETTINGS_JSON: &str = r#"{
    "files.associations": {
        "*.blade.xr": "blade"
    },
    "material-icon-theme.files.associations": {
        "*.blade.xr": "laravel"
    }
}
"#;

const VSCODE_EXTENSIONS_JSON: &str = r#"{
    "recommendations": [
        "onecentlin.laravel-blade",
        "pkief.material-icon-theme"
    ]
}
"#;

/// Scaffolds a plain `xr new <path>` app, also turning on the given
/// `larust-support` Tier-1 shim features (`xr new --features
/// permissions,sanctum`, or the interactive wizard's own multi-select -
/// see `wizard.rs`'s `OPTIONAL_FEATURES`) - the same `features = [...]`
/// mechanism `xr convert` already uses via `new_app_from_workspace`, just
/// with the workspace root auto-detected (walking up from the target
/// directory) instead of given explicitly. Before this existed, a
/// developer who wanted e.g. `permissions` had no way to ask for it from
/// `xr new` at all - only hand-editing the generated `Cargo.toml`'s
/// `larust-support` line afterward (documented in its own doc comment
/// there) or going through `xr convert` on a Laravel app whose
/// `composer.json` already required the equivalent package. Pass `&[]`
/// for the no-optional-features case - that's every call site in this
/// module's own tests below, and `main.rs`'s own `Command::New` dispatch
/// when the wizard/`--features` selected nothing.
pub fn new_app_with_features(
    target: &str,
    auth: bool,
    support_features: &[&str],
    tauri: bool,
) -> Result<()> {
    new_app_with_workspace(target, auth, None, support_features, tauri)
}

/// Scaffolds an application using `workspace_root` to resolve Larust's local
/// path dependencies, even when the target is outside that workspace.
///
/// `xr convert --out` needs this form: the converted project is commonly a
/// sibling of the source Laravel application rather than a child of the
/// Larust checkout that provides the unpublished framework crates.
/// `support_features` is `composer::required_features(&packages)` - the
/// `larust-support` Cargo features the source app's own `composer.json`
/// implies (see that function's own doc comment).
pub fn new_app_from_workspace(
    target: &str,
    auth: bool,
    workspace_root: &Path,
    support_features: &[&str],
    tauri: bool,
) -> Result<()> {
    new_app_with_workspace(target, auth, Some(workspace_root), support_features, tauri)
}

fn new_app_with_workspace(
    target: &str,
    auth: bool,
    workspace_root: Option<&Path>,
    support_features: &[&str],
    tauri: bool,
) -> Result<()> {
    let root = PathBuf::from(target);
    let target_is_nonempty = if root.exists() {
        !root.is_dir()
            || std::fs::read_dir(&root)
                .with_context(|| format!("reading target directory {}", root.display()))?
                .next()
                .is_some()
    } else {
        false
    };
    anyhow::ensure!(
        !target_is_nonempty,
        "target directory `{}` already exists and is not empty",
        root.display()
    );

    if let Err(err) = scaffold(&root, auth, workspace_root, support_features, tauri) {
        // Best-effort cleanup: don't leave a half-written project behind
        // that then blocks a retry with "already exists".
        let _ = std::fs::remove_dir_all(&root);
        return Err(err);
    }

    println!("Created new Larust application at {}", root.display());
    Ok(())
}

// Paths for the demo `Post` scaffold (model/controller/migration/views/test)
// that `remove_demo_scaffold` (crates/larust-cli/src/convert.rs) strips back
// out of a converted Laravel app. Named here, next to the `write_file` calls
// that actually produce them, and consumed directly by `convert.rs` via
// `DEMO_SCAFFOLD_FILES`/`DEMO_SCAFFOLD_MOD_FILES` so the two lists can't
// silently drift apart the way two independently hardcoded copies could.
const POST_CONTROLLER_PATH: &str = "app/Http/Controllers/post_controller.rs";
const STORE_POST_REQUEST_PATH: &str = "app/Http/Requests/store_post_request.rs";
const POST_MODEL_PATH: &str = "app/Models/post.rs";
const CREATE_POSTS_TABLE_PATH: &str = "database/migrations/0001_create_posts_table.sql";
const TESTS_EXAMPLE_PATH: &str = "tests/posts_test.rs";
const LAYOUT_APP_BLADE_XR_PATH: &str = "resources/views/layouts/app.blade.xr";
const WELCOME_BLADE_XR_PATH: &str = "resources/views/welcome.blade.xr";
const LANG_EN_JSON_PATH: &str = "resources/lang/en.json";
const POSTS_INDEX_BLADE_XR_PATH: &str = "resources/views/posts/index.blade.xr";
const POSTS_CREATE_BLADE_XR_PATH: &str = "resources/views/posts/create.blade.xr";

const CONTROLLERS_MOD_PATH: &str = "app/Http/Controllers/mod.rs";
const REQUESTS_MOD_PATH: &str = "app/Http/Requests/mod.rs";
const MODELS_MOD_PATH: &str = "app/Models/mod.rs";

/// Files that only exist because of the demo `Post` scaffold - deleted
/// outright by `remove_demo_scaffold` when converting a real Laravel app.
pub(crate) const DEMO_SCAFFOLD_FILES: &[&str] = &[
    POST_CONTROLLER_PATH,
    STORE_POST_REQUEST_PATH,
    POST_MODEL_PATH,
    CREATE_POSTS_TABLE_PATH,
    TESTS_EXAMPLE_PATH,
    LAYOUT_APP_BLADE_XR_PATH,
    WELCOME_BLADE_XR_PATH,
    POSTS_INDEX_BLADE_XR_PATH,
    POSTS_CREATE_BLADE_XR_PATH,
];

/// `mod.rs` files that reference the demo scaffold and get reset to empty
/// (rather than deleted, since the directory itself must stay a valid
/// module) by `remove_demo_scaffold`.
pub(crate) const DEMO_SCAFFOLD_MOD_FILES: &[&str] =
    &[CONTROLLERS_MOD_PATH, REQUESTS_MOD_PATH, MODELS_MOD_PATH];

fn scaffold(
    root: &Path,
    auth: bool,
    workspace_root: Option<&Path>,
    support_features: &[&str],
    tauri: bool,
) -> Result<()> {
    let app_name = validate_app_name(root)?;

    write_dir(root)?;

    // Requires `root` to already exist on disk (canonicalize needs a real
    // path), and is the step most likely to fail (no ambient workspace) -
    // do it before creating the rest of the tree so failure leaves as
    // little behind as possible.
    let target_abs = root
        .canonicalize()
        .with_context(|| format!("resolving {}", root.display()))?;
    // `Some(_)` only when `--workspace <path>` was given explicitly - every
    // Larust crate is published to crates.io now, so there's nothing to
    // auto-discover by walking up from the target anymore (the old
    // behavior, before this - deliberately not replaced with an
    // auto-detect-if-we-happen-to-be-inside-a-checkout fallback: this
    // codebase's own convention is explicit, not inferred, and that
    // fallback would make `xr new`'s own output depend on *where you
    // happened to run it from*, not what you asked for). `None` here
    // means `crate_dependency` resolves every framework crate as a plain
    // `version = "..."` dependency instead of a local `path` one - no
    // checkout needed at all.
    let ws_root = match workspace_root {
        Some(root) => {
            let root = root
                .canonicalize()
                .with_context(|| format!("resolving Larust workspace {}", root.display()))?;
            anyhow::ensure!(
                root.join("Cargo.toml").is_file(),
                "Larust workspace {} has no Cargo.toml",
                root.display()
            );
            Some(root)
        }
        None => None,
    };
    // `--auth` always generates the comments example (see the `if auth`
    // block below), which is the one thing in this starter app that
    // actually calls `larust_support::reverb`, so `reverb` needs to be a
    // real compiled-in feature whenever `auth` is set - regardless of
    // whatever `support_features` already carries from elsewhere
    // (`composer::required_features`, for `xr convert`; whatever `xr new
    // --features ...`/the interactive wizard selected, for a plain `xr
    // new`). This turning-on is unconditional and not user-visible as a
    // choice at all - unlike every other Tier-1 shim feature, which is
    // strictly opt-in (see `new_app_with_features`'s own doc comment) -
    // because it isn't a Laravel-package equivalent a developer decides to
    // adopt; it's this starter's own baseline example needing the crate it
    // demonstrates.
    let mut resolved_support_features: Vec<&str> = support_features.to_vec();
    if auth {
        resolved_support_features.push("reverb");
    }
    // Exactly one sqlx driver, always - `larust-support`'s own default
    // (`default = ["sqlite"]`) only exists for an app scaffolded before
    // this feature did; every app scaffolded from here on picks one
    // explicitly and turns that default off (see `crate_dependency`'s own
    // `default_features` handling below). `xr new` never asks (matches
    // `DB_CONNECTION`'s own `"sqlite"` default exactly - zero new CLI/
    // wizard surface); `xr convert` already knows the source Laravel
    // app's real driver and pushes the matching feature into
    // `support_features` itself before calling here (see
    // `convert.rs::detect_target_driver`), so this only ever falls back
    // to `"sqlite"` when nothing more specific was already requested.
    if !resolved_support_features
        .iter()
        .any(|f| matches!(*f, "sqlite" | "mysql" | "postgres"))
    {
        resolved_support_features.push("sqlite");
    }
    resolved_support_features.sort_unstable();
    resolved_support_features.dedup();
    // Drives `main_rs`/`routes_web_rs`'s own snippet splicing - see
    // `DB_MAIN_RS_SNIPPET`'s doc comment for why that's presence/absence of
    // fixed text rather than `#[cfg]`.
    let has_db = resolved_support_features.contains(&"db");
    // The same one driver `resolved_support_features` above guarantees is
    // present, needed again by `cargo_toml()` for the app's own *direct*
    // `sqlx` dependency line (`#[derive(Model)]`'s `sqlx::FromRow` can't be
    // reached through `larust-support`'s re-export - see that call site's
    // own comment) - without this, a converted MySQL/Postgres app would
    // still only ever get a `sqlite`-only sqlx build, unable to actually
    // connect.
    let db_driver_feature = resolved_support_features
        .iter()
        .find(|f| matches!(**f, "sqlite" | "mysql" | "postgres"))
        .expect("exactly one sqlx driver feature was pushed above");

    let deps: Vec<(&str, String)> = FRAMEWORK_CRATES
        .iter()
        .map(|name| {
            // Only `larust-support` has optional Tier-1 shim features to
            // turn on - every other framework crate always gets `&[]`
            // (byte-for-byte the same dependency line as before this
            // parameter existed).
            let is_support = *name == "larust-support";
            let features: &[&str] = if is_support {
                &resolved_support_features
            } else {
                &[]
            };
            // `default-features = false` for `larust-http` too, not just
            // `larust-support`: the app depends on `larust-http` *directly*
            // here (it's in `FRAMEWORK_CRATES`), a second, independent
            // edge to the same crate `larust-support`'s own cascade (see
            // its `Cargo.toml`) doesn't control - leaving this edge's
            // `default-features` at `true` would silently re-activate
            // `larust-http`'s own `default = ["sqlite", "mysql",
            // "postgres"]` (see `larust-orm/Cargo.toml`'s comment on that
            // shape) regardless of what the `larust-support` edge
            // selected, defeating the whole point (confirmed empirically
            // via `cargo tree -i sqlx-mysql` before this fix - `sqlx-mysql`
            // was still present through exactly this second path).
            // `larust-core` has no such features to lose either way, but
            // is included here too rather than special-cased out, so a
            // future feature on it doesn't silently reopen this same gap.
            let default_features = *name == "larust-core";
            Ok((
                *name,
                crate_dependency(
                    ws_root.as_deref(),
                    &target_abs,
                    name,
                    features,
                    default_features,
                )?,
            ))
        })
        .collect::<Result<_>>()?;
    let dev_deps: Vec<(&str, String)> = DEV_FRAMEWORK_CRATES
        .iter()
        .map(|name| {
            Ok((
                *name,
                crate_dependency(ws_root.as_deref(), &target_abs, name, &[], true)?,
            ))
        })
        .collect::<Result<_>>()?;

    for dir in APP_DIRS {
        write_dir(&root.join(dir))?;
    }
    write_dir(&root.join("src"))?;

    write_file(
        &root.join("Cargo.toml"),
        cargo_toml(&app_name, &deps, &dev_deps, db_driver_feature),
    )?;
    write_file(&root.join("src/lib.rs"), lib_rs(has_db))?;
    write_file(
        &root.join("src/main.rs"),
        main_rs(&crate_ident(&app_name), has_db),
    )?;
    write_file(
        &root.join(TESTS_EXAMPLE_PATH),
        TESTS_EXAMPLE_RS.replace("__CRATE__", &crate_ident(&app_name)),
    )?;
    write_file(
        &root.join(CONTROLLERS_MOD_PATH),
        if auth {
            CONTROLLERS_MOD_RS_WITH_AUTH
        } else {
            CONTROLLERS_MOD_RS
        },
    )?;
    write_file(
        &root.join(POST_CONTROLLER_PATH),
        if auth {
            POST_CONTROLLER_RS_WITH_AUTH
        } else {
            POST_CONTROLLER_RS
        },
    )?;
    write_file(
        &root.join(REQUESTS_MOD_PATH),
        if auth {
            REQUESTS_MOD_RS_WITH_AUTH
        } else {
            REQUESTS_MOD_RS
        },
    )?;
    write_file(&root.join(STORE_POST_REQUEST_PATH), STORE_POST_REQUEST_RS)?;
    write_file(
        &root.join(MODELS_MOD_PATH),
        if auth {
            MODELS_MOD_RS_WITH_AUTH
        } else {
            MODELS_MOD_RS
        },
    )?;
    write_file(
        &root.join(POST_MODEL_PATH),
        if auth {
            POST_MODEL_RS_WITH_AUTH
        } else {
            POST_MODEL_RS
        },
    )?;
    write_file(&root.join("app/Http/Middleware/mod.rs"), MIDDLEWARE_MOD_RS)?;
    write_file(&root.join("app/Policies/mod.rs"), POLICIES_MOD_RS)?;
    write_file(&root.join("app/Mail/mod.rs"), MAIL_MOD_RS)?;
    write_file(&root.join("app/Jobs/mod.rs"), JOBS_MOD_RS)?;
    write_file(&root.join("app/Events/mod.rs"), EVENTS_MOD_RS)?;
    write_file(&root.join("app/Console/Commands/mod.rs"), COMMANDS_MOD_RS)?;
    write_file(&root.join("app/Wire/mod.rs"), WIRE_MOD_RS)?;
    write_file(&root.join("database/factories/mod.rs"), FACTORIES_MOD_RS)?;
    write_file(&root.join("database/seeders/mod.rs"), SEEDERS_MOD_RS)?;
    write_file(
        &root.join(CREATE_POSTS_TABLE_PATH),
        if auth {
            CREATE_POSTS_TABLE_SQL_WITH_AUTH
        } else {
            CREATE_POSTS_TABLE_SQL
        },
    )?;
    write_file(&root.join(LAYOUT_APP_BLADE_XR_PATH), LAYOUT_APP_BLADE_XR)?;
    write_file(&root.join(WELCOME_BLADE_XR_PATH), WELCOME_BLADE_XR)?;
    write_file(&root.join(LANG_EN_JSON_PATH), LANG_EN_JSON)?;
    write_file(
        &root.join(POSTS_INDEX_BLADE_XR_PATH),
        if auth {
            POSTS_INDEX_BLADE_XR_WITH_AUTH
        } else {
            POSTS_INDEX_BLADE_XR
        },
    )?;
    write_file(
        &root.join(POSTS_CREATE_BLADE_XR_PATH),
        POSTS_CREATE_BLADE_XR,
    )?;
    write_file(&root.join("routes/mod.rs"), ROUTES_MOD_RS)?;
    write_file(
        &root.join("routes/web.rs"),
        routes_web_rs(auth, &crate_ident(&app_name), has_db),
    )?;
    write_file(&root.join("routes/api.rs"), ROUTES_API_RS)?;
    write_file(&root.join("routes/console.rs"), ROUTES_CONSOLE_RS)?;
    write_file(&root.join("config/app.rs"), config_app_rs(&app_name))?;
    write_file(
        &root.join("config/database.rs"),
        config_template::render_database_config_rs(),
    )?;
    write_file(
        &root.join("config/mod.rs"),
        "pub mod app;\npub mod database;\n",
    )?;
    write_file(&root.join(".env"), dot_env_contents(tauri))?;
    write_file(&root.join(".gitignore"), GITIGNORE)?;
    write_file(&root.join(".vscode/settings.json"), VSCODE_SETTINGS_JSON)?;
    write_file(
        &root.join(".vscode/extensions.json"),
        VSCODE_EXTENSIONS_JSON,
    )?;
    if tauri {
        write_tauri_scaffold(root, &crate_ident(&app_name), &app_name)?;
    }

    if auth {
        write_dir(&root.join("resources/views/auth"))?;
        write_file(
            &root.join("app/Http/Requests/register_request.rs"),
            REGISTER_REQUEST_RS,
        )?;
        write_file(
            &root.join("app/Http/Requests/login_request.rs"),
            LOGIN_REQUEST_RS,
        )?;
        write_file(&root.join("app/Models/user.rs"), USER_MODEL_RS)?;
        write_file(
            &root.join("app/Http/Controllers/auth_controller.rs"),
            AUTH_CONTROLLER_RS,
        )?;
        write_file(
            &root.join("resources/views/auth/register.blade.xr"),
            AUTH_REGISTER_BLADE_XR,
        )?;
        write_file(
            &root.join("resources/views/auth/login.blade.xr"),
            AUTH_LOGIN_BLADE_XR,
        )?;
        write_file(
            &root.join("database/migrations/0002_create_users_table.sql"),
            CREATE_USERS_TABLE_SQL,
        )?;

        // Live comments - the one piece of this starter that demonstrates
        // `larust_support::reverb` (see `resolved_support_features`
        // above). Needs a `User` to attribute a comment to, so it's
        // auth-only, unlike everything else in this function.
        write_file(&root.join("app/Models/comment.rs"), COMMENT_MODEL_RS)?;
        write_file(
            &root.join("app/Http/Requests/store_comment_request.rs"),
            STORE_COMMENT_REQUEST_RS,
        )?;
        write_file(
            &root.join("app/Http/Controllers/comment_controller.rs"),
            COMMENT_CONTROLLER_RS,
        )?;
        write_file(
            &root.join("resources/views/posts/show.blade.xr"),
            POSTS_SHOW_BLADE_XR_WITH_AUTH,
        )?;
        write_file(
            &root.join("database/migrations/0003_create_comments_table.sql"),
            CREATE_COMMENTS_TABLE_SQL,
        )?;
    }

    Ok(())
}

/// Validates that the target path's final component is safe to interpolate
/// into generated Rust identifiers and string literals (package name,
/// `config/app.rs`'s own `app_name` default). Rejecting anything outside a
/// conservative charset up front means the generator never has to worry
/// about escaping quotes or control characters.
fn validate_app_name(root: &Path) -> Result<String> {
    let app_name = root
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("larust-app")
        .to_string();

    anyhow::ensure!(
        !app_name.is_empty()
            && app_name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
        "invalid application name `{app_name}`: use only letters, digits, `-`, and `_`"
    );
    // `app_name` itself only ever became a Cargo package name and a
    // private `mod` declaration before `lib.rs`/`__CRATE__` existed, so a
    // leading digit or a Rust keyword was harmless. Now `crate_ident`
    // (hyphens→underscores) gets substituted directly into `use
    // {crate_ident}::...` paths in `main.rs`/`tests/posts_test.rs`, so it
    // has to be validated as a real Rust identifier - reusing
    // `larust_convert::codegen::validate_identifier` (charset, leading
    // digit, Rust keywords, and `__WORD__`-shaped placeholder collisions)
    // rather than duplicating that logic here. Checking
    // `crate_ident(&app_name)` itself, not the pre-transform `app_name`,
    // matters: a hyphenated name that's harmless on its own (`--CRATE--`)
    // can still transform into something placeholder-shaped (`__CRATE__`)
    // once hyphens become underscores.
    larust_convert::codegen::validate_identifier(&crate_ident(&app_name))
        .with_context(|| format!("invalid application name `{app_name}`"))?;

    Ok(app_name)
}

pub(crate) fn write_dir(path: &Path) -> Result<()> {
    std::fs::create_dir_all(path).with_context(|| format!("creating {}", path.display()))
}

pub(crate) fn write_file(path: &Path, contents: impl AsRef<[u8]>) -> Result<()> {
    std::fs::write(path, contents).with_context(|| format!("writing {}", path.display()))
}

/// Strips `canonicalize()`'s own `\\?\` verbatim-path prefix, if present -
/// a no-op on Unix (that prefix is Windows-only, `canonicalize()` there
/// never adds one) and a no-op for any path that never carried it. Needed
/// because that prefix, embedded as a `Cargo.toml` `path = "..."` value,
/// is what makes Cargo's manifest parser reject it outright with "invalid
/// path url" - a plain absolute path with the identical target, minus
/// just this prefix, parses and resolves fine (confirmed directly against
/// a real scratch crate, cross-drive included).
fn strip_verbatim_prefix(path: &Path) -> PathBuf {
    const VERBATIM_PREFIX: &str = r"\\?\";
    match path.to_str() {
        Some(s) if s.starts_with(VERBATIM_PREFIX) => PathBuf::from(&s[VERBATIM_PREFIX.len()..]),
        _ => path.to_path_buf(),
    }
}

/// The version every crates.io-mode dependency (`ws_root: None` below)
/// pins against - `larust-cli`'s own compiled-in package version, not a
/// hardcoded literal, so a future `xr release` version bump can't silently
/// drift out of sync with what newly-scaffolded apps actually ask for. A
/// plain `"0.5.0"` string is already a caret requirement by Cargo's own
/// default (`^0.5.0`, not an exact pin) - nothing extra needed for normal
/// patch/compatible updates to keep resolving.
const FRAMEWORK_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Resolves a framework crate as a dependency of the app being scaffolded.
/// `ws_root: Some(_)` is `--workspace` mode (a `path` dependency, relative
/// to `target_abs` when possible - exactly today's long-standing
/// behavior, for contributors scaffolding a test app against local,
/// possibly-unpublished framework changes). `ws_root: None` is the default
/// since every Larust crate is now on crates.io: a plain `version =
/// "...\"` dependency, no checkout needed at all.
///
/// `features` is almost always empty (every framework crate except
/// `larust-support` has no optional features at all) - when non-empty,
/// appends a `features = [...]` field, the mechanism `xr convert` uses to
/// turn `composer.json`'s own `require` block into which of
/// `larust-support`'s optional Tier-1 shim features the generated
/// `Cargo.toml` turns on (see `composer::required_features`).
/// `default_features = false` is only ever needed for `larust-support`
/// today - it now always carries exactly one `sqlite`/`mysql`/`postgres`
/// driver feature (see `scaffold()`'s own `resolved_support_features`
/// handling), replacing its own `default = ["sqlite"]` fallback (kept
/// there purely for an *already-scaffolded* app generated before this
/// feature existed - see `larust-support/Cargo.toml`'s own comment) rather
/// than adding to it.
fn crate_dependency(
    ws_root: Option<&Path>,
    target_abs: &Path,
    crate_name: &str,
    features: &[&str],
    default_features: bool,
) -> Result<String> {
    let Some(ws_root) = ws_root else {
        let mut parts = vec![format!("version = \"{FRAMEWORK_VERSION}\"")];
        if !default_features {
            parts.push("default-features = false".to_string());
        }
        if !features.is_empty() {
            let feature_list = features
                .iter()
                .map(|f| format!("\"{f}\""))
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(format!("features = [{feature_list}]"));
        }
        return Ok(format!("{{ {} }}", parts.join(", ")));
    };

    let crate_path = ws_root.join("crates").join(crate_name);
    let rel = pathdiff::diff_paths(&crate_path, target_abs).with_context(|| {
        format!(
            "could not compute a relative path to {crate_name} \
             (target and workspace may be on different drives)"
        )
    })?;
    // `pathdiff::diff_paths` never actually returns `None` for this on
    // Windows - confirmed directly, not assumed: given two canonicalized
    // absolute paths with no common root (e.g. the new app on `C:` and
    // the workspace checkout on `E:` - a real case, not hypothetical:
    // `xr convert` deliberately resolves the workspace from its own
    // compile-time checkout regardless of wherever `--out` points, and
    // GitHub's hosted Windows runners checkout to `D:` while `TEMP`
    // resolves to `C:`), it silently falls back to returning `crate_path`
    // itself, verbatim and still absolute, rather than failing. The
    // `.with_context(...)` above is dead code for this real failure mode,
    // not a safety net.
    //
    // No relative path is *expressible* here - Windows has none across
    // drive letters, full stop - but that doesn't mean this has to be an
    // error: a plain absolute path dependency (`path = "E:/vsprojects/
    // Larust/crates/larust-core"`, no prefix) resolves and builds
    // correctly, cross-drive included - confirmed directly against a real
    // scratch crate. What actually breaks is `canonicalize()`'s own
    // `\\?\`-prefixed verbatim syntax riding along in `rel` here (still
    // `crate_path`, unchanged) - Cargo's manifest parser rejects that
    // outright with "invalid path url", a confusing failure one `cargo
    // build` away from its real cause. Stripping just that prefix - not
    // rejecting the cross-drive case outright - is what actually fixes
    // the original bug report without also breaking `xr convert`'s own
    // documented "destination lives anywhere" design.
    let path = if rel.is_relative() {
        rel.to_string_lossy().replace('\\', "/")
    } else {
        strip_verbatim_prefix(&rel)
            .to_string_lossy()
            .replace('\\', "/")
    };
    let mut parts = vec![format!("path = \"{path}\"")];
    if !default_features {
        parts.push("default-features = false".to_string());
    }
    if !features.is_empty() {
        let feature_list = features
            .iter()
            .map(|f| format!("\"{f}\""))
            .collect::<Vec<_>>()
            .join(", ");
        parts.push(format!("features = [{feature_list}]"));
    }
    Ok(format!("{{ {} }}", parts.join(", ")))
}

fn cargo_toml(
    app_name: &str,
    deps: &[(&str, String)],
    dev_deps: &[(&str, String)],
    db_driver_feature: &str,
) -> String {
    let mut out = format!(
        "[package]\nname = \"{app_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n"
    );
    for (name, dep) in deps {
        out.push_str(&format!("{name} = {dep}\n"));
    }
    out.push_str("tokio = { version = \"1\", features = [\"full\"] }\n");
    // sqlx's own `#[derive(FromRow)]` generates code referencing `::sqlx::...`
    // directly - it doesn't honor a local `use larust_support::orm::sqlx;`
    // alias, so unlike the rest of the framework it can't be fully hidden
    // behind `larust-support`. This is a real limitation of sqlx (and
    // several other derive-macro crates), not a Larust design choice.
    // `db_driver_feature` mirrors whatever driver `larust-support`'s own
    // dependency line above just selected - see `scaffold()`'s own
    // `db_driver_feature` comment for why this can't just always say
    // `"sqlite"` (a converted MySQL/Postgres app needs to actually be able
    // to connect).
    out.push_str(&format!(
        "sqlx = {{ version = \"0.8\", default-features = false, features = [\"runtime-tokio\", \"{db_driver_feature}\", \"derive\"] }}\n",
    ));
    // Same limitation, same reasoning as `sqlx` above: `#[derive(Serialize,
    // Deserialize)]` generates code referencing `::serde::...` directly,
    // not honoring a `larust_support`-re-exported alias, so a `Job`'s own
    // payload struct - a real app-defined type, not a framework internal -
    // needs `serde` as a direct dependency to derive against. `Event`
    // payloads need no such exception: `Event` is `Clone`-based, never
    // serialized.
    out.push_str("serde = { version = \"1\", features = [\"derive\"] }\n");
    // A transitive dependency (pulled in via ICU/URL-parsing crates several
    // framework crates use), pinned here for the same reason this repo's
    // own root `Cargo.toml`/`Cargo.lock` already resolve to it rather than
    // 1.13.0: `tinyvec` 1.13.0 fails to compile under rustc 1.98+ ("cannot
    // find macro `vec` in this scope" - confirmed live, reproduced and
    // fixed by pinning to this exact version). A freshly scaffolded app has
    // no lockfile of its own yet, so without this it would resolve fresh to
    // whatever crates.io currently has as latest - silently inheriting that
    // break the moment someone runs `xr new` on an affected toolchain, with
    // no framework code of their own to blame. Remove once a fixed release
    // ships upstream.
    out.push_str("tinyvec = \"=1.12.0\"\n");

    out.push_str("\n[dev-dependencies]\n");
    for (name, dep) in dev_deps {
        out.push_str(&format!("{name} = {dep}\n"));
    }
    out.push_str(include_str!("build_profiles.toml"));
    out
}

/// `config/app.rs`'s content for a freshly scaffolded app - the same
/// literal defaults `config_app_toml` (this function's TOML-era
/// predecessor) used, re-expressed via [`config_template::render_app_config_rs`]'s
/// shared `env_or`/`env_bool`-backed template so `.env` can still override
/// any of them, matching `xr convert`'s own use of the same template.
/// `tauri` picks which of the two mutually exclusive `DEPLOY_TYPE` example
/// lines is left active - see [`write_tauri_scaffold`]'s own doc comment
/// for why `xr new --tauri`/`xr add tauri` are the only two writers of an
/// uncommented `DEPLOY_TYPE=app` line.
fn dot_env_contents(tauri: bool) -> String {
    let deploy_type_line = if tauri {
        "DEPLOY_TYPE=app\n"
    } else {
        "# DEPLOY_TYPE=web\n"
    };
    format!(
        "APP_ENV=local\nAPP_PORT=34187\n\
         # Which named connection below is active - sqlite, mysql, mariadb,\n\
         # pgsql, or sqlsrv (see config/database.rs). sqlsrv isn't connectable\n\
         # via this framework's ORM at all - see the larust-mssql crate.\n\
         DB_CONNECTION=sqlite\n\
         # DB_HOST=127.0.0.1\n\
         # DB_PORT=3306\n\
         # DB_DATABASE=larust\n\
         # DB_USERNAME=root\n\
         # DB_PASSWORD=\n\
         # DB_CHARSET=utf8mb4\n\
         # Base URL used by url()/asset() to build absolute URLs from a relative path.\n\
         APP_URL=http://localhost\n\
         # t()/t_with() resolve against this locale by default; APP_FALLBACK_LOCALE is\n\
         # tried next when a key is missing from the current locale's own translation\n\
         # file (see resources/lang/en.json). No effect until a route actually attaches\n\
         # larust_http::locale::negotiate - see routes/web.rs.\n\
         APP_LOCALE=en\n\
         APP_FALLBACK_LOCALE=en\n\
         # Browsers only treat loopback/`localhost` as a secure context over plain HTTP.\n\
         # Set this to false if you serve local dev from a custom hostname (e.g. a .test\n\
         # domain in /etc/hosts) or the session cookie will be silently dropped.\n\
         SESSION_SECURE_COOKIE=true\n\
         # \"database\" (default) - sessions live in DB_CONNECTION's database. \"file\"\n\
         # writes one file per session to storage/sessions/ instead - no database\n\
         # round trip for session reads/writes, at the cost of only working on a single\n\
         # server (every process needs to see the same directory).\n\
         # SESSION_DRIVER=database\n\
         # Renders full error detail (message, source chain, panics) as an HTML page\n\
         # instead of a generic \"internal server error\". Never enable outside local dev.\n\
         APP_DEBUG=true\n\
         # \"stdout\" (default) - everything goes to the terminal. \"file\" writes to\n\
         # storage/logs/larust.log instead (rotated once it passes LOG_MAX_SIZE, oldest\n\
         # kept backups deleted beyond LOG_KEEP_FILES). \"stack\" does both at once.\n\
         # LOG_CHANNEL=stdout\n\
         # trace/debug/info/warn/error - leave unset to keep this framework's own\n\
         # default (verbose locally, quieter in any other APP_ENV).\n\
         # LOG_LEVEL=debug\n\
         # LOG_MAX_SIZE=10485760\n\
         # LOG_KEEP_FILES=5\n\
         # \"log\" writes a mail's rendered subject/body to the app's own log output\n\
         # instead of sending it - no SMTP server needed for local dev or `cargo test`.\n\
         # Set this to \"smtp\" and fill in the fields below to send for real.\n\
         MAIL_DRIVER=log\n\
         # MAIL_HOST=smtp.example.com\n\
         # Port 587 (the standard submission port almost every real provider\n\
         # expects) needs \"starttls\", not \"tls\" (implicit TLS, port 465's\n\
         # convention) - pick the pairing that matches your provider's setup.\n\
         # MAIL_PORT=587\n\
         # MAIL_USERNAME=\n\
         # MAIL_PASSWORD=\n\
         # MAIL_ENCRYPTION=starttls\n\
         # MAIL_FROM_ADDRESS=hello@example.com\n\
         # MAIL_FROM_NAME=\n\
         # \"database\" stores cache/queue entries in the same connection\n\
         # config/database.rs selects above; \"redis\" uses Redis instead.\n\
         # CACHE_DRIVER=database\n\
         # QUEUE_DRIVER=database\n\
         # \"web\" (default) - an ordinary server, published via `xr deploy`.\n\
         # \"app\" - a Tauri desktop build, published via `xr deploy` from\n\
         # src-tauri/ (scaffold it first with `xr add tauri` if you didn't\n\
         # pass --tauri to `xr new`).\n\
         {deploy_type_line}"
    )
}

const TAURI_CARGO_TOML: &str = r#"[package]
name = "__PACKAGE__-tauri"
version = "0.1.0"
edition = "2021"

[build-dependencies]
tauri-build = { version = "2", features = [] }

[dependencies]
__PACKAGE__ = { path = ".." }
tauri = { version = "2", features = [] }
tokio = { version = "1", features = ["rt-multi-thread"] }

[[bin]]
name = "__PACKAGE__-tauri"
path = "src/main.rs"
"#;

const TAURI_BUILD_RS: &str = "fn main() {\n    tauri_build::build();\n}\n";

const TAURI_MAIN_RS: &str = r#"// Spawns the same `__CRATE__::serve()` this app's ordinary web binary
// (`src/main.rs`) calls, on a background thread of its own runtime, then
// points a native webview at it - the "embedded local server" model: one
// router, one set of business logic, reached over loopback HTTP instead of
// duplicated behind a second frontend stack.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
    let runtime = tokio::runtime::Runtime::new()
        .expect("failed to start the embedded server's async runtime");
    let handle = runtime.handle().clone();
    std::thread::spawn(move || {
        handle.block_on(async {
            if let Err(err) = __CRATE__::serve().await {
                eprintln!("embedded server exited: {err}");
            }
        });
    });

    let url = format!("http://127.0.0.1:{}", __CRATE__::port());
    tauri::Builder::default()
        .setup(move |app| {
            let target = tauri::WebviewUrl::External(url.parse().expect("valid embedded server URL"));
            tauri::WebviewWindowBuilder::new(app, "main", target)
                .title("__APP_NAME__")
                .build()?;
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running the Tauri application");
}
"#;

/// Written by both `scaffold()` (when `xr new --tauri`) and `xr add tauri`
/// (`add.rs`, retrofitting an already-scaffolded app) - the single code
/// path that writes `src-tauri/`, so the two entry points can't drift.
/// `src-tauri/Cargo.toml` deliberately depends on the parent app crate via
/// a plain `path = ".."` rather than joining it as a workspace member - the
/// app root has no `[workspace]` table of its own (`find_workspace_root`
/// only ever looks *upward*, for the ambient Larust checkout), so this is a
/// perfectly ordinary sibling crate, the same split
/// `create-tauri-app`-style scaffolds use. No icon files are generated
/// here - `cargo tauri dev` doesn't need any, and `cargo tauri build`'s
/// install-style hint if `src-tauri/icons/` is still empty (`deploy.rs`'s
/// `deploy_app`) is cheaper than shipping an image-processing dependency
/// in `xr` just to produce placeholder art nobody keeps.
pub(crate) fn write_tauri_scaffold(root: &Path, crate_ident: &str, app_name: &str) -> Result<()> {
    write_dir(&root.join("src-tauri/src"))?;
    write_dir(&root.join("src-tauri/icons"))?;
    write_file(
        &root.join("src-tauri/Cargo.toml"),
        TAURI_CARGO_TOML.replace("__PACKAGE__", app_name),
    )?;
    write_file(&root.join("src-tauri/build.rs"), TAURI_BUILD_RS)?;
    write_file(
        &root.join("src-tauri/tauri.conf.json"),
        tauri_conf_json(app_name),
    )?;
    write_file(
        &root.join("src-tauri/src/main.rs"),
        TAURI_MAIN_RS
            .replace("__CRATE__", crate_ident)
            .replace("__APP_NAME__", app_name),
    )?;
    Ok(())
}

/// Tauri v2 config schema. `bundle.icon` starts empty - see
/// [`write_tauri_scaffold`]'s own doc comment on why icons aren't
/// generated at scaffold time. The window's real content comes from
/// `src/main.rs`'s own `WebviewUrl::External(...)` call, not from
/// `build.frontendDist` - there's no separate frontend bundle here, so
/// that field just needs to point at *something* that exists to satisfy
/// the schema, and `public/` (already scaffolded for the ordinary web
/// binary's own static-asset serving) already does.
fn tauri_conf_json(app_name: &str) -> String {
    format!(
        r#"{{
  "$schema": "https://schema.tauri.app/config/2",
  "productName": {app_name:?},
  "version": "0.1.0",
  "identifier": "com.larust.{app_name}",
  "build": {{
    "frontendDist": "../public"
  }},
  "app": {{
    "windows": [
      {{
        "title": {app_name:?},
        "width": 1024,
        "height": 768
      }}
    ]
  }},
  "bundle": {{
    "active": true,
    "targets": "all",
    "icon": []
  }}
}}
"#
    )
}

fn config_app_rs(app_name: &str) -> String {
    let mut defaults = HashMap::new();
    defaults.insert("app_name", format!("{app_name:?}"));
    // Local-dev-friendly: `false` is `Config`'s own generic default
    // (matching a production-safe fallback), but a freshly scaffolded app
    // is always local dev - same override `.env`'s own `APP_DEBUG=true`
    // line already carries, kept here too as this file's own fallback if
    // `.env` ever goes missing.
    defaults.insert("app_debug", "true".to_string());
    config_template::render_app_config_rs(&defaults, &[])
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn crate_dependency_computes_relative_path_into_crates_dir() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("crates").join("larust-core")).unwrap();
        let app_root = tmp.path().join("examples").join("blog");
        fs::create_dir_all(&app_root).unwrap();

        let dep = crate_dependency(Some(tmp.path()), &app_root, "larust-core", &[], true).unwrap();

        assert_eq!(dep, "{ path = \"../../crates/larust-core\" }");
    }

    #[test]
    fn crate_dependency_emits_a_version_requirement_in_crates_io_mode() {
        // `ws_root: None` - the default now that every Larust crate is
        // published, exercised with no filesystem at all (unlike the
        // `--workspace` tests above, which need a real tempdir to compute
        // a path against): this mode never touches `target_abs`.
        let app_root = Path::new("/irrelevant/for/this/mode");

        let dep = crate_dependency(None, app_root, "larust-core", &[], true).unwrap();

        assert_eq!(dep, format!("{{ version = \"{FRAMEWORK_VERSION}\" }}"));
    }

    #[test]
    fn crate_dependency_crates_io_mode_still_honors_default_features_and_feature_list() {
        let app_root = Path::new("/irrelevant/for/this/mode");

        let dep = crate_dependency(None, app_root, "larust-support", &["sqlite"], false).unwrap();

        assert_eq!(
            dep,
            format!(
                "{{ version = \"{FRAMEWORK_VERSION}\", default-features = false, \
                 features = [\"sqlite\"] }}"
            )
        );
    }

    #[test]
    fn crate_dependency_adds_default_features_false_when_asked() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("crates").join("larust-support")).unwrap();
        let app_root = tmp.path().join("examples").join("blog");
        fs::create_dir_all(&app_root).unwrap();

        let dep = crate_dependency(
            Some(tmp.path()),
            &app_root,
            "larust-support",
            &["sqlite"],
            false,
        )
        .unwrap();

        assert_eq!(
            dep,
            "{ path = \"../../crates/larust-support\", default-features = false, \
             features = [\"sqlite\"] }"
        );
    }

    #[test]
    #[cfg(windows)]
    fn crate_dependency_falls_back_to_a_plain_absolute_path_across_different_drives() {
        // Real paths, not a tempdir: reproduces a real incident directly
        // (`xr convert`'s own `run()` always resolves the workspace from
        // its compile-time checkout regardless of wherever `--out` points
        // - see that function's own doc comment - and GitHub's hosted
        // Windows runners checkout to `D:` while `TEMP` resolves to `C:`,
        // a real case this exact scenario hit in CI) without needing a
        // second drive to actually exist locally - this function never
        // touches the filesystem itself (the caller canonicalizes first),
        // so synthetic absolute paths exercise the identical code path.
        // No relative path exists across drive letters on Windows, full
        // stop - but that's not an error case: a plain absolute path
        // dependency resolves and builds fine, cross-drive included
        // (confirmed directly against a real scratch crate).
        let ws_root = Path::new(r"E:\vsprojects\Larust");
        let target_abs = Path::new(r"C:\Users\someone\myapp");

        let dep = crate_dependency(Some(ws_root), target_abs, "larust-core", &[], true).unwrap();
        assert_eq!(
            dep,
            "{ path = \"E:/vsprojects/Larust/crates/larust-core\" }"
        );
    }

    #[test]
    #[cfg(windows)]
    fn strip_verbatim_prefix_removes_the_windows_canonicalize_prefix() {
        // The actual mechanism behind the fix above: `canonicalize()`'s
        // own `\\?\`-prefixed form is what Cargo's manifest parser
        // rejects outright with "invalid path url" - confirmed directly
        // against a real `cargo check` - even though the identical path
        // minus just this prefix resolves fine.
        assert_eq!(
            strip_verbatim_prefix(Path::new(r"\\?\E:\vsprojects\Larust")),
            Path::new(r"E:\vsprojects\Larust")
        );
        // A path that never carried the prefix passes through unchanged -
        // the common case, and what every same-drive scaffold already
        // exercises via the relative-path branch that never calls this at
        // all.
        assert_eq!(
            strip_verbatim_prefix(Path::new(r"E:\vsprojects\Larust")),
            Path::new(r"E:\vsprojects\Larust")
        );
    }

    #[test]
    fn crate_dependency_appends_features_when_given() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("crates").join("larust-support")).unwrap();
        let app_root = tmp.path().join("examples").join("blog");
        fs::create_dir_all(&app_root).unwrap();

        let dep = crate_dependency(
            Some(tmp.path()),
            &app_root,
            "larust-support",
            &["permissions", "sanctum"],
            true,
        )
        .unwrap();

        assert_eq!(
            dep,
            "{ path = \"../../crates/larust-support\", features = [\"permissions\", \"sanctum\"] }"
        );
    }

    #[test]
    fn new_app_succeeds_outside_any_workspace_using_crates_io_dependencies() {
        // The real behavior change this whole milestone is about: no
        // ambient Larust checkout anywhere above `target`, and no
        // `--workspace` given either - this used to be a hard error
        // ("`xr new` currently requires running from inside a Larust
        // workspace checkout") before every Larust crate was published.
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("app");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
        assert!(
            cargo_toml.contains(&format!("version = \"{FRAMEWORK_VERSION}\"")),
            "expected a crates.io version requirement with no workspace available, got:\n{cargo_toml}"
        );
        assert!(
            !cargo_toml.contains("path = \"../"),
            "must not fall back to a local path dependency with no workspace available: \
             {cargo_toml}"
        );
    }

    #[test]
    fn validate_app_name_rejects_unsafe_characters() {
        assert!(validate_app_name(Path::new("my\"app")).is_err());
    }

    #[test]
    fn validate_app_name_accepts_normal_names() {
        assert_eq!(
            validate_app_name(Path::new("/tmp/examples/blog")).unwrap(),
            "blog"
        );
    }

    #[test]
    fn validate_app_name_rejects_names_shaped_like_a_template_placeholder() {
        assert!(validate_app_name(Path::new("/tmp/__CRATE__")).is_err());
    }

    #[test]
    fn validate_app_name_rejects_a_hyphenated_name_whose_crate_ident_is_placeholder_shaped() {
        // `app_name` itself ("--CRATE--") isn't `__`-shaped and passes the
        // charset check, but `crate_ident("--CRATE--")` ("__CRATE__")
        // collides with the `__CRATE__` template placeholder - the guard
        // has to check the post-transform identifier, not the raw name.
        assert!(validate_app_name(Path::new("/tmp/--CRATE--")).is_err());
    }

    #[test]
    fn validate_app_name_rejects_a_name_starting_with_a_digit() {
        // Harmless before `crate_ident` started flowing into `use`
        // paths (`app_name` was only ever a Cargo package name and a
        // private `mod` declaration) - `use 9lives::...` is a syntax
        // error now that it's a real identifier.
        assert!(validate_app_name(Path::new("/tmp/9lives")).is_err());
    }

    #[test]
    fn validate_app_name_rejects_a_rust_keyword() {
        // `use type::controllers::...;` is a syntax error.
        assert!(validate_app_name(Path::new("/tmp/type")).is_err());
    }

    #[test]
    fn crate_ident_replaces_hyphens_with_underscores() {
        assert_eq!(crate_ident("my-app"), "my_app");
        assert_eq!(crate_ident("blog"), "blog");
        assert_eq!(crate_ident("my_app"), "my_app");
    }

    #[test]
    fn new_app_cleans_up_partial_scaffold_on_failure() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("orphan-app");
        // A deliberately bogus `--workspace` path - still fails *after*
        // `scaffold()` has already created the root directory (the write
        // the cleanup path exists to undo), unlike the crates.io default,
        // which no longer has any fallible step here at all.
        let bogus_workspace = tmp.path().join("does-not-exist");

        let result = new_app_from_workspace(
            target.to_str().unwrap(),
            false,
            &bogus_workspace,
            &[],
            false,
        );

        assert!(result.is_err());
        assert!(
            !target.exists(),
            "partial scaffold should be cleaned up on failure"
        );
    }

    #[test]
    fn new_app_with_auth_creates_the_auth_specific_files() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), true, &[], false).unwrap();

        for path in [
            "app/Models/user.rs",
            "app/Http/Controllers/auth_controller.rs",
            "app/Http/Requests/register_request.rs",
            "app/Http/Requests/login_request.rs",
            "resources/views/auth/register.blade.xr",
            "resources/views/auth/login.blade.xr",
            "database/migrations/0002_create_users_table.sql",
            "app/Models/comment.rs",
            "app/Http/Controllers/comment_controller.rs",
            "app/Http/Requests/store_comment_request.rs",
            "resources/views/posts/show.blade.xr",
            "database/migrations/0003_create_comments_table.sql",
        ] {
            assert!(
                target.join(path).exists(),
                "`xr new --auth` should create {path}"
            );
        }

        let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
        assert!(
            routes_web_rs.contains("AuthController") && routes_web_rs.contains("require_auth"),
            "routes/web.rs should wire up AuthController and the require_auth middleware"
        );
    }

    #[test]
    fn new_app_without_auth_does_not_create_auth_specific_files() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        assert!(!target.join("app/Models/user.rs").exists());
        assert!(!target
            .join("app/Http/Controllers/auth_controller.rs")
            .exists());

        let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
        assert!(!routes_web_rs.contains("AuthController"));

        // Live comments need a `User` to attribute a comment to - see
        // `scaffold()`'s own `if auth { ... }` block - so a non-auth app
        // gets none of it, and `reverb` stays off in its `Cargo.toml`.
        assert!(!target.join("app/Models/comment.rs").exists());
        assert!(!routes_web_rs.contains("CommentController"));
        let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
        assert!(
            !cargo_toml.contains("reverb"),
            "Cargo.toml was: {cargo_toml}"
        );
    }

    #[test]
    fn new_app_with_auth_wires_up_live_comments() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), true, &[], false).unwrap();

        let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
        assert!(
            cargo_toml.contains("\"reverb\""),
            "Cargo.toml should turn on the reverb feature for an auth app: {cargo_toml}"
        );

        let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
        assert!(
            routes_web_rs.contains("CommentController")
                && routes_web_rs.contains(".plugin(larust_support::wire::WirePlugin)")
                && routes_web_rs.contains(".plugin(larust_support::spa::SpaPlugin)")
                && routes_web_rs.contains(".plugin(larust_support::image::ImagePlugin)")
                && routes_web_rs.contains(".plugin(larust_support::reverb::ReverbPlugin)"),
            "routes/web.rs should wire up CommentController and the wire/spa/image/reverb \
             plugins: {routes_web_rs}"
        );

        let show_view =
            fs::read_to_string(target.join("resources/views/posts/show.blade.xr")).unwrap();
        assert!(
            show_view.contains("LarustReverb") && show_view.contains("CommentCreated"),
            "posts/show.blade.xr should wire up the reverb client: {show_view}"
        );
    }

    #[test]
    fn new_app_with_tauri_scaffolds_src_tauri() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], true).unwrap();

        assert!(target.join("src-tauri/Cargo.toml").is_file());
        assert!(target.join("src-tauri/build.rs").is_file());
        assert!(target.join("src-tauri/tauri.conf.json").is_file());
        assert!(target.join("src-tauri/src/main.rs").is_file());
        assert!(target.join("src-tauri/icons").is_dir());

        let cargo_toml = fs::read_to_string(target.join("src-tauri/Cargo.toml")).unwrap();
        assert!(
            cargo_toml.contains("blog = { path = \"..\" }"),
            "src-tauri/Cargo.toml should depend on the parent app crate by path: {cargo_toml}"
        );

        let env = fs::read_to_string(target.join(".env")).unwrap();
        assert!(
            env.contains("\nDEPLOY_TYPE=app\n") && !env.contains("# DEPLOY_TYPE=app"),
            ".env should uncomment DEPLOY_TYPE=app when --tauri is passed: {env}"
        );
    }

    #[test]
    fn new_app_without_tauri_has_no_src_tauri() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        assert!(!target.join("src-tauri").exists());
        let env = fs::read_to_string(target.join(".env")).unwrap();
        assert!(env.contains("# DEPLOY_TYPE=web"));
    }

    /// Guards the coupling `convert.rs`'s `remove_demo_scaffold` documents:
    /// every path in `DEMO_SCAFFOLD_FILES`/`DEMO_SCAFFOLD_MOD_FILES` must
    /// actually exist after a real scaffold, or `xr convert` would try to
    /// delete/reset a file that was never written. Catches the case someone
    /// adds a new demo `write_file` call with an inline literal path
    /// without also adding it to one of these two shared arrays.
    #[test]
    fn every_demo_scaffold_path_exists_after_a_real_scaffold() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        for relative in DEMO_SCAFFOLD_FILES {
            assert!(
                target.join(relative).is_file(),
                "DEMO_SCAFFOLD_FILES entry {relative:?} was not written by scaffold()"
            );
        }
        for relative in DEMO_SCAFFOLD_MOD_FILES {
            assert!(
                target.join(relative).is_file(),
                "DEMO_SCAFFOLD_MOD_FILES entry {relative:?} was not written by scaffold()"
            );
        }
    }

    /// The real local checkout, not whatever happens to be published on
    /// crates.io - mirrors `convert.rs::run()`'s own identical arithmetic
    /// exactly. Every test below that actually *compiles* or *resolves*
    /// its scaffold output needs this explicitly, now that `ws_root: None`
    /// means crates.io by default: without it, these tests would silently
    /// start verifying whatever version is currently published instead of
    /// the source sitting right here, uncommitted changes included -
    /// exactly the regression-catching power they exist for.
    fn local_workspace_root() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .and_then(Path::parent)
            .expect("CARGO_MANIFEST_DIR should be nested two levels under the workspace root")
            .to_path_buf()
    }

    /// Scaffolds a real `xr new --auth` app into this crate's own
    /// `target/tmp/`, then actually **compiles it** - same "scratch-
    /// scaffold verification" technique `convert.rs`'s own
    /// `converts_the_fixture_app_into_a_project_that_compiles` uses (see
    /// its doc comment): a temporary `[workspace]` table isolates the
    /// generated crate from the outer workspace (it isn't matched by
    /// `crates/*`, so without this Cargo would error "believes it's in a
    /// workspace when it's not"), `cargo build` runs against it
    /// standalone, then the whole output directory is discarded. No
    /// scaffold.rs test previously proved the generated app actually
    /// compiles at all - every other test here only asserts on file
    /// existence/content strings - so this is the first, and specifically
    /// targets `--auth` since that's the branch the live-comments example
    /// (and its new `reverb` Cargo feature) lives on.
    #[test]
    fn new_app_with_auth_actually_compiles() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let out_dir = manifest_dir.join("target/tmp/new_app_auth_integration_test");

        if out_dir.exists() {
            fs::remove_dir_all(&out_dir).unwrap();
        }
        fs::create_dir_all(out_dir.parent().unwrap()).unwrap();

        new_app_from_workspace(
            out_dir.to_str().unwrap(),
            true,
            &local_workspace_root(),
            &[],
            false,
        )
        .unwrap();

        let cargo_toml_path = out_dir.join("Cargo.toml");
        let mut cargo_toml = fs::read_to_string(&cargo_toml_path).unwrap();
        assert!(
            cargo_toml.contains("\"reverb\""),
            "expected the generated Cargo.toml to enable the `reverb` \
             larust-support feature for an auth app, got:\n{cargo_toml}"
        );

        // Isolate from the outer workspace (see this test's own doc
        // comment) so `cargo build` treats it as a standalone crate.
        cargo_toml.push_str("\n[workspace]\nmembers = [\".\"]\n");
        fs::write(&cargo_toml_path, cargo_toml).unwrap();

        let status = std::process::Command::new("cargo")
            .args(["build", "--quiet"])
            .current_dir(&out_dir)
            .status()
            .unwrap();
        assert!(status.success(), "scaffolded --auth app failed to compile");

        fs::remove_dir_all(&out_dir).unwrap();
    }

    #[test]
    fn new_app_without_db_feature_wires_up_neither_the_cli_dispatch_nor_the_dashboard_route() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        let main_rs = fs::read_to_string(target.join("src/main.rs")).unwrap();
        assert!(!main_rs.contains("db:list"));
        let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
        assert!(!routes_web_rs.contains("DbPlugin"));
        let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
        assert!(
            !cargo_toml.contains("\"db\""),
            "Cargo.toml was: {cargo_toml}"
        );
    }

    #[test]
    fn new_app_with_db_feature_wires_up_dashboard_and_cli() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &["db"], false).unwrap();

        let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
        assert!(
            cargo_toml.contains("\"db\""),
            "Cargo.toml should turn on the db feature: {cargo_toml}"
        );

        let main_rs = fs::read_to_string(target.join("src/main.rs")).unwrap();
        assert!(
            main_rs.contains("db:list")
                && main_rs.contains("db:get")
                && main_rs.contains("db:put")
                && main_rs.contains("db:forget"),
            "main.rs should wire up all 4 db:* subcommands: {main_rs}"
        );
        assert!(
            !main_rs.contains("__DB_MAIN_RS_SNIPPET__"),
            "placeholder should be fully substituted"
        );
        // The 4 CLI-subcommand connects live in main.rs; the connect
        // immediately before `.with_sessions(...)` in the normal
        // HTTP-serving path lives in `lib.rs`'s `serve()` (a real bug this
        // session's own live sanity check caught: without it, every request
        // to `/__larust_db` 500s with "embedded db not connected", since
        // the serving process itself never touches the CLI-only connect
        // calls in main.rs).
        assert_eq!(
            main_rs.matches("larust_support::db::connect(").count(),
            4,
            "main.rs should connect the embedded db in each CLI arm: {main_rs}"
        );

        let lib_rs = fs::read_to_string(target.join("src/lib.rs")).unwrap();
        assert!(
            !lib_rs.contains("__DB_SERVE_SNIPPET__"),
            "placeholder should be fully substituted"
        );
        assert_eq!(
            lib_rs.matches("larust_support::db::connect(").count(),
            1,
            "lib.rs's serve() should connect the embedded db once, in the normal serve path: \
             {lib_rs}"
        );
        assert!(
            lib_rs.contains(
                "larust_support::db::connect(&paths().join(\"database/db.redb\")).await?;\n    let route = route"
            ),
            "the embedded db must be connected immediately before .with_sessions(...) runs in \
             serve(), not just inside main.rs's early-return CLI arms: {lib_rs}"
        );

        let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
        assert!(
            routes_web_rs.contains("larust_core::try_config().is_some_and(|c| c.app_debug)")
                && routes_web_rs.contains(".plugin(larust_support::db::DbPlugin)"),
            "routes/web.rs should register DbPlugin behind an app_debug gate: {routes_web_rs}"
        );
        assert!(
            !routes_web_rs.contains("__DB_ROUTE_SNIPPET__"),
            "placeholder should be fully substituted"
        );
    }

    /// Same "scratch-scaffold, compile, discard" technique as
    /// `new_app_with_auth_actually_compiles` (see its own doc comment) -
    /// this one specifically exercises the `db` optional feature's own
    /// scaffolding path (a real Cargo dependency on `larust-db`, plus the
    /// spliced `main.rs`/`routes/web.rs` snippets), which nothing else
    /// here proves actually compiles.
    #[test]
    fn new_app_with_db_actually_compiles() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let out_dir = manifest_dir.join("target/tmp/new_app_db_integration_test");

        if out_dir.exists() {
            fs::remove_dir_all(&out_dir).unwrap();
        }
        fs::create_dir_all(out_dir.parent().unwrap()).unwrap();

        new_app_from_workspace(
            out_dir.to_str().unwrap(),
            false,
            &local_workspace_root(),
            &["db"],
            false,
        )
        .unwrap();

        let cargo_toml_path = out_dir.join("Cargo.toml");
        let mut cargo_toml = fs::read_to_string(&cargo_toml_path).unwrap();

        // Isolate from the outer workspace so `cargo build` treats it as a
        // standalone crate - see `new_app_with_auth_actually_compiles`'s
        // own doc comment for why this is needed at all.
        cargo_toml.push_str("\n[workspace]\nmembers = [\".\"]\n");
        fs::write(&cargo_toml_path, cargo_toml).unwrap();

        let status = std::process::Command::new("cargo")
            .args(["build", "--quiet"])
            .current_dir(&out_dir)
            .status()
            .unwrap();
        assert!(status.success(), "scaffolded db app failed to compile");

        fs::remove_dir_all(&out_dir).unwrap();
    }

    /// The actual regression proof for the sqlx driver feature-gating
    /// cascade (`larust-support`'s `sqlite`/`mysql`/`postgres` features
    /// forwarding through `larust-orm`/`larust-cache`/`larust-http`/etc. -
    /// see `larust-orm/Cargo.toml`'s own `[features]` comment): a plain
    /// `xr new` (sqlite, the default, no other flags) must resolve
    /// `sqlx-mysql`/`sqlx-postgres` out of its dependency tree entirely,
    /// not just "fewer crates than before" (a fuzzy count would pass for
    /// unrelated reasons - this asserts the actual thing that changed).
    /// Only needs `cargo tree` (dependency resolution), not a full `cargo
    /// build` - meaningfully faster than the `_actually_compiles` tests
    /// above, so this isn't `#[ignore]`d.
    #[test]
    fn new_app_excludes_unused_sqlx_backends_from_its_dependency_tree() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let out_dir = manifest_dir.join("target/tmp/new_app_sqlx_tree_test");

        if out_dir.exists() {
            fs::remove_dir_all(&out_dir).unwrap();
        }
        fs::create_dir_all(out_dir.parent().unwrap()).unwrap();

        new_app_from_workspace(
            out_dir.to_str().unwrap(),
            false,
            &local_workspace_root(),
            &[],
            false,
        )
        .unwrap();

        let cargo_toml_path = out_dir.join("Cargo.toml");
        let mut cargo_toml = fs::read_to_string(&cargo_toml_path).unwrap();
        // Isolate from the outer workspace - see `new_app_with_auth_
        // actually_compiles`'s own doc comment for why this is needed.
        cargo_toml.push_str("\n[workspace]\nmembers = [\".\"]\n");
        fs::write(&cargo_toml_path, cargo_toml).unwrap();

        // No `--locked` - a freshly-scaffolded app has no `Cargo.lock` of
        // its own yet, so this genuinely needs to resolve fresh (exactly
        // the real-world scenario this test is proving something about).
        let output = std::process::Command::new("cargo")
            .args(["tree", "--edges", "normal"])
            .current_dir(&out_dir)
            .output();
        let output = match output {
            Ok(o) if o.status.success() => o,
            Ok(o) => {
                fs::remove_dir_all(&out_dir).unwrap();
                panic!("cargo tree failed: {}", String::from_utf8_lossy(&o.stderr));
            }
            Err(_) => {
                // Without a `Cargo.lock` yet, `cargo tree` needs to resolve
                // against crates.io - if this environment has no network
                // access at all, skip rather than fail the whole suite over
                // an environment limitation unrelated to what this test
                // actually checks.
                fs::remove_dir_all(&out_dir).unwrap();
                eprintln!("skipping: cargo tree could not run (no cargo on PATH?)");
                return;
            }
        };
        let tree = String::from_utf8_lossy(&output.stdout);

        assert!(
            tree.contains("sqlx-sqlite"),
            "the actually-selected driver must still be present: {tree}"
        );
        assert!(
            !tree.contains("sqlx-mysql") && !tree.contains("sqlx-postgres"),
            "a plain `xr new` (sqlite) must not pull in the unused mysql/postgres sqlx \
             backends:\n{tree}"
        );

        fs::remove_dir_all(&out_dir).unwrap();
    }

    #[test]
    fn new_app_creates_a_lib_rs_and_wires_main_rs_to_it_by_crate_name() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("my-blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        let lib_rs = fs::read_to_string(target.join("src/lib.rs")).unwrap();
        assert!(lib_rs.contains("pub mod controllers;"));
        assert!(lib_rs.contains("pub mod policies;"));

        let main_rs = fs::read_to_string(target.join("src/main.rs")).unwrap();
        // The app dir is named `my-blog` (a hyphen) - `main.rs` must
        // reference the underscored crate identifier `my_blog`, not the
        // literal package name, or `use my-blog::...` would be a syntax
        // error.
        assert!(
            main_rs.contains("my_blog::serve()") && main_rs.contains("my_blog::connect_database()"),
            "main.rs was: {main_rs}"
        );
        assert!(
            !main_rs.contains("__CRATE__"),
            "placeholder should be fully substituted"
        );

        // `routes::web::routes()` now lives in `lib.rs`'s own `router()`
        // function - internal to the library crate itself, so unqualified
        // (no `my_blog::` prefix, unlike main.rs's external reference).
        assert!(
            lib_rs.contains("routes::web::routes()"),
            "lib.rs was: {lib_rs}"
        );

        // Unlike `main.rs` (a separate binary crate that reaches the
        // library via the external `my_blog::` path), `routes/web.rs` is
        // compiled as *part of* the library crate itself (`lib.rs`'s
        // `#[path = "../routes/mod.rs"]`), so it must reach `controllers`
        // via `crate::`, never the external crate name - using the
        // external name there is a real compile error (verified: it broke
        // a fresh `cargo build` of a scaffolded app before this assertion
        // was added).
        let routes_web_rs = fs::read_to_string(target.join("routes/web.rs")).unwrap();
        assert!(
            routes_web_rs.contains("use crate::controllers::"),
            "routes/web.rs was: {routes_web_rs}"
        );
        assert!(
            !routes_web_rs.contains("__CRATE__") && !routes_web_rs.contains("my_blog::"),
            "routes/web.rs must never reference the external crate name - it's compiled as part \
             of the library crate itself: {routes_web_rs}"
        );
    }

    #[test]
    fn new_app_adds_larust_testing_as_a_dev_dependency() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("examples").join("blog");

        new_app_with_features(target.to_str().unwrap(), false, &[], false).unwrap();

        let cargo_toml = fs::read_to_string(target.join("Cargo.toml")).unwrap();
        assert!(cargo_toml.contains("[dev-dependencies]"));
        assert!(cargo_toml.contains("larust-testing"));
    }
}