autumn-macros 0.7.0

Proc macros for the Autumn web framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
//! Route macro implementation.
//!
//! Generates two companion functions for each annotated handler:
//!
//! 1. `__autumn_route_info_{name}()` — returns a `Route` (existing behaviour).
//! 2. `__autumn_path_{helper_name}(params…) -> String` — typed path helper
//!    that accepts one `impl Display` argument per `{param}` segment in the URL
//!    and returns the formatted absolute path string.
//!
//! The `helper_name` defaults to the handler function name but can be
//! overridden with the `name = "custom_name"` route attribute argument.
//!
//! [`ApiDoc`]: ../../autumn_web/openapi/struct.ApiDoc.html

use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{FnArg, LitStr, ReturnType, Type};

use crate::api_doc;
use crate::idempotency_guard::block_has_replay_guard;
use crate::parse;

/// Core implementation shared by all route macros (`#[get]`, `#[post]`, etc.).
///
/// `http_method` is the uppercase method name (e.g., `"GET"`).
/// `axum_fn` is the lowercase axum routing function name (e.g., `"get"`).
#[allow(clippy::too_many_lines)]
pub fn route_macro(
    http_method: &str,
    axum_fn: &str,
    attr: TokenStream,
    item: TokenStream,
) -> TokenStream {
    let route_args = match parse::parse_route_attr(attr) {
        Ok(a) => a,
        Err(err) => return err,
    };
    let path = route_args.path.clone();

    let mut input_fn = match parse::parse_async_handler(item) {
        Ok(f) => f,
        Err(err) => return err,
    };

    // Extract #[intercept(LayerType)] attributes from the handler.
    let interceptors = parse::extract_interceptors(&mut input_fn.attrs);

    // Extract #[api_doc(...)] overrides before emitting the function, so
    // the attribute doesn't leak onto the emitted fn definition and
    // trigger an "unknown attribute" error.
    let api_doc_attr = match api_doc::extract(&mut input_fn.attrs) {
        Ok(v) => v,
        Err(err) => return err,
    };

    // ── `#[edge]` opt-in (#1790) ────────────────────────────────
    // Detected before any code is generated so an ineligible route fails with
    // one purpose-written diagnostic instead of a wall of downstream type
    // errors from the emitted edge companion.
    let edge = crate::edge::detect(&input_fn);
    if let Some(marking) = edge
        && let Some(err) = reject_ineligible_edge_route(
            http_method,
            &input_fn,
            !interceptors.is_empty(),
            marking.span,
        )
    {
        return err;
    }

    let fn_name = &input_fn.sig.ident;
    let route_info_name = format_ident!("__autumn_route_info_{}", fn_name);
    let vis = &input_fn.vis;

    // Determine the path-helper name: use `name = "..."` override when set,
    // otherwise default to the handler function name.
    let helper_ident = route_args.helper_ident(fn_name);
    let path_helper_name = format_ident!("__autumn_path_{}", helper_ident);
    let fn_name_alias = emit_fn_name_alias(
        route_args.name_override.as_ref(),
        fn_name,
        &path_helper_name,
    );

    let method_const = format_ident!("{}", http_method); // e.g., GET
    let routing_fn = format_ident!("{}", axum_fn); // e.g., get

    // When #[feature_flag] is stacked, it prepends a gate parameter of type
    // `__AutumnFlagGate_{handler_name}` to the handler inputs. Since route macros
    // run before attribute macros lower down the chain, we must detect this attribute
    // and manually propagate the gate parameter to the primitive wrapper so that
    // the wrapper's call to the handler compiles.
    let has_feature_flag_attr = input_fn.attrs.iter().any(|a| {
        a.path()
            .segments
            .last()
            .is_some_and(|s| s.ident == "feature_flag")
    });
    // Body guards that rewrite the handler's return type to `Response` (and
    // inject hidden extractors): #[throttle], #[step_up], #[authorize], and
    // #[secured]. This route macro is outermost, so when one of these guards is
    // still present as an attribute it has not expanded yet — the signature we
    // see here still declares the original primitive return type, but the guard
    // will lower it to `Response`. Emitting the primitive `.to_string()` wrapper
    // (which calls the handler with only the user's original args and stringifies
    // the result) would then fail to compile, so skip it and route through the
    // normal `Response` path. (#[feature_flag] does NOT rewrite the return type;
    // it propagates its gate param instead, so the primitive wrapper is kept.)
    let has_response_rewriting_guard = has_throttle_guard(&input_fn)
        || has_step_up_guard(&input_fn)
        || has_secured_attr(&input_fn)
        || has_authorize_attr(&input_fn);
    let primitive_wrapper = if should_stringify_primitive_output(&input_fn.sig.output)
        && !has_response_rewriting_guard
    {
        let wrapper_name = format_ident!("__autumn_primitive_handler_{}", fn_name);
        let mut wrapper_inputs = Vec::new();
        let mut call_args = Vec::new();

        if has_feature_flag_attr {
            let gate_ident = format_ident!("__AutumnFlagGate_{}", fn_name);
            wrapper_inputs.push(quote! { __autumn_gate: #gate_ident });
            call_args.push(quote! { __autumn_gate });
        }

        for (idx, arg) in input_fn.sig.inputs.iter().enumerate() {
            match arg {
                FnArg::Typed(pat_type) => {
                    let arg_name = format_ident!("__autumn_arg_{idx}");
                    let ty = &pat_type.ty;
                    wrapper_inputs.push(quote! { #arg_name: #ty });
                    call_args.push(quote! { #arg_name });
                }
                FnArg::Receiver(receiver) => {
                    return syn::Error::new_spanned(
                        receiver,
                        "Autumn route handlers cannot take a self receiver",
                    )
                    .to_compile_error();
                }
            }
        }

        Some(quote! {
            #[doc(hidden)]
            async fn #wrapper_name(#(#wrapper_inputs),*) -> ::std::string::String {
                #fn_name(#(#call_args),*).await.to_string()
            }
        })
    } else {
        None
    };

    let handler_name = primitive_wrapper.as_ref().map_or_else(
        || fn_name.clone(),
        |_| format_ident!("__autumn_primitive_handler_{}", fn_name),
    );

    // ── Edge lane codegen (#1790) ───────────────────────────────
    // For an edge route every item that mentions `::autumn_web` is gated off
    // the wasm32 target (autumn-web is never compiled for wasm), while the
    // handler itself and the edge companion stay unconditional so one source
    // file serves both the origin binary and the capsule. For every other
    // route both values are empty and the expansion is unchanged.
    let (native_cfg, edge_companion) = emit_edge_items(edge, fn_name, &handler_name, vis, &path);

    // ── OpenAPI metadata ────────────────────────────────────────
    let path_params = api_doc::extract_path_params(&path.value());
    let path_params_tokens = api_doc::emit_path_param_slice(&path_params);
    let request_body = api_doc::schema_option(api_doc::infer_request_body(&input_fn));
    let response_body = api_doc::schema_option(api_doc::infer_response_body(&input_fn));
    let query_schema = api_doc::schema_option(api_doc::infer_query_params(&input_fn));
    let (secured, required_roles, required_scopes) = api_doc::extract_secured_info(&input_fn);
    let is_public = api_doc::is_public(&input_fn);
    let has_feature_flag = has_feature_flag_attr || has_expanded_feature_flag_gate(&input_fn);
    let body_guarded_replay = secured
        || has_authorize_guard(&input_fn)
        || has_feature_flag
        || has_step_up_guard(&input_fn)
        || has_throttle_guard(&input_fn);
    let intercepted_route = !interceptors.is_empty();
    let mut handler_expr = build_handler_expr(
        &routing_fn,
        &handler_name,
        &interceptors,
        !body_guarded_replay && !intercepted_route,
    );
    if edge.is_some() {
        // The wire runtime strips SENSITIVE_HEADERS before the capsule
        // dispatches, so the native mount must strip the same set before the
        // handler: otherwise a handler that reads `cookie`/`authorization`
        // through `HeaderMap` would serve different bytes at the origin than
        // at the edge. Route-local — middleware above the router still sees
        // the original request.
        handler_expr = quote! {
            #handler_expr.layer(::autumn_edge::reexports::axum::middleware::map_request(
                ::autumn_edge::strip_request_credentials,
            ))
        };
    }
    let route_idempotency = if intercepted_route {
        quote! { ::autumn_web::RouteIdempotency::Direct }
    } else {
        quote! { ::autumn_web::RouteIdempotency::ReplayThroughInner }
    };
    let api_doc_fields = api_doc_attr.emit_ident_fields(fn_name);
    let http_method_lit = LitStr::new(http_method, Span::call_site());
    let api_version_expr = route_args.api_version.as_ref().map_or_else(
        || quote! { ::core::option::Option::None },
        |lit| quote! { ::core::option::Option::Some(#lit) },
    );
    let sunset_opt_out_val = route_args.sunset_opt_out;
    let route_timeout = match route_args.timeout {
        crate::parse::RouteTimeoutAttr::Inherit => {
            quote! { ::autumn_web::RouteTimeout::Inherit }
        }
        crate::parse::RouteTimeoutAttr::Ms(ms) => {
            quote! {
                ::autumn_web::RouteTimeout::Override(
                    ::core::time::Duration::from_millis(#ms)
                )
            }
        }
        crate::parse::RouteTimeoutAttr::Disabled => {
            quote! { ::autumn_web::RouteTimeout::Disabled }
        }
    };
    let has_policy_val = has_policy_only(&input_fn);
    // Source order is preserved here on purpose: `ApiDoc` stays faithful to the
    // handler as written, and the route listing canonicalizes (sorts/dedupes)
    // when it projects these onto the wire.
    let authorize_bindings =
        api_doc::emit_authorize_binding_slice(&api_doc::extract_authorize_bindings(&input_fn));
    let seo_defaults = route_args.seo.emit();

    // ── Path helper ─────────────────────────────────────────────
    let path_helper = emit_path_helper(&path_helper_name, &path, &path_params);
    // The alias re-exports the (possibly gated) helper, so it carries the same
    // gate. An absent alias is an empty token stream — prefixing a `#[cfg]`
    // onto nothing would emit a dangling attribute.
    let fn_name_alias = if fn_name_alias.is_empty() {
        fn_name_alias
    } else {
        quote! { #native_cfg #fn_name_alias }
    };

    quote! {
        // ECHO-001: We want to apply #[axum::debug_handler] but without forcing the user
        // to import axum manually. However, the path resolution in Axum macros makes this impossible
        // natively. Custom compile errors handle the type checks.
        #input_fn
        #primitive_wrapper

        #native_cfg
        #[doc(hidden)]
        #vis fn #route_info_name() -> ::autumn_web::Route {
            ::autumn_web::Route {
                method: ::autumn_web::reexports::http::Method::#method_const,
                path: #path,
                handler: #handler_expr,
                name: ::core::stringify!(#fn_name),
                api_version: #api_version_expr,
                sunset_opt_out: #sunset_opt_out_val,
                api_doc: ::autumn_web::openapi::ApiDoc {
                    method: #http_method_lit,
                    path: #path,
                    path_params: #path_params_tokens,
                    request_body: #request_body,
                    response: #response_body,
                    query_schema: #query_schema,
                    secured: #secured,
                    required_roles: #required_roles,
                    required_scopes: #required_scopes,
                    register_schemas: ::core::option::Option::None,
                    api_version: #api_version_expr,
                    sunset_opt_out: #sunset_opt_out_val,
                    has_policy: #has_policy_val,
                    authorize_bindings: #authorize_bindings,
                    public: #is_public,
                    module_path: ::core::module_path!(),
                    source_file: ::core::file!(),
                    source_line: ::core::line!(),
                    #api_doc_fields
                },
                repository: ::core::option::Option::None,
                idempotency: #route_idempotency,
                timeout: #route_timeout,
                seo: #seo_defaults,
            }
        }

        #native_cfg
        #path_helper
        #fn_name_alias

        #edge_companion
    }
}

/// Compile error for `#[edge]` on a route the edge lane cannot serve.
const EDGE_METHOD_ERROR: &str = "`#[edge]` is only supported on `#[get]` routes; \
                                 the edge lane is read-path only (issue #1790)";

/// Compile error for `#[edge]` stacked with an auth or rate guard.
const EDGE_GUARD_ERROR: &str = "`#[edge]` cannot be combined with \
                                `#[secured]`/`#[authorize]`/`#[step_up]`/`#[throttle]` — the edge \
                                capsule has no session or auth state; serve this route from the \
                                origin";

/// Compile error for `#[edge]` stacked with `#[intercept(...)]`.
const EDGE_INTERCEPT_ERROR: &str = "`#[edge]` cannot be combined with `#[intercept(...)]` — \
                                    interceptor layers are origin-only tower middleware and are \
                                    not carried into the edge capsule, so the two lanes would \
                                    serve different bytes; serve this route from the origin";

/// Compile error for an `#[edge]` handler taking `Extension<T>`.
const EDGE_EXTENSION_ERROR: &str = "`#[edge]` handlers cannot take `Extension<...>` — the \
                                    capsule installs no request extensions (the `EdgeCache` seam \
                                    is the one mediated capability), so a missing extension \
                                    would be served as a 500 instead of falling through; use \
                                    `EdgeCache`, or serve this route from the origin";

/// Marker consts the auth/rate guards inject into a handler body. A guard that
/// expanded *before* this route macro left one of these behind instead of an
/// attribute, and missing it would ship a guarded route to the unauthenticated
/// edge lane.
const GUARD_MARKERS: &[&str] = &[
    "__AUTUMN_SECURED_ROLES",
    "__AUTUMN_SECURED_SCOPES",
    "__AUTUMN_STEP_UP_MAX_AGE",
    "__AUTUMN_THROTTLE_ROUTE_ID",
    "__AUTUMN_AUTHORIZE_BINDINGS",
];

/// Reject an `#[edge]` route the edge lane cannot serve, spanning the error at
/// the `#[edge]` attribute (or the handler name once it has expanded).
fn reject_ineligible_edge_route(
    http_method: &str,
    input_fn: &syn::ItemFn,
    has_interceptors: bool,
    span: Span,
) -> Option<TokenStream> {
    if http_method != "GET" {
        return Some(syn::Error::new(span, EDGE_METHOD_ERROR).to_compile_error());
    }
    if has_auth_or_rate_guard(input_fn) {
        return Some(syn::Error::new(span, EDGE_GUARD_ERROR).to_compile_error());
    }
    // `#[intercept(...)]` attrs were already stripped off `input_fn` by
    // `parse::extract_interceptors`, so the caller passes the extracted list's
    // emptiness instead of this fn re-scanning attributes.
    if has_interceptors {
        return Some(syn::Error::new(span, EDGE_INTERCEPT_ERROR).to_compile_error());
    }
    if has_extension_param(input_fn) {
        return Some(syn::Error::new(span, EDGE_EXTENSION_ERROR).to_compile_error());
    }
    None
}

/// Whether any parameter's type names `Extension` — `Extension<T>`,
/// `axum::Extension<T>`, or nested as `Option<Extension<T>>`.
///
/// `Extension` satisfies axum's `Handler<_, EdgeState>` bound for *any* state,
/// so the type system alone cannot keep it out of the edge lane; this
/// syntactic check is the enforcement point. A type alias that hides the name
/// is not resolved — the same recognition limit every source-level check in
/// this crate documents.
fn has_extension_param(input_fn: &syn::ItemFn) -> bool {
    input_fn.sig.inputs.iter().any(|arg| {
        let syn::FnArg::Typed(pat_type) = arg else {
            return false;
        };
        tokens_contain_ident(&quote! { #pat_type }, "Extension")
    })
}

/// Whether `stream` contains `needle` as an exact identifier, at any nesting.
fn tokens_contain_ident(stream: &TokenStream, needle: &str) -> bool {
    stream.clone().into_iter().any(|tree| match tree {
        proc_macro2::TokenTree::Ident(ident) => ident == needle,
        proc_macro2::TokenTree::Group(group) => tokens_contain_ident(&group.stream(), needle),
        _ => false,
    })
}

/// Whether an auth or rate guard is declared on the handler, in either
/// attribute order: still a live attribute, or already expanded into the marker
/// const it injects.
fn has_auth_or_rate_guard(input_fn: &syn::ItemFn) -> bool {
    has_secured_attr(input_fn)
        || has_authorize_attr(input_fn)
        || has_step_up_guard(input_fn)
        || has_throttle_guard(input_fn)
        || GUARD_MARKERS
            .iter()
            .any(|marker| crate::edge::stmts_have_marker(&input_fn.block.stmts, marker))
}

/// Build the wasm32 gate and the edge companion for an `#[edge]` route.
///
/// Returns two empty token streams for every other route, which keeps the
/// expansion of a non-edge route byte-identical to what it was before the edge
/// lane existed.
fn emit_edge_items(
    edge: Option<crate::edge::EdgeMarking>,
    fn_name: &proc_macro2::Ident,
    handler_name: &proc_macro2::Ident,
    vis: &syn::Visibility,
    path: &LitStr,
) -> (TokenStream, TokenStream) {
    let Some(marking) = edge else {
        return (TokenStream::new(), TokenStream::new());
    };

    let needs = if marking.needs_kv {
        quote! { &[::autumn_edge::EdgeCapability::Kv] }
    } else {
        quote! { &[] }
    };
    let edge_route_name = format_ident!("__autumn_edge_route_{}", fn_name);

    (
        quote! { #[cfg(not(target_arch = "wasm32"))] },
        quote! {
            #[doc(hidden)]
            #vis fn #edge_route_name() -> ::autumn_edge::EdgeRoute {
                ::autumn_edge::EdgeRoute {
                    method: ::autumn_edge::reexports::http::Method::GET,
                    path: #path,
                    // The same handler axum mounts natively — including the
                    // primitive-output wrapper when there is one. Everything
                    // else the native mount can wrap around a handler
                    // (`#[intercept]` layers, auth guards) is refused for edge
                    // routes by `reject_ineligible_edge_route`, so the two
                    // lanes cannot diverge on how a response is produced.
                    handler: ::autumn_edge::edge_get(#handler_name),
                    name: ::core::stringify!(#fn_name),
                    needs: #needs,
                }
            }
        },
    )
}

/// Build the axum handler expression, applying interceptor layers in reverse
/// attribute order so the first `#[intercept(...)]` is the outermost layer.
fn build_handler_expr(
    routing_fn: &proc_macro2::Ident,
    handler_name: &proc_macro2::Ident,
    interceptors: &[syn::Path],
    include_replay_layer: bool,
) -> TokenStream {
    let mut expr = quote! { ::autumn_web::reexports::axum::routing::#routing_fn(#handler_name) };
    if include_replay_layer {
        expr = quote! {
            ::autumn_web::reexports::axum::routing::MethodRouter::<
                ::autumn_web::AppState, ::core::convert::Infallible
            >::layer(#expr, ::autumn_web::idempotency::IdempotencyReplayLayer)
        };
    }
    for interceptor in interceptors.iter().rev() {
        // Explicit type annotation avoids inference ambiguity with chained .layer() calls.
        expr = quote! {
            ::autumn_web::reexports::axum::routing::MethodRouter::<
                ::autumn_web::AppState, ::core::convert::Infallible
            >::layer(#expr, #interceptor)
        };
    }
    expr
}

fn has_authorize_guard(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "authorize")
    }) || block_has_replay_guard(&input_fn.block)
        || crate::api_doc::has_policy_check_in_stmts(&input_fn.block.stmts)
}

fn has_step_up_guard(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "step_up")
    })
}

fn has_throttle_guard(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "throttle")
    })
}

/// Whether a `#[secured]` attribute is still present on the handler (i.e. it has
/// not expanded yet because this route macro is outermost). Used to disable the
/// primitive-output wrapper, since `#[secured]` rewrites the return type to
/// `Response`.
fn has_secured_attr(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "secured")
    })
}

/// Whether an `#[authorize]` attribute is still present on the handler. Used to
/// disable the primitive-output wrapper, since `#[authorize]` rewrites the
/// return type to `Response`. This is intentionally narrower than
/// [`has_authorize_guard`], which also matches inline policy checks that do not
/// rewrite the return type.
fn has_authorize_attr(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "authorize")
    })
}

fn has_policy_only(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "authorize")
    }) || crate::api_doc::has_policy_check_in_stmts(&input_fn.block.stmts)
}

fn has_expanded_feature_flag_gate(input_fn: &syn::ItemFn) -> bool {
    input_fn.sig.inputs.iter().any(|arg| {
        let FnArg::Typed(pat_type) = arg else {
            return false;
        };
        let Type::Path(type_path) = pat_type.ty.as_ref() else {
            return false;
        };
        let Some(last_segment) = type_path.path.segments.last() else {
            return false;
        };
        last_segment
            .ident
            .to_string()
            .starts_with("__AutumnFlagGate_")
    })
}

/// When a `name = "..."` override is active, emit a `pub use` alias for the
/// handler's own function name so that `paths![fn_name]` resolves alongside
/// the override's `paths![custom_name]`.
fn emit_fn_name_alias(
    name_override: Option<&syn::LitStr>,
    fn_name: &proc_macro2::Ident,
    path_helper_name: &proc_macro2::Ident,
) -> TokenStream {
    let fn_path_helper_name = format_ident!("__autumn_path_{}", fn_name);
    if name_override.is_some() && fn_path_helper_name != *path_helper_name {
        quote! {
            #[doc(hidden)]
            pub use self::#path_helper_name as #fn_path_helper_name;
        }
    } else {
        quote! {}
    }
}

/// Emit the typed path helper function.
///
/// For `/posts/{id}/comments/{comment_id}` this emits:
/// ```ignore
/// pub fn __autumn_path_handler(id: impl Display, comment_id: impl Display) -> String {
///     format!("/posts/{}/comments/{}", id, comment_id)
/// }
/// ```
///
/// Helpers are always emitted as `pub` regardless of handler visibility so
/// that `paths![]` can re-export them without hitting E0364.
///
/// Positional `{}` placeholders are used (rather than named captures) so that
/// route params whose names are Rust keywords — e.g. `/{type}` or `/{match}` —
/// do not produce invalid `format!` invocations. Parameter idents are emitted
/// as raw identifiers (`r#type`) so they are valid in the function signature.
fn emit_path_helper(
    helper_name: &proc_macro2::Ident,
    path: &LitStr,
    params: &[String],
) -> TokenStream {
    // Build parameter idents: strip `*` catch-all prefix, replace `-` → `_`,
    // then emit as raw identifiers so Rust keywords are valid param names.
    let param_idents: Vec<proc_macro2::Ident> = params
        .iter()
        .map(|p| {
            let sanitized = p.trim_start_matches('*').replace('-', "_");
            proc_macro2::Ident::new_raw(&sanitized, proc_macro2::Span::call_site())
        })
        .collect();

    // Build a positional format string: each `{param}` / `{param:regex}` → `{}`.
    // Positional placeholders avoid named-capture errors when param names are
    // Rust keywords (you cannot write `format!("{type}")` in generated code).
    let format_str = positional_format_string(&path.value());
    let format_lit = LitStr::new(&format_str, path.span());
    let encoded_params: Vec<TokenStream> = params
        .iter()
        .zip(param_idents.iter())
        .map(|(param, ident)| {
            if param.starts_with('*') {
                quote! { ::autumn_web::paths::encode_catch_all_param(#ident) }
            } else {
                quote! { ::autumn_web::paths::encode_path_segment(#ident) }
            }
        })
        .collect();

    quote! {
        #[doc(hidden)]
        pub fn #helper_name(#(#param_idents: impl ::std::fmt::Display),*) -> ::std::string::String {
            format!(#format_lit, #(#encoded_params),*)
        }
    }
}

/// Replace every `{...}` placeholder in a route path with `{}` (positional).
///
/// Handles nested braces from regex quantifiers like `{id:[0-9]{1,3}}` by
/// tracking brace depth, so the outer `{...}` is consumed correctly.
/// Escaped braces (`{{` / `}}`) are passed through unchanged as literal
/// format-string escapes representing a single `{` or `}` in the output.
fn positional_format_string(path: &str) -> String {
    let mut result = String::with_capacity(path.len());
    let mut chars = path.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '{' if chars.peek() == Some(&'{') => {
                // Escaped literal brace `{{` — pass through for format string.
                chars.next();
                result.push_str("{{");
            }
            '{' => {
                // Path parameter — emit positional placeholder and skip contents.
                result.push_str("{}");
                let mut depth: u32 = 1;
                for inner in chars.by_ref() {
                    match inner {
                        '{' => depth += 1,
                        '}' => {
                            depth -= 1;
                            if depth == 0 {
                                break;
                            }
                        }
                        _ => {}
                    }
                }
            }
            '}' if chars.peek() == Some(&'}') => {
                // Escaped closing brace `}}` — pass through.
                chars.next();
                result.push_str("}}");
            }
            _ => result.push(c),
        }
    }
    result
}

/// Whether a route handler's declared return type is a bare numeric/bool
/// primitive that Autumn serves by stringifying it (primitives do not implement
/// axum's `IntoResponse`). Shared with the `#[throttle]` macro so a throttled
/// primitive-returning handler stringifies its result the same way the plain
/// primitive-output wrapper does.
pub fn should_stringify_primitive_output(output: &ReturnType) -> bool {
    let ReturnType::Type(_, ty) = output else {
        return false;
    };

    let Type::Path(path) = ty.as_ref() else {
        return false;
    };

    if path.qself.is_some() || path.path.segments.len() != 1 {
        return false;
    }

    let ident = path.path.segments[0].ident.to_string();
    matches!(
        ident.as_str(),
        "bool"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "isize"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "usize"
            | "f32"
            | "f64"
    )
}

#[cfg(test)]
mod tests {
    use quote::quote;

    use super::{positional_format_string, route_macro};

    #[test]
    fn positional_plain_params() {
        assert_eq!(positional_format_string("/posts/{id}"), "/posts/{}");
    }

    #[test]
    fn positional_regex_constrained_params() {
        assert_eq!(positional_format_string("/users/{id:[0-9]+}"), "/users/{}");
    }

    #[test]
    fn positional_multiple_params() {
        assert_eq!(
            positional_format_string("/posts/{year}/{slug}"),
            "/posts/{}/{}"
        );
    }

    #[test]
    fn positional_static_path() {
        assert_eq!(positional_format_string("/hello"), "/hello");
    }

    #[test]
    fn positional_catch_all_param() {
        assert_eq!(positional_format_string("/files/{*path}"), "/files/{}");
    }

    #[test]
    fn positional_hyphenated_param() {
        assert_eq!(positional_format_string("/items/{item-id}"), "/items/{}");
    }

    #[test]
    fn positional_regex_with_quantifier_braces() {
        // Regex quantifiers like {1,3} must not end the outer capture early.
        assert_eq!(
            positional_format_string("/users/{id:[0-9]{1,3}}"),
            "/users/{}"
        );
    }

    #[test]
    fn positional_keyword_param() {
        // Keyword params like `type` must produce a valid positional placeholder.
        assert_eq!(positional_format_string("/items/{type}"), "/items/{}");
    }

    #[test]
    fn positional_escaped_braces_pass_through() {
        // `{{` / `}}` are literal braces in the route, not parameters.
        assert_eq!(positional_format_string("/{{hello}}"), "/{{hello}}");
        // Escaped brace followed by a real param.
        assert_eq!(
            positional_format_string("/{{literal}}/{id}"),
            "/{{literal}}/{}"
        );
    }

    #[test]
    fn route_macro_string_literal_replay_guard_still_injects_layer() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                async fn create_item() -> &'static str {
                    let _ = "__AUTUMN_IDEMPOTENCY_REPLAY_GUARD";
                    "created"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("IdempotencyReplayLayer"),
            "plain handler text must not be mistaken for a generated replay stop: {generated}"
        );
    }

    #[test]
    fn route_macro_interceptor_uses_direct_idempotency() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                #[intercept(TenantLayer)]
                async fn create_item() -> &'static str {
                    "created"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteIdempotency :: Direct"),
            "intercepted routes must fail closed when replay scope is not explicit: {generated}"
        );
        assert!(
            !generated.contains("IdempotencyReplayLayer"),
            "intercepted routes must not advertise an implicit replay stop: {generated}"
        );
    }

    #[test]
    fn route_macro_suppresses_replay_layer_when_throttle_attribute_present() {
        // Ordering A: `#[post]` outermost, `#[throttle]` still an attribute below
        // it. The route macro detects the attribute (`has_throttle_guard`) and
        // must NOT add the outer IdempotencyReplayLayer — replay handling moves
        // into the (later-expanded) throttle body, after the throttle check.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                #[throttle(limit = 1, per = "60s", key = "ip")]
                async fn create_item() -> &'static str { "created" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("IdempotencyReplayLayer"),
            "throttled route (route outermost) must not add the outer replay layer: {generated}"
        );
    }

    #[test]
    fn route_macro_suppresses_replay_layer_for_expanded_throttle_prologue() {
        // Ordering B: `#[throttle]` written ABOVE `#[post]`, so the throttle macro
        // expands FIRST — it removes its own attribute and injects the throttle
        // prologue into the body. The route macro no longer sees a `#[throttle]`
        // attribute and must instead recognize the generated throttle prologue in
        // the body to suppress the outer IdempotencyReplayLayer; otherwise a
        // cached replay would be served before the in-body throttle check.
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 1, per = "60s", key = "ip" },
            quote! {
                async fn create_item() -> &'static str { "created" }
            },
        );
        let generated = route_macro("POST", "post", quote! { "/items" }, throttled).to_string();

        assert!(
            !generated.contains("IdempotencyReplayLayer"),
            "throttled route (throttle expanded first) must not add the outer replay layer: \
             {generated}"
        );
    }

    #[test]
    fn route_macro_parses_api_version_and_sunset_opt_out() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/items", api_version = "v1", sunset_opt_out = true },
            quote! {
                async fn get_items() -> &'static str {
                    "items"
                }
            },
        )
        .to_string();

        // Check that api_version and sunset_opt_out are generated in Route constructor
        assert!(
            generated.contains("api_version"),
            "should generate api_version field: {generated}"
        );
        assert!(
            generated.contains("sunset_opt_out"),
            "should generate sunset_opt_out field: {generated}"
        );
    }

    #[test]
    fn route_macro_defaults_timeout_to_inherit() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/items" },
            quote! {
                async fn get_items() -> &'static str { "items" }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteTimeout :: Inherit"),
            "routes without a timeout attribute must inherit the global deadline: {generated}"
        );
    }

    #[test]
    fn route_macro_parses_timeout_ms_override() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/export", timeout_ms = 120000 },
            quote! {
                async fn export() -> &'static str { "report" }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteTimeout :: Override"),
            "timeout_ms must emit a RouteTimeout::Override: {generated}"
        );
        assert!(
            generated.contains("from_millis") && generated.contains("120000"),
            "override must carry the configured millisecond budget: {generated}"
        );
    }

    #[test]
    fn route_macro_defaults_public_false() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/widgets" },
            quote! { async fn create_widget() -> &'static str { "ok" } },
        )
        .to_string();
        assert!(
            generated.contains("public : false"),
            "an unannotated route must record public = false: {generated}"
        );
        // The handler's module path is captured for audit diagnostics.
        assert!(generated.contains("module_path"));
    }

    #[test]
    fn route_macro_marks_public_when_public_attribute_present() {
        // Ordering A: `#[post]` outermost, `#[public]` still an attribute below.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/pricing" },
            quote! {
                #[public]
                async fn pricing() -> &'static str { "free" }
            },
        )
        .to_string();
        assert!(
            generated.contains("public : true"),
            "a #[public] handler must record public = true: {generated}"
        );
    }

    #[test]
    fn route_macro_marks_public_from_expanded_marker() {
        // Ordering B: `#[public]` written above `#[post]`, so it expands first and
        // injects the `__AUTUMN_PUBLIC` marker into the body; the route macro must
        // recognize the marker.
        let public_fn = crate::public::public_macro(
            quote! {},
            quote! { async fn pricing() -> &'static str { "free" } },
        );
        let generated = route_macro("POST", "post", quote! { "/pricing" }, public_fn).to_string();
        assert!(
            generated.contains("public : true"),
            "a route macro over an expanded #[public] marker must record public = true: {generated}"
        );
    }

    // ── seo(...) route-level defaults (#1182) ───────────────────────────────

    #[test]
    fn route_macro_defaults_seo_to_empty() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("SeoRouteDefaults :: EMPTY"),
            "a route without seo(...) must record the empty defaults: {generated}"
        );
    }

    #[test]
    fn route_macro_emits_declared_seo_defaults() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "About", description = "Learn about us") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("with_title (\"About\")"),
            "seo(title = ...) must populate the title default: {generated}"
        );
        assert!(
            generated.contains("with_description (\"Learn about us\")"),
            "seo(description = ...) must populate the description default: {generated}"
        );
        assert!(
            generated.contains("SeoRouteDefaults :: EMPTY . with_title"),
            "unset seo keys must fall back to the empty defaults: {generated}"
        );
    }

    #[test]
    fn route_macro_seo_composes_with_other_keys() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "About"), name = "about_page", timeout_ms = 500 },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("with_title (\"About\")"),
            "seo(...) must parse when it precedes other keys: {generated}"
        );
        assert!(
            generated.contains("RouteTimeout :: Override"),
            "keys after seo(...) must still parse: {generated}"
        );
        assert!(
            generated.contains("__autumn_path_about_page"),
            "name override after seo(...) must still apply: {generated}"
        );
    }

    #[test]
    fn route_macro_never_emits_a_seo_struct_literal() {
        // The expansion lands in the *user's* crate, so a struct literal there
        // would pin `SeoRouteDefaults` as exhaustively constructible forever —
        // a fourteenth SEO key could then never be added without a breaking
        // change — and would trip `clippy::needless_update` once every key is
        // spelled out. Chained `const fn` setters avoid both.
        let generated = route_macro(
            "GET",
            "get",
            quote! {
                "/full",
                seo(
                    title = "t",
                    description = "d",
                    canonical = "c",
                    og_title = "ot",
                    og_description = "od",
                    og_image = "oi",
                    og_type = "oty",
                    og_url = "ou",
                    twitter_card = "tc",
                    twitter_title = "tt",
                    twitter_description = "td",
                    twitter_image = "ti",
                    robots = "noindex"
                )
            },
            quote! { async fn full() -> &'static str { "full" } },
        )
        .to_string();

        assert!(
            generated.contains("with_robots (\"noindex\")"),
            "every declared key must still be emitted: {generated}"
        );
        assert!(
            !generated.contains("SeoRouteDefaults {"),
            "the expansion must not construct SeoRouteDefaults by struct literal: {generated}"
        );
        // Scoped to the emitted `seo:` value. The surrounding expansion
        // legitimately contains `..Default::default()` in other literals, so
        // asserting over the whole token stream would be a trap for future
        // edits (the `#[static_get]` expansion already trips it).
        let seo_value = generated
            .split("seo : ")
            .nth(1)
            .and_then(|rest| rest.split(',').next())
            .expect("expansion should assign the seo field");
        assert!(
            seo_value.contains("SeoRouteDefaults :: EMPTY"),
            "sanity: seo value should build from EMPTY: {seo_value}"
        );
        assert!(
            !seo_value.contains(".."),
            "the seo value must not use struct-update syntax: {seo_value}"
        );
    }

    #[test]
    fn route_macro_rejects_empty_seo_group() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo() },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "an empty seo() must be a compile error, not a silent no-op: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_repeated_seo_argument() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "A"), seo(og_type = "website") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a second seo(...) argument must be a compile error: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_seo_keys_without_separating_comma() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "A" og_type = "website") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a missing comma must be rejected rather than dropping later keys: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_unknown_seo_key() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(titel = "About") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "an unknown seo key must be a compile error: {generated}"
        );
        assert!(
            generated.contains("titel"),
            "the error must name the offending key: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_duplicate_seo_key() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "A", title = "B") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a duplicate seo key must be a compile error: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_non_string_seo_value() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = 42) },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a non-string seo value must be a compile error: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_seo_without_parentheses() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo = "title" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "`seo = ...` must be rejected in favour of `seo(...)`: {generated}"
        );
    }

    #[test]
    fn route_macro_parses_timeout_off_disabled() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stream", timeout = "off" },
            quote! {
                async fn stream() -> &'static str { "data" }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteTimeout :: Disabled"),
            "timeout = \"off\" must emit RouteTimeout::Disabled: {generated}"
        );
    }

    // ── #[authorize] bindings recorded in ApiDoc (#1627) ────────────────────

    #[test]
    fn route_macro_emits_empty_authorize_bindings_by_default() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/widgets" },
            quote! { async fn create_widget() -> &'static str { "ok" } },
        )
        .to_string();

        assert!(
            generated.contains("authorize_bindings : & []"),
            "an unguarded route must record no authorization bindings: {generated}"
        );
    }

    #[test]
    fn route_macro_records_authorize_binding_when_attribute_present() {
        // Ordering A: `#[post]` outermost, `#[authorize]` still an attribute
        // below it, so the route macro reads the arguments straight off the
        // unexpanded attribute.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/notes/{id}" },
            quote! {
                #[authorize("update", resource = Note)]
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        )
        .to_string();

        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "an #[authorize] attribute must record its (action, resource) binding: {generated}"
        );
    }

    #[test]
    fn route_macro_records_authorize_binding_from_expanded_marker() {
        // Ordering B: `#[authorize]` written ABOVE `#[post]`, so it expands
        // first, removes its own attribute and leaves only the generated body.
        // The binding must survive in the marker const it injects.
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let generated =
            route_macro("POST", "post", quote! { "/notes/{id}" }, authorized).to_string();

        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "an already-expanded #[authorize] must still record its binding: {generated}"
        );
    }

    #[test]
    fn route_macro_records_authorize_binding_under_secured_wrapper() {
        // `#[authorize]` above `#[secured]` above `#[post]`: authorize expands
        // first, then secured wraps that whole body in
        // `(async move { … }).await`, burying the marker one level down. The
        // walk must descend the generated wrapper instead of stopping at the
        // outermost statement list.
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let secured = crate::secured::secured_macro(quote! { "admin" }, authorized);
        let generated = route_macro("POST", "post", quote! { "/notes/{id}" }, secured).to_string();

        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "a binding nested inside a #[secured] wrapper must not be lost: {generated}"
        );
    }

    #[test]
    fn route_macro_records_all_bindings_for_stacked_authorize_attributes() {
        // Every attribute contributes: the existing `policy` boolean collapses
        // N bindings into one flag, so the list must not do the same.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/notes/{id}" },
            quote! {
                #[authorize("update", resource = Note)]
                #[authorize("publish", resource = Note)]
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        )
        .to_string();

        let update = generated
            .find(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#)
            .unwrap_or_else(|| {
                panic!("the first stacked #[authorize] must record a binding: {generated}")
            });
        let publish = generated
            .find(r#"AuthorizeBinding { action : "publish" , resource : "Note" }"#)
            .unwrap_or_else(|| {
                panic!("the second stacked #[authorize] must record a binding: {generated}")
            });
        assert!(
            update < publish,
            "stacked bindings must be recorded in source order: {generated}"
        );
    }

    #[test]
    fn route_macro_preserves_secured_roles_when_authorize_wraps_them() {
        // `#[secured("admin")]` above `#[authorize]` above `#[post]`: secured
        // expands first and leaves its role marker in the body; authorize then
        // wraps that body in `let __autumn_inner: T = (async move { … }).await;`.
        // The roles walk must descend that generated wrapper — otherwise the
        // route silently reports `required_roles: &[]` and a `provable` manifest
        // dimension under-states the posture.
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let authorized =
            crate::authorize::authorize_macro(quote! { "update", resource = Note }, secured);
        let generated =
            route_macro("POST", "post", quote! { "/notes/{id}" }, authorized).to_string();

        assert!(
            generated.contains(r#"required_roles : & ["admin"]"#),
            "roles from a #[secured] buried under an #[authorize] wrapper must survive: \
             {generated}"
        );
        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "…and the authorize binding must be recorded alongside them: {generated}"
        );
    }

    #[test]
    fn route_macro_preserves_secured_roles_when_authorize_is_still_an_attribute() {
        // The remaining ordering of {secured, route, authorize}: `#[secured]`
        // ABOVE `#[post]` (already expanded into markers) with `#[authorize]`
        // BELOW it (still a live attribute). The marker read must not be
        // short-circuited by the live-authorize fallback — both idioms are the
        // documented house style, and losing the roles here means deleting the
        // `#[secured(...)]` line produces zero manifest diff on a `provable`
        // dimension.
        let secured = crate::secured::secured_macro(
            quote! { "admin", scopes = ["notes:write"] },
            quote! {
                #[authorize("update", resource = Note)]
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let generated = route_macro("POST", "post", quote! { "/notes/{id}" }, secured).to_string();

        assert!(
            generated.contains(r#"required_roles : & ["admin"]"#),
            "roles from an expanded #[secured] must survive a live #[authorize] attribute: \
             {generated}"
        );
        assert!(
            generated.contains(r#"required_scopes : & ["notes:write"]"#),
            "scopes must survive alongside the roles: {generated}"
        );
        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "…and the authorize binding must be recorded alongside them: {generated}"
        );
    }

    #[test]
    fn route_macro_orders_marker_binding_before_live_attribute() {
        // Mixed arrangement: `#[authorize(A)]` ABOVE `#[post]` (already
        // expanded into a marker by the time the route macro runs) and
        // `#[authorize(B)]` BELOW it (still a live attribute). A is higher in
        // the source than B, so the recorded order must be [A, B] — the marker
        // before the attribute, not the collection-mechanism order.
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let mixed = quote! {
            #[authorize("publish", resource = Note)]
            #authorized
        };
        let generated = route_macro("POST", "post", quote! { "/notes/{id}" }, mixed).to_string();

        let update = generated
            .find(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#)
            .unwrap_or_else(|| panic!("the marker binding must be recorded: {generated}"));
        let publish = generated
            .find(r#"AuthorizeBinding { action : "publish" , resource : "Note" }"#)
            .unwrap_or_else(|| panic!("the live-attribute binding must be recorded: {generated}"));
        assert!(
            update < publish,
            "the marker comes from the attribute above the route macro, so it precedes the \
             live attribute below it in source order: {generated}"
        );
    }

    // ── `#[edge]` opt-in (#1790) ────────────────────────────────────────────

    /// The edge companion is emitted last, so everything from its `fn` keyword
    /// to the end of the stream *is* the companion. Comparing that slice across
    /// two attribute stackings proves detection produced the same route, not
    /// merely that both stackings emitted *something*.
    fn edge_companion_fragment(generated: &str) -> &str {
        let start = generated
            .find("fn __autumn_edge_route_")
            .unwrap_or_else(|| panic!("expansion should emit an edge companion: {generated}"));
        &generated[start..]
    }

    #[test]
    fn route_macro_edge_get_emits_edge_companion() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        assert!(
            generated.contains("fn __autumn_edge_route_greet () -> :: autumn_edge :: EdgeRoute"),
            "an #[edge] GET route must emit the edge companion: {generated}"
        );
        assert!(
            generated.contains(":: autumn_edge :: edge_get (greet)"),
            "the edge companion must adapt the handler through edge_get: {generated}"
        );
        assert!(
            generated.contains(":: autumn_edge :: reexports :: http :: Method :: GET"),
            "the edge companion must carry the GET method: {generated}"
        );
        assert!(
            generated.contains("path : \"/greet\""),
            "the edge companion must carry the route path: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_companion_mounts_the_primitive_wrapper() {
        // A primitive-returning handler is mounted natively through a
        // `.to_string()` wrapper (primitives are not `IntoResponse`). The edge
        // companion must mount the *same* wrapper, or the two lanes would
        // disagree about what the response body is — and `edge_get(stats)`
        // would not even compile.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stats" },
            quote! {
                #[edge]
                async fn stats() -> usize { 42 }
            },
        )
        .to_string();

        assert!(
            generated.contains(":: autumn_edge :: edge_get (__autumn_primitive_handler_stats)"),
            "the edge companion must mount the primitive wrapper: {generated}"
        );
        // …and that wrapper is pure std, so it stays available on wasm32.
        let wrapper = generated
            .find("async fn __autumn_primitive_handler_stats")
            .unwrap_or_else(|| panic!("the primitive wrapper must be emitted: {generated}"));
        assert!(
            !generated[..wrapper].contains("cfg"),
            "the primitive wrapper references no autumn_web item, so it is not gated: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_cfg_gates_native_companions() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts/{id}" },
            quote! {
                #[edge]
                async fn show(id: Path<String>) -> &'static str { "post" }
            },
        )
        .to_string();

        // Native companions reference `::autumn_web`, which never compiles for
        // wasm32 — they must be gated off the edge target.
        let gate = "# [cfg (not (target_arch = \"wasm32\"))]";
        assert!(
            generated.contains(&format!(
                "{gate} # [doc (hidden)] fn __autumn_route_info_show"
            )),
            "the route-info companion must be gated off wasm32: {generated}"
        );
        assert!(
            generated.contains(&format!(
                "{gate} # [doc (hidden)] pub fn __autumn_path_show"
            )),
            "the path helper must be gated too — it calls ::autumn_web::paths: {generated}"
        );
        assert_eq!(
            generated.matches(gate).count(),
            2,
            "exactly the two native companions are gated: {generated}"
        );
        // The handler itself and the edge companion stay unconditional.
        assert!(
            !edge_companion_fragment(&generated).contains("cfg"),
            "the edge companion must not be gated: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_gates_the_path_helper_alias() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet", name = "greeting" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        assert!(
            generated.contains(
                "# [cfg (not (target_arch = \"wasm32\"))] # [doc (hidden)] \
                 pub use self :: __autumn_path_greeting as __autumn_path_greet ;"
            ),
            "the alias re-exports a gated helper, so it must be gated too: {generated}"
        );
        assert_eq!(
            generated
                .matches("# [cfg (not (target_arch = \"wasm32\"))]")
                .count(),
            3,
            "route info + path helper + alias are all native-only: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_detection_is_identical_for_both_attribute_orders() {
        // Ordering A: `#[get]` outermost, `#[edge]` still a live attribute.
        let below = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        // Ordering B: `#[edge]` above `#[get]`, so it expanded first and left
        // only the `__AUTUMN_EDGE` marker in the body.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! { async fn greet() -> &'static str { "hi" } },
        );
        let above = route_macro("GET", "get", quote! { "/greet" }, edged).to_string();

        assert_eq!(
            edge_companion_fragment(&below),
            edge_companion_fragment(&above),
            "both stacking orders must produce the same edge route"
        );
    }

    #[test]
    fn route_macro_edge_needs_kv_populates_the_needs_slice() {
        let edged = crate::edge::edge_macro(
            quote! { needs(kv) },
            quote! { async fn note() -> &'static str { "note" } },
        );
        let generated = route_macro("GET", "get", quote! { "/note" }, edged).to_string();

        assert!(
            generated.contains("needs : & [:: autumn_edge :: EdgeCapability :: Kv]"),
            "needs(kv) must declare the Kv capability on the edge route: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_needs_kv_is_read_from_a_live_attribute_too() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/note" },
            quote! {
                #[edge(needs(kv))]
                async fn note() -> &'static str { "note" }
            },
        )
        .to_string();

        assert!(
            generated.contains("needs : & [:: autumn_edge :: EdgeCapability :: Kv]"),
            "a live #[edge(needs(kv))] attribute must declare the capability: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_without_needs_declares_no_capabilities() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        assert!(
            generated.contains("needs : & []"),
            "a bare #[edge] route must declare no capabilities: {generated}"
        );
    }

    #[test]
    fn route_macro_non_edge_expansion_is_untouched() {
        // The edge work must be inert for every route that did not opt in:
        // no cfg attribute, no edge companion, nothing.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts/{id}", name = "post_page" },
            quote! {
                async fn show(id: Path<String>) -> &'static str { "post" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("cfg"),
            "a non-edge route must not gain a cfg attribute: {generated}"
        );
        assert!(
            !generated.contains("__autumn_edge_route_"),
            "a non-edge route must not gain an edge companion: {generated}"
        );
        assert!(
            !generated.contains("autumn_edge"),
            "a non-edge route must not reference autumn_edge at all: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_on_post_is_a_compile_error() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                #[edge]
                async fn create_item() -> &'static str { "created" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] on a write-path route must be rejected: {generated}"
        );
        assert!(
            generated.contains("only supported on"),
            "the error must say the edge lane is GET-only: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_secured_attribute_is_a_compile_error() {
        // Ordering A: both guards still live attributes below `#[get]`.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/dashboard" },
            quote! {
                #[edge]
                #[secured]
                async fn dashboard() -> &'static str { "dash" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[secured] must be rejected: {generated}"
        );
        assert!(
            generated.contains("no session or auth state"),
            "the error must explain why the edge lane cannot authenticate: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_expanded_secured_marker_is_a_compile_error() {
        // Ordering B: `#[secured]` above `#[get]` (already expanded into
        // markers), `#[edge]` still a live attribute below it.
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                #[edge]
                async fn dashboard() -> &'static str { "dash" }
            },
        );
        let generated = route_macro("GET", "get", quote! { "/dashboard" }, secured).to_string();

        assert!(
            generated.contains("compile_error"),
            "an already-expanded #[secured] must still be detected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_marker_buried_under_secured_wrapper_is_a_compile_error() {
        // `#[edge]` above `#[secured]` above `#[get]`: edge expands first, then
        // secured buries its marker inside `(async move { … }).await`. Losing
        // the marker here would silently ship an authenticated route to the
        // edge lane.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! { async fn dashboard() -> &'static str { "dash" } },
        );
        let secured = crate::secured::secured_macro(quote! { "admin" }, edged);
        let generated = route_macro("GET", "get", quote! { "/dashboard" }, secured).to_string();

        assert!(
            generated.contains("compile_error"),
            "a buried #[edge] marker must still be detected next to #[secured]: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_intercept_is_a_compile_error() {
        // `#[intercept]` layers wrap only the native mount; the edge companion
        // mounts the bare handler, so allowing the pair would let the two
        // lanes serve different bytes. Refused whichever side of `#[get]` the
        // interceptor sits on.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stamped" },
            quote! {
                #[edge]
                #[intercept(StampLayer)]
                async fn stamped() -> &'static str { "stamped" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[intercept] must be rejected: {generated}"
        );
        assert!(
            generated.contains("origin-only tower middleware"),
            "the error must explain that interceptors do not cross into the capsule: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_marker_with_intercept_is_a_compile_error() {
        // Ordering B: `#[edge]` above `#[get]` (already expanded into its
        // marker const), `#[intercept]` still a live attribute.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! {
                #[intercept(StampLayer)]
                async fn stamped() -> &'static str { "stamped" }
            },
        );
        let generated = route_macro("GET", "get", quote! { "/stamped" }, edged).to_string();

        assert!(
            generated.contains("compile_error"),
            "an expanded #[edge] marker + live #[intercept] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_native_mount_strips_request_credentials() {
        // The wire runtime strips SENSITIVE_HEADERS before capsule dispatch;
        // the native mount must strip the same set so a HeaderMap-reading
        // handler observes identical headers on both substrates.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet/{name}" },
            quote! {
                #[edge]
                async fn greet(Path(name): Path<String>) -> String { name }
            },
        )
        .to_string();

        assert!(
            generated.contains("strip_request_credentials"),
            "the edge route's native mount must carry the credential strip: {generated}"
        );

        let plain = route_macro(
            "GET",
            "get",
            quote! { "/greet/{name}" },
            quote! {
                async fn greet(Path(name): Path<String>) -> String { name }
            },
        )
        .to_string();
        assert!(
            !plain.contains("strip_request_credentials"),
            "a non-edge route must not be rewritten: {plain}"
        );
    }

    #[test]
    fn route_macro_edge_with_extension_param_is_a_compile_error() {
        // `Extension<T>` satisfies the Handler bound for any state, so the
        // type system cannot keep it out of the capsule; the macro must.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/tenant" },
            quote! {
                #[edge]
                async fn tenant(ext: Extension<TenantConfig>) -> String { ext.name() }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + Extension<T> must be rejected: {generated}"
        );
        assert!(
            generated.contains("installs no request extensions"),
            "the error must explain the missing-extension 500 hazard: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_nested_extension_param_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/tenant" },
            quote! {
                #[edge]
                async fn tenant(ext: Option<axum::Extension<TenantConfig>>) -> String { greet() }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a nested Extension extractor must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_cache_param_is_not_mistaken_for_an_extension() {
        // EdgeCache is delivered through an extension internally, but the
        // parameter type the author writes never names `Extension`.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/note/{key}" },
            quote! {
                #[edge(needs(kv))]
                async fn note(Path(key): Path<String>, cache: EdgeCache) -> String {
                    cache.get_string(&key).unwrap_or_default()
                }
            },
        )
        .to_string();

        assert!(
            !generated.contains("compile_error"),
            "EdgeCache must stay accepted: {generated}"
        );
    }

    #[test]
    fn route_macro_intercept_without_edge_is_unaffected() {
        // The refusal must not leak into the ordinary interceptor path.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stamped" },
            quote! {
                #[intercept(StampLayer)]
                async fn stamped() -> &'static str { "stamped" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("compile_error"),
            "#[intercept] without #[edge] must keep compiling: {generated}"
        );
        assert!(
            generated.contains("StampLayer"),
            "the interceptor layer must still wrap the native mount: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_throttle_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/search" },
            quote! {
                #[edge]
                #[throttle(limit = 1, per = "60s", key = "ip")]
                async fn search() -> &'static str { "results" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[throttle] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_expanded_throttle_marker_is_a_compile_error() {
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 1, per = "60s", key = "ip" },
            quote! {
                #[edge]
                async fn search() -> &'static str { "results" }
            },
        );
        let generated = route_macro("GET", "get", quote! { "/search" }, throttled).to_string();

        assert!(
            generated.contains("compile_error"),
            "an already-expanded #[throttle] must still be detected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_step_up_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/vault" },
            quote! {
                #[edge]
                #[step_up]
                async fn vault() -> &'static str { "secrets" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[step_up] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_authorize_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/notes/{id}" },
            quote! {
                #[edge]
                #[authorize("read", resource = Note)]
                async fn show_note(note: Note) -> &'static str { "note" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[authorize] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_string_literal_edge_marker_is_not_an_edge_route() {
        // Handler *text* that merely spells the marker const must not opt the
        // route into the edge lane: the marker is decoded structurally.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                async fn greet() -> &'static str {
                    let _ = "const __AUTUMN_EDGE: () = ();";
                    "hi"
                }
            },
        )
        .to_string();

        assert!(
            !generated.contains("__autumn_edge_route_"),
            "a string literal must not be mistaken for the edge marker: {generated}"
        );
    }

    #[test]
    fn route_macro_string_literal_authorize_marker_is_not_a_binding() {
        // Handler *text* that merely spells the marker const must not be
        // mistaken for one: the marker is decoded structurally, never scanned
        // for as a string.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                async fn create_item() -> &'static str {
                    let _ = "const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[(\"update\", \"Note\")];";
                    "created"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("authorize_bindings : & []"),
            "a string literal must not be mistaken for a generated binding marker: {generated}"
        );
    }
}