autumn-web 0.6.0

An opinionated, convention-over-configuration web framework for Rust
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
//! # Autumn
//!
//! An opinionated, convention-over-configuration web framework for Rust.
//!
//! Autumn assembles proven Rust crates ([Axum], [Maud], [Diesel], htmx, Tailwind)
//! into a Spring Boot-style developer experience with proc-macro-driven
//! conventions and customization options at every level.
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use autumn_web::prelude::*;
//!
//! #[get("/")]
//! async fn index() -> Markup {
//!     html! { h1 { "Hello, Autumn!" } }
//! }
//!
//! #[autumn_web::main]
//! async fn main() {
//!     autumn_web::app()
//!         .routes(routes![index])
//!         .run()
//!         .await;
//! }
//! ```
//!
//! ## Architecture overview
//!
//! | Layer | Crate | Purpose |
//! |-------|-------|---------|
//! | HTTP server | [Axum] | Routing, extractors, middleware |
//! | HTML templates | [Maud] | Type-safe, compiled HTML via `html!` macro |
//! | Database | [Diesel] | Async Postgres via `diesel-async` + deadpool |
//! | Client interactivity | htmx | Embedded JS served from same-origin `/static/js/` routes |
//! | Styling | Tailwind CSS | Downloaded + managed by `autumn-cli` |
//!
//! ## Modules
//!
//! - [`mod@app`] -- Application builder for configuring and launching the server.
//! - [`config`] -- Layered configuration: defaults, `autumn.toml`, env overrides.
//! - [`db`] -- Database connection pool and the [`Db`] request extractor.
//! - [`error`] -- Framework error type ([`AutumnError`]) and result alias.
//! - [`extract`] -- Re-exported Axum extractors ([`Form`],
//!   [`Json`], [`Path`], [`Query`], and optional multipart support).
//! - [`health`] -- Compatibility alias for readiness plus legacy health helpers.

//! - [`middleware`] -- Built-in middleware (request IDs).
//! - [`pagination`] -- Standardized `page`/`size` extractor and response wrapper.
//! - [`prelude`] -- Glob import for the most common types.

//!
//! ## Zero-config defaults
//!
//! An Autumn app runs out of the box with no configuration file. Every
//! setting has a sensible default (port 3000, `info` log level, etc.).
//! Override via `autumn.toml` or `AUTUMN_*` environment variables.
//! See [`config::AutumnConfig`] for the full list.
//!
//! [Axum]: https://docs.rs/axum
//! [Maud]: https://maud.lambda.xyz
//! [Diesel]: https://diesel.rs

// Allow `::autumn_web::` paths generated by proc macros to resolve
// within this crate itself (needed for tests and doctests).
#[allow(unused_extern_crates)]
extern crate self as autumn_web;

/// Typed accessible UI primitives (issue #1706).
///
/// These make the accessible name a compile-time obligation. See [`mod@a11y`].
#[cfg(feature = "maud")]
pub mod a11y;
pub mod actuator;
pub mod aggregate;
/// Operator alerts for built-in failure conditions.
///
/// Connects built-in failure signals (dead-lettered jobs, Down health
/// indicators, 5xx-rate spikes, scheduled-task failures) to the app's
/// configured mailer and signed outbound webhook behind `[alerts]` config —
/// with zero application code. See [`mod@alerts`].
pub mod alerts;
pub mod app;
pub mod assets;
pub mod audit;
pub mod auth;
pub mod authorization;
pub mod batches;
pub mod build_info;
pub mod cache;
#[cfg(feature = "ws")]
pub mod channels;
#[cfg(feature = "ws")]
pub use channels::{
    Broadcast, BroadcastError, BroadcastPayload, ChannelBackendConfigError, ChannelMessage,
    ChannelPublishError, ChannelStats, Channels, ChannelsBackend, LocalChannelsBackend,
};
pub mod canary;
pub mod circuit_breaker;
pub mod config;
pub mod credentials;
pub mod current;
#[cfg(feature = "db")]
pub mod db;
pub mod dotenv;
pub mod download;
pub mod encryption;
pub mod error;
#[cfg(feature = "maud")]
pub mod error_pages;
pub mod extract;
/// Deterministic fake-data generation backing factory `.fake()` support.
pub mod fake;
pub mod feed;
/// View-layer value formatting helpers (currency, delimited numbers,
/// pluralize, truncate, relative/absolute dates) for Maud templates.
///
/// See [`mod@format`] for the full API.
pub mod format;
pub mod health;
#[cfg(feature = "db")]
pub mod hooks;
#[cfg(feature = "i18n")]
pub mod i18n;
pub mod idempotency;
pub mod range;
pub mod seo;
/// Translation lookup macro with compile-time key validation.
///
/// Re-exported from [`crate::i18n::t`] for ergonomic
/// `autumn_web::t!(locale, "key")` usage.
#[cfg(feature = "i18n")]
pub use crate::i18n::t;
#[cfg(feature = "inbound-mail")]
pub mod inbound_mail;
pub mod inspector;
pub mod interceptor;
#[cfg(feature = "mail")]
pub mod mail;
pub mod maintenance;
#[cfg(feature = "managed-pg")]
pub mod managed_pg;
#[cfg(feature = "db")]
pub mod migrate;
pub(crate) mod pg_conn_str;
pub mod plugin;
pub mod plugin_conformance;
pub mod probe;

/// Re-export of the [`include_dir`](https://docs.rs/include_dir) crate.
///
/// Lets apps embed their `static/` and `i18n/` trees without adding `include_dir`
/// as a direct dependency. Used by the [`embed_static!`] and [`embed_locales!`]
/// macros. Nested in a module (rather than a crate-root `pub use`) so the
/// re-export resolves for external consumers, mirroring [`reexports`].
#[cfg(feature = "embed-assets")]
pub mod include_dir {
    pub use ::include_dir::*;
}

/// Embed the app's `static/` directory (including the `.autumn-manifest.json`
/// written by `autumn build --embed`) into the binary at compile time.
///
/// Expands to an [`include_dir::Dir`] rooted at the **calling crate's**
/// `static/` directory (resolved via `$CARGO_MANIFEST_DIR`, exactly like
/// `embed_migrations!`). Pass the result to
/// [`AppBuilder::embedded_static`](crate::app::AppBuilder::embedded_static):
///
/// ```rust,ignore
/// static STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();
///
/// #[autumn_web::main]
/// async fn main() {
///     autumn_web::app().embedded_static(&STATIC).run().await;
/// }
/// ```
#[cfg(feature = "embed-assets")]
#[macro_export]
macro_rules! embed_static {
    () => {{
        // `include_dir!` emits `include_dir::{Dir, File, ...}` paths resolved at
        // the call site, so bring our re-export into scope under that name. This
        // lets apps embed without depending on the `include_dir` crate directly.
        #[allow(unused_imports)]
        use $crate::include_dir;
        $crate::include_dir::include_dir!("$CARGO_MANIFEST_DIR/static")
    }};
}

/// Embed the app's i18n locale bundles (the `i18n/` directory, or a custom
/// directory) into the binary at compile time.
///
/// Pass the result to
/// [`AppBuilder::embedded_locales`](crate::app::AppBuilder::embedded_locales).
///
/// ```rust,ignore
/// static LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();
/// // or a custom directory:
/// static LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!("translations");
/// ```
#[cfg(all(feature = "embed-assets", feature = "i18n"))]
#[macro_export]
macro_rules! embed_locales {
    () => {{
        #[allow(unused_imports)]
        use $crate::include_dir;
        $crate::include_dir::include_dir!("$CARGO_MANIFEST_DIR/i18n")
    }};
    ($dir:literal) => {{
        #[allow(unused_imports)]
        use $crate::include_dir;
        $crate::include_dir::include_dir!(concat!("$CARGO_MANIFEST_DIR/", $dir))
    }};
}
#[cfg(feature = "system-info")]
pub mod system_info;
pub use plugin::{Plugin, Plugins};

pub mod route_listing;

/// Inbound (server-side) TLS support (issue #1603).
///
/// Load and validate a certificate + key, build a reloadable rustls
/// `ServerConfig`, and inspect leaf-certificate expiry. Gated behind the
/// off-by-default `tls` feature.
#[cfg(feature = "tls")]
pub mod tls;

/// Automatic ACME (Let's Encrypt) certificate provisioning + renewal (#1608).
///
/// Builds on the [`tls`] listener: the certificate obtained over the ACME
/// HTTP-01 challenge hot-swaps into the same `ReloadableCertResolver` the TLS
/// listener serves. Gated behind the off-by-default `acme` feature.
#[cfg(feature = "acme")]
pub mod acme;

#[cfg(feature = "db")]
pub mod sharding;

#[cfg(feature = "db")]
pub mod repository;
#[cfg(feature = "db")]
pub(crate) mod repository_commit_hooks;
#[cfg(feature = "db")]
pub use repository::RepositoryError;

/// Read-your-own-writes routing support.
///
/// When `database.read_your_writes` is `request` or `session`, generated
/// repository read methods consult the per-request task-local at acquire time
/// and redirect replica-eligible reads to the primary when a write has
/// occurred in the same request (or within the session cookie window).
#[cfg(feature = "db")]
pub mod read_your_writes;

/// Offline-first local SQLite store and background sync engine for
/// occasionally-connected apps (e.g. Tauri mobile).
///
/// See the [`sync`] module documentation for the architecture (change
/// tracking, tombstoning, conflict resolution) and wiring examples.
#[cfg(feature = "offline-sync")]
pub mod sync;

/// Automatic record version history for `#[repository]` writes.
///
/// See [`version_history`] module documentation for the full API.
pub mod version_history;
pub use version_history::{
    ColumnChange, VersionEntry, VersionFilter, VersionOp, VersionPage, VersionedRecord,
    compute_delete_changes, compute_diff, compute_insert_changes,
};

/// Router construction and integration with Axum.
///
/// This module is responsible for taking the application's configuration,
/// defined routes, middleware, and state, and building the final `axum::Router`
/// that will handle incoming HTTP requests.
pub(crate) mod router;

/// Fuzzing-only re-export surface.
///
/// Compiled only when the crate is built with `--cfg fuzzing` (as cargo-fuzz
/// does for the workspace-root `fuzz/` crate). It re-exports otherwise-private
/// or `pub(crate)` request-path parsing seams so the fuzz targets can drive
/// them over raw untrusted bytes. Everything here is guarded by `#[cfg(fuzzing)]`
/// so normal builds — and `cargo package` output — are byte-identical.
///
/// Not part of the public API; no stability guarantees.
#[cfg(fuzzing)]
#[doc(hidden)]
pub mod __fuzz {
    // Routing / path-parameter extraction (functions are `pub` inside the
    // `pub(crate)` `router` module).
    pub use crate::router::{
        extract_host_without_port, join_nested_path, path_matches_route_prefix,
    };
    // `extract_path_params` only exists under the `openapi` feature (it backs
    // spec-URL generation); the `fuzz/` crate enables `openapi` so this routing
    // seam is present when fuzzing.
    #[cfg(feature = "openapi")]
    pub use crate::router::extract_path_params;

    // Trusted-proxy / `X-Forwarded-*` header parsing.
    pub use crate::security::trusted_proxies::{
        __fuzz_parse_forwarded_ip as parse_forwarded_ip,
        __fuzz_parse_trusted_proxy as parse_trusted_proxy,
        __fuzz_resolve_forwarded as resolve_forwarded,
    };

    // Cookie / signed-session decode.
    pub use crate::session::__fuzz_decode_cookie as decode_cookie;

    // Body handling: form-urlencoded (always) + inbound-mail MIME (feature-gated).
    pub use crate::form::__fuzz_decode_urlencoded as decode_urlencoded_form;
    #[cfg(feature = "inbound-mail")]
    pub use crate::inbound_mail::{
        __fuzz_parse_address_list as parse_address_list, __fuzz_parse_generic as parse_generic,
        __fuzz_parse_ses as parse_ses,
    };
}

#[cfg(feature = "db")]
pub use hooks::{
    DraftField, FieldDiff, MutationContext, MutationHooks, MutationOp, NoHooks, Patch, UpdateDraft,
};
pub mod etag;
/// Traced outbound HTTP client with retries and test mocks.
///
/// See [`http_client::Client`] for the full API. The module is exposed as
/// `autumn_web::http` so handler code can write `use autumn_web::http::Client`.
#[cfg(feature = "http-client")]
pub mod http_client;
#[cfg(feature = "http-client")]
pub use http_client as http;
#[cfg(feature = "flash")]
pub mod flash;
#[cfg(feature = "htmx")]
pub mod htmx;
/// Declarative live-broadcast trait for `#[repository(Model, broadcasts = "topic")]`.
///
/// Implement [`live::LiveFragment`] on a model to enable automatic `hx-swap-oob`
/// broadcasts after each `save`/`update`/`delete_by_id` call. Requires the
/// `ws`, `maud`, and `htmx` features.
#[cfg(all(feature = "htmx", feature = "maud"))]
pub mod live;
pub mod lock;
pub mod log;
pub(crate) mod logging;
/// Project typed JSON endpoints as Model Context Protocol (MCP) tools so AI
/// agents can call the real, authenticated handler pipeline.
///
/// Enable with the Cargo feature `mcp` (which implies `openapi`).
#[cfg(feature = "mcp")]
pub mod mcp;
pub mod middleware;
/// Content-negotiated success responder (`Negotiate` / `Negotiated` / `Format`).
#[cfg(feature = "maud")]
pub mod negotiate;
pub mod openapi;
pub mod pagination;
pub mod paths;
/// Eager-loading (preload) runtime for `#[model]` associations.
///
/// See [`preload`] for [`preload::Preloaded`], [`preload::NotLoaded`], and the
/// [`preload::Preloadable`] trait that generated code implements.
pub mod preload;
pub mod prelude;
pub use paths::PathExt;
#[cfg(feature = "presence")]
pub mod presence;
#[cfg(all(feature = "presence", feature = "maud"))]
pub use presence::presence_badge;
#[cfg(all(
    feature = "presence",
    feature = "ws",
    feature = "maud",
    feature = "htmx"
))]
pub use presence::presence_stream;
#[cfg(feature = "presence")]
pub use presence::{Presence, PresenceEntry, PresenceEvent, PresenceHandle};
pub(crate) mod route;
pub use route::{RepositoryApiMeta, Route, RouteIdempotency, RouteTimeout};
/// First-class Markdown rendering with frontmatter parsing and SSG integration.
///
/// Enable with the Cargo feature `markdown`.
#[cfg(feature = "markdown")]
pub mod markdown;
/// Pluggable error reporting: catch handler panics and route panics + 5xx
/// responses to configured [`ErrorReporter`](reporting::ErrorReporter)s.
///
/// Enabled by the `reporting` Cargo feature (on by default).
#[cfg(feature = "reporting")]
pub mod reporting;
pub mod scheduler;
pub mod security;
pub mod session;
#[cfg(feature = "redis")]
pub(crate) mod session_redis;
pub mod sse;
/// Static site generation support.
pub mod static_gen;
pub mod step_up;
#[cfg(feature = "storage")]
pub mod storage;
pub mod tenancy;
pub mod tenant_cell;
pub mod time;
pub mod time_zone;
pub mod user_agent;

pub mod events;
pub mod experiments;
pub mod feature_flags;
pub mod form;
pub mod gdpr;
pub mod job;
pub mod job_tracking;
/// Safe, method-aware link helpers: [`links::link_to`] anchors and
/// [`links::button_to`] CSRF-protected action buttons.
pub mod links;
pub mod nested_form;
pub mod payload_version;
pub mod runtime_config;
#[cfg(feature = "seed")]
pub mod seed;

// ── #1343 AC4: fake-seeder registration forwarding ──────────────────────────
//
// `#[model]` emits a call to `autumn_web::__autumn_register_fake_seeder!` for
// every model so `autumn seed --count N --model M` can find and run the model's
// factory without the user editing `src/bin/seed.rs`. The registration must
// exist *exactly* when `autumn_web::seed::FakeSeeder` and the db-backed
// `create_many` do — i.e. when this crate is built with the `seed` feature.
//
// A downstream `#[cfg(feature = "seed")]` in the emitted code would test the
// *application* crate's features, not autumn-web's, so it can't be used
// directly. Instead we forward through a `#[macro_export]` macro whose two
// cfg-gated definitions are resolved against *autumn-web's* features at the
// point autumn-web is compiled: the real `inventory::submit!` when `seed` is on,
// and a no-op otherwise. This keeps models compiling unchanged when seeding is
// disabled (e.g. autumn-web's own default-feature test build).

/// Register a model's factory as a CLI-callable fake seeder (internal; invoked
/// by `#[model]`). Expands to an `inventory::submit!` of a
/// [`seed::FakeSeeder`](crate::seed::FakeSeeder).
#[cfg(feature = "seed")]
#[macro_export]
#[doc(hidden)]
macro_rules! __autumn_register_fake_seeder {
    ($model:ty, $name:expr) => {
        $crate::reexports::inventory::submit! {
            $crate::seed::FakeSeeder {
                model: $name,
                run: |__pool, __count| ::std::boxed::Box::pin(async move {
                    <$model>::factory().fake().create_many(__count, __pool).await.len()
                }),
            }
        }
    };
}

/// No-op fake-seeder registration (internal): emitted when autumn-web is built
/// without the `seed` feature, so `#[model]` compiles unchanged.
#[cfg(not(feature = "seed"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __autumn_register_fake_seeder {
    ($model:ty, $name:expr) => {};
}
/// Widget story gallery (issue #1526).
///
/// Browsable `/_stories` UI plus a CI anti-rot registry of zero-arg widget
/// render examples.
#[cfg(feature = "maud")]
pub mod stories;
pub mod task;
pub mod telemetry;
pub mod ui;
/// Active search and autocomplete form primitives with htmx integration.
///
/// See [`widgets`] for the full API including [`widgets::active_search`],
/// [`widgets::autocomplete_input`], [`widgets::data_table`],
/// [`widgets::property_list`], and their configuration types.
pub mod widgets;
/// First-class multi-step form wizards with session-backed state and per-step validation.
///
/// See [`wizard`] for the full API including [`wizard::WizardContext`] and
/// [`wizard::wizard_progress`].
pub mod wizard;
/// Changeset type carrying submitted values + per-field errors.
pub use form::Changeset;
/// Changeset form extractor — decodes body + validates, captures errors in [`form::Changeset`].
pub use form::ChangesetForm;
/// Trait implemented for all `validator::Validate` types to produce a [`Changeset`].
pub use form::IntoChangeset;
#[cfg(feature = "maud")]
pub use nested_form::{InputsForOptions, RowScope, inputs_for, nested_row_fragment};
/// Nested (`has_many`) form binding: parent + one child collection.
pub use nested_form::{
    NestedChangeset, NestedChangesetForm, NestedChild, NestedRow, decode_nested_urlencoded,
};
pub mod data;
pub mod normalize;
pub mod validation;
pub mod webhook;
#[cfg(feature = "http-client")]
pub mod webhook_outbound;
#[cfg(feature = "ws")]
pub mod ws;

/// Private runtime helpers for code generated by Autumn proc macros.
///
/// This module is semver-exempt. Do not use it directly.
#[doc(hidden)]
pub mod __private {
    #[cfg(feature = "db")]
    pub use crate::db::scoped_immediate_transaction;
    #[cfg(feature = "db")]
    pub use crate::db::scoped_transaction;
    #[cfg(all(feature = "db", feature = "ws"))]
    pub use crate::repository_commit_hooks::CURRENT_CHANNELS;
    #[cfg(feature = "db")]
    pub use crate::repository_commit_hooks::{
        RepositoryCommitHookDescriptor, catch_repository_after_hook_unwind,
        discard_repository_commit_hook_pending, enqueue_repository_commit_hook_on_conn,
        enqueue_repository_commit_hook_pending_on_conn,
        enqueue_repository_commit_hooks_bulk_on_conn,
        enqueue_repository_commit_hooks_pending_bulk_on_conn,
        finalize_repository_commit_hook_after_hook, kick_repository_commit_hook_dispatcher,
        mark_repository_commit_hook_after_hook_failed, register_repository_commit_hook_runner,
        start_repository_commit_hook_pending_finalizer_heartbeat,
        start_repository_commit_hook_worker,
    };
    #[cfg(feature = "db")]
    pub use crate::repository_commit_hooks::{
        clear_global_channels, get_global_channels, set_global_channels,
    };
    #[cfg(feature = "db")]
    pub use crate::version_history::VersionedRepositoryDescriptor;

    pub use crate::router::check_sunset;

    // Shared factory creation depth — bounds cyclic `#[factory_assoc]` chains
    // across all models in a single create() chain.
    //
    // Task-local (not thread-local) so it is maintained correctly when a
    // generated async `create()` future migrates between worker threads on a
    // work-stealing runtime such as Tokio's multi-thread scheduler.
    tokio::task_local! {
        pub static FACTORY_DEPTH: u32;
    }
}

pub use crate::router::RouteVersionMetadata;

/// Create a new [`app::AppBuilder`] for configuring and launching an Autumn server.
///
/// This is the primary entry point for every Autumn application.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn index() -> &'static str { "hello" }
///
/// #[autumn_web::main]
/// async fn main() {
///     autumn_web::app()
///         .routes(routes![index])
///         .run()
///         .await;
/// }
/// ```
pub use app::app;
pub use app::{ApiVersion, RegisteredApiVersions};
/// Async database connection extractor.
///
/// Declare `db: Db` in a handler signature to get a pooled Postgres
/// connection. See [`db::Db`] for full documentation and examples.
#[cfg(feature = "db")]
pub use db::Db;

/// Transaction options (isolation level + retry policy) and the savepoint
/// helper for [`Db::tx_with`]. See [`db::TxOptions`].
#[cfg(feature = "db")]
pub use db::{IsolationLevel, TxOptions, savepoint};

/// The runtime database connection type (Postgres by default; `SQLite` under the
/// `sqlite` feature). Named by generated `#[repository]`/`#[model]` code as
/// `::autumn_web::RuntimeConnection`. See [`db::RuntimeConnection`].
#[cfg(feature = "db")]
pub use db::RuntimeConnection;

/// The runtime diesel query backend (`diesel::pg::Pg` by default;
/// `diesel::sqlite::Sqlite` under the `sqlite` feature). Named by generated
/// `#[repository]`/`#[model]` code as `::autumn_web::RuntimeBackend`. See
/// [`db::RuntimeBackend`].
#[cfg(feature = "db")]
pub use db::RuntimeBackend;

/// Framework error type and result alias.
///
/// [`AutumnError`] wraps any `Error + Send + Sync` with an HTTP status code.
/// [`AutumnResult<T>`] is `Result<T, AutumnError>`.
/// See the [`error`] module for details.
pub use error::{AutumnError, AutumnResult};

pub use tenant_cell::{QuotaExceeded, TenantCell, TenantCellHandle, TenantCellRegistry};

/// Paginated list response wrapper with navigation metadata.
///
/// See the [`pagination`] module for the full query contract and usage
/// patterns.
pub use pagination::Page;

/// Pagination parameters extracted from the query string.
///
/// See the [`pagination`] module for the full query contract and usage
/// patterns.
pub use pagination::PageRequest;

/// Allowlisted sort/filter parameters extracted from the query string, and the
/// canonical [`SortDir`] direction. Compose with [`PageRequest`] to drive the
/// `#[repository]`-generated `list()` method.
///
/// See the [`pagination`] module for the security model (the allowlist is the
/// injection boundary) and the query contract.
pub use pagination::{ListQuery, SortDir};

/// Cursor pagination response wrapper. Companion to [`CursorRequest`]
/// for keyset/seek pagination of real-time feeds.
///
/// See the [`pagination`] module for the full query contract and usage
/// patterns.
pub use pagination::CursorPage;

/// Eager-loaded record wrapper and the typed `NotLoaded` accessor error.
///
/// See the [`preload`] module for declaring `#[belongs_to]` / `#[has_many]` /
/// `#[has_one]` associations and loading them with a `#[repository]`
/// `preload(...)` call.
pub use preload::{NotLoaded, Preloaded};

/// Cursor pagination parameters extracted from the query string.
///
/// See the [`pagination`] module for the full query contract and usage
/// patterns.
pub use pagination::CursorRequest;

/// Auto-validating extractor. Wraps `Json<T>`, `Form<T>`, or `Query<T>`
/// and validates via `validator::Validate` before the handler runs.
/// Returns 422 with structured error details on validation failure.
pub use validation::Valid;

/// Proof that `T` has passed validation. See [`validation`] module.
pub use validation::Validated;

/// htmx version string embedded in the binary.
///
/// Useful for cache-busting or diagnostic logging. The corresponding
/// minified JS is served automatically at `/static/js/htmx.min.js`.
#[cfg(feature = "htmx")]
pub use htmx::{
    AUTUMN_WIDGETS_JS_PATH, HTMX_CSRF_JS_PATH, HTMX_JS, HTMX_JS_PATH, HTMX_SSE_JS,
    HTMX_SSE_JS_PATH, HTMX_VERSION, IDIOMORPH_JS, IDIOMORPH_JS_PATH,
};
#[cfg(all(feature = "htmx", feature = "maud"))]
pub use htmx::{HtmxFragments, OobSwap};
/// Trait for rendering a model instance as an htmx `hx-swap-oob` fragment.
///
/// Implement this on your model and declare `broadcasts = "topic"` on the
/// `#[repository]` attribute to enable automatic live broadcasts.
#[cfg(all(feature = "htmx", feature = "maud"))]
pub use live::LiveFragment;
#[cfg(feature = "mail")]
pub use mail::{
    Mail, MailAttachment, MailConfig, MailDeliveryQueue, MailDeliveryQueueHandle, MailError,
    MailTransport, Mailer, SmtpConfig, TlsMode, Transport,
};
/// Extension trait adding `.validate()` to all `validator::Validate` types.
pub use validation::ValidateExt;

// ── Proc-macro re-exports ──────────────────────────────────────────

/// Annotate an async function as a `DELETE` route handler.
///
/// Generates a companion function that returns a [`crate::route::Route`]
/// pairing the path with an Axum handler. In debug builds
/// `#[axum::debug_handler]` is applied automatically for better error
/// messages (zero cost in release).
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[delete("/items/{id}")]
/// async fn remove_item() -> &'static str {
///     "removed"
/// }
/// ```
pub use autumn_macros::delete;

/// Enrich a route handler's auto-generated `OpenAPI` documentation.
///
/// See the [`openapi`] module and the [`autumn_macros::api_doc`]
/// attribute docs for details on the supported keys.
///
/// # Example
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/users/{id}")]
/// #[api_doc(summary = "Fetch a user by id", tag = "users")]
/// async fn get_user(Path(id): Path<i32>) -> String {
///     format!("User {id}")
/// }
/// ```
pub use autumn_macros::api_doc;

/// Annotate an async function as a `GET` route handler.
///
/// Generates a companion function that returns a [`crate::route::Route`]
/// pairing the path with an Axum handler. In debug builds
/// `#[axum::debug_handler]` is applied automatically for better error
/// messages (zero cost in release).
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/hello")]
/// async fn hello() -> &'static str {
///     "Hello, Autumn!"
/// }
/// ```
pub use autumn_macros::get;
/// Annotate an async function as a first-class inbound mail handler.
///
/// See [`inbound_mail`] for usage documentation.
#[cfg(feature = "inbound-mail")]
pub use autumn_macros::inbound_mail;
/// Collect mailer preview registrations into an `AppBuilder`.
#[cfg(feature = "mail")]
pub use autumn_macros::mail_previews;
/// Generate ergonomic `send_*` and `deliver_later_*` helpers for mailer impls.
#[cfg(feature = "mail")]
pub use autumn_macros::mailer;
/// Register zero-argument mail template previews for the dev mail UI.
#[cfg(feature = "mail")]
pub use autumn_macros::mailer_preview;
/// Set up the Tokio async runtime for an Autumn application.
///
/// A thin wrapper around `#[tokio::main]`. The real framework setup
/// happens inside [`app::AppBuilder::run`].
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn index() -> &'static str { "hi" }
///
/// #[autumn_web::main]
/// async fn main() {
///     autumn_web::app()
///         .routes(routes![index])
///         .run()
///         .await;
/// }
/// ```
pub use autumn_macros::main;
/// Author a widget story for the `/_stories` gallery:
/// `story!{ "Group", "Name", { ... } }`.
///
/// Also available as [`stories::story`], the macro's module home.
#[cfg(feature = "maud")]
pub use autumn_macros::story;

/// Derive Diesel and Serde traits for a database model struct.
///
/// Applies `Queryable`, `Selectable`, `Insertable`, `Serialize`, and
/// `Deserialize` derives plus a `#[diesel(table_name = ...)]` attribute.
/// The table name is either specified explicitly or inferred from the
/// struct name (`PascalCase` -> `snake_case` + `s`).
///
/// # Examples
///
/// Explicit table name:
///
/// ```rust,ignore
/// use autumn_web::model;
///
/// #[model(table = "users")]
/// pub struct User {
///     pub id: i64,
///     pub name: String,
/// }
/// ```
///
/// Inferred table name (`BlogPost` -> `blog_posts`):
///
/// ```rust,ignore
/// use autumn_web::model;
///
/// #[model]
/// pub struct BlogPost {
///     pub id: i64,
///     pub title: String,
/// }
/// ```
#[cfg(feature = "db")]
pub use autumn_macros::model;
/// Annotate an OAuth2/OIDC callback handler.
///
/// Convenience alias for `#[get(...)]` with callback-focused naming.
pub use autumn_macros::oauth2_callback;

/// Derive a repository with CRUD operations and derived queries.
///
/// See [`macro@repository`] for details.
#[cfg(feature = "db")]
pub use autumn_macros::repository;

/// Define a service for cross-model orchestration and non-DB side effects.
///
/// Generates a `XxxServiceImpl` struct with dependency injection.
/// Use when logic spans multiple repositories or involves non-DB work.
/// For single-model CRUD, use [`macro@repository`] instead.
///
/// # Examples
///
/// ```rust,ignore
/// use autumn_web::service;
///
/// #[service]
/// pub trait OrderService {
///     fn deps(order_repo: PgOrderRepository, inventory_repo: PgInventoryRepository);
/// }
///
/// impl OrderServiceImpl {
///     pub async fn place_order(&self, req: PlaceOrderRequest) -> AutumnResult<Order> {
///         let order = self.order_repo.save(&req.into()).await?;
///         self.inventory_repo.reserve(order.id).await?;
///         Ok(order)
///     }
/// }
/// ```
#[cfg(feature = "db")]
pub use autumn_macros::service;

/// Annotate an async function as a `PATCH` route handler.
///
/// Generates a companion function that returns a [`crate::route::Route`]
/// and a typed `__autumn_path_{name}(…) -> String` path helper.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::patch;
///
/// #[patch("/items/{id}")]
/// async fn patch_item() -> &'static str {
///     "patched"
/// }
/// ```
pub use autumn_macros::patch;

/// Emit a `pub mod paths { … }` re-exporting typed path helpers.
///
/// Takes the same comma-separated handler list as [`routes!`]. Invoke once
/// in the module where your handlers live:
///
/// ```ignore
/// autumn_web::paths![show_post, create_post];
/// // callers can then: use crate::routes::paths;
/// //                    paths::show_post(42)
/// ```
pub use autumn_macros::paths;

/// HTTP redirect response.
///
/// Re-exported from [Axum](https://docs.rs/axum) so route handlers can
/// return a redirect without a direct `axum` dependency.
///
/// Use [`Redirect::to`] with a path helper:
///
/// ```ignore
/// use autumn_web::Redirect;
/// Redirect::to(&paths::show_post(id))
/// ```
pub use axum::response::Redirect;

/// Annotate an async function as a `POST` route handler.
///
/// Generates a companion function that returns a [`crate::route::Route`]
/// pairing the path with an Axum handler. In debug builds
/// `#[axum::debug_handler]` is applied automatically for better error
/// messages (zero cost in release).
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[post("/items")]
/// async fn create_item() -> &'static str {
///     "created"
/// }
/// ```
pub use autumn_macros::post;

/// Annotate an async function as a `PUT` route handler.
///
/// Generates a companion function that returns a [`crate::route::Route`]
/// pairing the path with an Axum handler. In debug builds
/// `#[axum::debug_handler]` is applied automatically for better error
/// messages (zero cost in release).
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[put("/items/{id}")]
/// async fn update_item() -> &'static str {
///     "updated"
/// }
/// ```
pub use autumn_macros::put;

/// Collect route-annotated handlers into a `Vec<Route>`.
///
/// Each handler must have been annotated with a route macro ([`get`],
/// [`post`], [`put`], [`delete`]) which generates a companion
/// `__autumn_route_info_{name}()` function.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/hello")]
/// async fn hello() -> &'static str { "hello" }
///
/// #[post("/create")]
/// async fn create() -> &'static str { "created" }
///
/// # #[autumn_web::main]
/// # async fn main() {
/// let all_routes = routes![hello, create];
/// autumn_web::app().routes(all_routes).run().await;
/// # }
/// ```
pub use autumn_macros::routes;

/// Cache the return value of a function based on its arguments.
///
/// Wraps a function with an in-memory cache backed by a static
/// [`MokaCache`](cache::MokaCache) (default) via the [`Cache`](cache::Cache)
/// trait. Arguments must implement `Hash + Clone`; the return type must
/// be `Clone + Send + Sync + 'static`.
///
/// Use `result` to only cache `Ok` values from `Result`-returning
/// functions (common with [`AutumnResult`]).
///
/// # Examples
///
/// ```rust,ignore
/// use autumn_web::cached;
///
/// #[cached(ttl = "5m", max = 100, result)]
/// async fn get_user(id: i64) -> AutumnResult<User> {
///     db.find(id).await
/// }
/// ```
pub use autumn_macros::cached;

/// Annotate an async function as a WebSocket route handler.
///
/// The function follows the **two-function pattern**: it runs at HTTP
/// upgrade time and returns a closure implementing [`ws::WsHandler`]
/// that handles the live WebSocket connection.
///
/// Generates a GET route for the WebSocket upgrade, compatible with
/// [`routes!`]. Requires the `ws` feature.
///
/// # Examples
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
/// use autumn_web::ws::{WebSocket, Message, WsHandler};
///
/// #[ws("/echo")]
/// async fn echo() -> impl WsHandler {
///     |mut socket: WebSocket| async move {
///         while let Some(Ok(msg)) = socket.recv().await {
///             if let Message::Text(text) = msg {
///                 socket.send(Message::Text(text)).await.ok();
///             }
///         }
///     }
/// }
/// ```
#[cfg(feature = "ws")]
pub use autumn_macros::ws;

/// Declare a typed domain event. See [`mod@events`] module.
pub use autumn_macros::event;
/// Declare an on-demand background job. See [`mod@job`] module.
pub use autumn_macros::job;
/// Declare an event listener. See [`mod@events`] module.
pub use autumn_macros::listener;
/// Declare a scheduled background task. See [`mod@task`] module.
pub use autumn_macros::scheduled;
/// Declare a one-off operational task. See [`task::OneOffTaskInfo`].
pub use autumn_macros::task;

/// Extractor that yields a verified bearer-token principal for API routes.
///
/// Must be used with [`auth::RequireApiToken`] middleware. See the
/// [`auth`] module for a complete quick-start example.
pub use auth::ApiToken;

/// Tower layer that validates `Authorization: Bearer <token>` on API routes.
///
/// Verifies tokens against any [`auth::ApiTokenStore`] implementation.
/// Returns `401 Unauthorized` for missing, unknown, revoked, or expired tokens.
pub use auth::RequireApiToken;

/// Scoped service-token types and helpers: mint named, scoped, optionally
/// expiring tokens whose granted scopes flow into the policy layer.
pub use auth::{
    ApiTokenScopes, IssueTokenSpec, TokenMetadata, VerifiedToken, issue_scoped_api_token,
    list_api_tokens, rotate_api_token,
};

/// Postgres-backed API token store (requires `db` feature).
///
/// Production replacement for [`auth::InMemoryApiTokenStore`]. Hashes tokens
/// at rest and persists them across restarts. Use with [`API_TOKEN_MIGRATIONS`]
/// for dev/test startup checks; `autumn migrate` applies the token-table
/// framework migration in production.
#[cfg(feature = "db")]
pub use auth::DbApiTokenStore;

/// Embedded Diesel migrations for the `api_tokens` table (requires `db` feature).
///
/// Pass to `app().migrations()` so that dev/test startup migration checks can
/// create and validate the `api_tokens` table alongside your application
/// migrations.
#[cfg(feature = "db")]
pub use auth::API_TOKEN_MIGRATIONS;

/// Secure a route handler with authentication and optional role checks.
///
/// Applied before a route macro (`#[get]`, `#[post]`, etc.), this attribute
/// injects an authentication guard at the top of the handler. The guard
/// checks the session for the configured auth key (default: `"user_id"`)
/// and, when roles are specified, verifies the user's role matches.
///
/// Returns `401 Unauthorized` if not authenticated, or `403 Forbidden`
/// if the user lacks the required role.
///
/// The handler must return [`AutumnResult<T>`] so the guard can use `?`
/// to short-circuit on failure.
///
/// # Forms
///
/// - `#[secured]` -- require authentication only
/// - `#[secured("admin")]` -- require a specific role
/// - `#[secured("admin", "editor")]` -- require any of the listed roles
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/dashboard")]
/// #[secured]
/// async fn dashboard() -> AutumnResult<&'static str> {
///     Ok("welcome")
/// }
///
/// #[get("/admin")]
/// #[secured("admin")]
/// async fn admin_panel() -> AutumnResult<&'static str> {
///     Ok("admin area")
/// }
///
/// #[get("/content")]
/// #[secured("admin", "editor")]
/// async fn manage_content() -> AutumnResult<&'static str> {
///     Ok("content manager")
/// }
/// ```
pub use autumn_macros::secured;

/// Declare a route handler as deliberately public (unauthenticated).
///
/// A compile-time marker that records intent: it injects no runtime guard and
/// leaves the handler signature untouched, but surfaces on the route's
/// [`ApiDoc::public`](crate::openapi::ApiDoc::public) so the build-time security
/// classifier (`autumn routes audit`) treats the route as an explicit opt-out
/// of authentication rather than an oversight.
///
/// # Example
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/pricing")]
/// #[public]
/// async fn pricing() -> &'static str { "free" }
/// ```
pub use autumn_macros::public;

/// Require fresh ("step-up") authentication before a route handler runs.
///
/// The handler is guarded by a freshness check on the session's
/// `last_strong_auth_at` claim. When the claim is missing or older than
/// `max_age` (default: 5 minutes) the request is handled as follows:
///
/// - **Browser clients**: redirect to `/reauth?return_to=<current-path>`.
/// - **API / JSON clients** (`Accept: application/json`): `401` with
///   RFC 7807 problem-details and `WWW-Authenticate: StepUp max-age=N`.
///
/// # Examples
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
///
/// // Default 5-minute window.
/// #[delete("/account")]
/// #[step_up]
/// async fn destroy_account() -> AutumnResult<Redirect> {
///     Ok(Redirect::to("/bye"))
/// }
///
/// // Custom window.
/// #[post("/auth/mfa/remove")]
/// #[step_up(max_age = "2m")]
/// async fn remove_mfa() -> AutumnResult<&'static str> {
///     Ok("removed")
/// }
/// ```
pub use autumn_macros::step_up;

/// Apply a per-route rate limit that composes with the global limiter.
///
/// # Forms
///
/// - `#[throttle(limit = 5, per = "1m")]` — inline limit; keying strategy
///   matches the global limiter (`[security.rate_limit]`).
/// - `#[throttle(limit = 5, per = "1m", key = "ip" | "principal" | "token")]`
///   — inline limit with an explicit key strategy.
/// - `#[throttle("login")]` — reference a named limiter defined in
///   `[security.rate_limit.named.login]`.
///
/// Requests denied by the per-route bucket receive `429 Too Many Requests`
/// with a `Retry-After` header and the standard `x-ratelimit-*` headers.
/// [`RateLimitExempt`](crate::security::RateLimitExempt) still bypasses the
/// per-route throttle.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
///
/// #[post("/login")]
/// #[throttle(limit = 5, per = "1m", key = "ip")]
/// async fn login() -> AutumnResult<&'static str> {
///     Ok("welcome back")
/// }
/// ```
pub use autumn_macros::throttle;

/// Gate a route handler on a named feature flag. If the flag is disabled for
/// the current actor the handler responds with `404 Not Found` (default) or
/// delegates to a custom fallback specified with `fallback = my_fn`.
///
/// Requires a [`FeatureFlagService`](crate::feature_flags::FeatureFlagService)
/// installed in the app's [`AppState`] extensions.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
///
/// #[get("/beta")]
/// #[feature_flag("beta_dashboard")]
/// async fn beta_dashboard() -> Markup {
///     html! { h1 { "Beta!" } }
/// }
/// ```
pub use autumn_macros::feature_flag;

/// Enforce a record-level [`Policy`](crate::authorization::Policy)
/// before a handler runs. Coexists with [`secured`](macro@secured):
/// `#[secured]` answers "are you in?", `#[authorize]` answers
/// "are you allowed to act on *this record*?"
///
/// # Examples
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
///
/// #[get("/posts/{id}/edit")]
/// #[authorize("update", resource = Post)]
/// async fn edit_post(post: Post) -> AutumnResult<Markup> {
///     Ok(html! { h1 { (post.title) } })
/// }
/// ```
pub use autumn_macros::authorize;
/// Collect `#[job]` handlers into a `Vec<JobInfo>`.
pub use autumn_macros::jobs;
/// Collect `#[listener]` handlers into a `Vec<events::ListenerInfo>`.
pub use autumn_macros::listeners;

/// Collect `#[task]` handlers into a `Vec<task::OneOffTaskInfo>`.
pub use autumn_macros::one_off_tasks;

/// Collect `#[scheduled]` task handlers into a `Vec<TaskInfo>`.
pub use autumn_macros::tasks;

/// Collect `#[static_get]` handlers into a `Vec<StaticRouteMeta>`.
pub use autumn_macros::static_routes;

/// Annotate an async function as a statically pre-rendered GET route.
///
/// Like [`get`], this generates a route companion for Axum routing.
/// Additionally, it emits a `__autumn_static_meta_{name}()` companion
/// that registers the route for static HTML generation at build time
/// (`autumn build`).
///
/// Phase 1 restriction: path parameters (`{id}`) are **not** supported.
/// Use [`get`] for parameterized routes.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[static_get("/about")]
/// async fn about() -> &'static str {
///     "About us"
/// }
/// ```
pub use autumn_macros::static_get;

/// Turn a plain state enum into a statically-verified lifecycle.
///
/// Applied to an enum with an `initial` state, one or more `terminal` states,
/// and a set of `transitions`, this preserves the original enum and appends
/// metadata consts (`LIFECYCLE_INITIAL`, `LIFECYCLE_TERMINALS`,
/// `LIFECYCLE_STATES`, `LIFECYCLE_TRANSITIONS`) plus `can_transition_to` on the
/// enum, and a typestate transition module (named after the enum in
/// `snake_case`) whose `Machine<S>` only exposes `to_<target>` methods for
/// declared edges — firing an undeclared transition is a compile error.
///
/// # Examples
///
/// ```rust,ignore
/// use autumn_web::lifecycle;
///
/// #[lifecycle(
///     initial = Draft,
///     terminal(Archived),
///     transitions(
///         Draft -> Published,
///         Published -> Archived,
///         Published -> Draft,
///     )
/// )]
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// pub enum ArticleState { Draft, Published, Archived }
/// ```
pub use autumn_macros::lifecycle;

/// Marker trait implemented by every `#[lifecycle]` enum, exposing that
/// lifecycle's transition edges as a string-keyed table.
///
/// This is the bridge that lets a field-level `#[state_machine(lifecycle = X)]`
/// on a `#[model]` derive its runtime transitions table from a `#[lifecycle]`
/// enum `X` instead of an inline `transitions(...)` list — "transitions defined
/// once, typed" (issue #1911). The `#[lifecycle]` macro is the *only* thing that
/// implements this trait; referencing a type that is not a `#[lifecycle]` enum in
/// `#[state_machine(lifecycle = ...)]` therefore fails to compile with an
/// unsatisfied `T: Lifecycle` trait bound rather than a cryptic
/// "no associated const" error.
///
/// [`STATE_MACHINE_TRANSITIONS`](Lifecycle::STATE_MACHINE_TRANSITIONS) has the
/// exact `(from, to, guard)` shape the field-level `#[state_machine]` inline
/// table uses, so a lifecycle-derived state machine is byte-for-byte the same
/// runtime construct as the equivalent inline one. Lifecycle transitions carry
/// no guards, so every `guard` slot is `None` (see the `#[state_machine]` docs
/// for the guards rationale).
pub trait Lifecycle {
    /// This lifecycle's declared transition edges as
    /// `(from_variant_name, to_variant_name, guard)` triples, where the variant
    /// names are the enum variants rendered as strings (matching the value
    /// stored in the model's `String` column). The `guard` slot is always
    /// `None` — lifecycle transitions are unguarded.
    const STATE_MACHINE_TRANSITIONS: &'static [(
        &'static str,
        &'static str,
        ::core::option::Option<&'static str>,
    )];
}

/// Context payload delivered to an `on_commit` transition-effect job
/// (issue #1973).
///
/// When a `#[state_machine]` edge declares `on_commit = SomeJob`, firing that
/// edge via the generated `transition_{field}_to_on_conn` method enqueues
/// `SomeJob` **transactionally** on the caller's connection with an instance of
/// this struct as its payload. Because the enqueue writes the job row inside the
/// caller's own transaction, a rollback drops the effect; the durable worker
/// runs it post-commit with full `AppState` (at-least-once delivery).
///
/// Declare the job to receive it, deduping on the derived key so a retried
/// transition coalesces into a single delivery:
///
/// ```rust,ignore
/// #[job(name = "send_shipped_email", unique_by = "idempotency_key")]
/// async fn send_shipped_email(
///     state: AppState,
///     effect: TransitionEffect,
/// ) -> AutumnResult<()> {
///     // effect.model / .field / .record_id / .from_state / .to_state
///     Ok(())
/// }
/// ```
///
/// The [`idempotency_key`](TransitionEffect::idempotency_key) is derived from
/// `(model, field, record_id, from_state, to_state)`, so declaring the job
/// `unique_by = "idempotency_key"` gives idempotent, coalescing delivery.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TransitionEffect {
    /// The model type name whose field transitioned (e.g. `"Order"`).
    pub model: String,
    /// The state-machine field name that transitioned (e.g. `"status"`).
    pub field: String,
    /// The record's primary-key value, rendered as a string.
    pub record_id: String,
    /// The state the field moved from.
    pub from_state: String,
    /// The state the field moved to.
    pub to_state: String,
    /// Derived dedup key:
    /// `"{model}:{field}:{record_id}:{from_state}:{to_state}"`.
    pub idempotency_key: String,
}

/// Internal: returns `true` if `(from, to)` appears as an edge in a
/// `#[lifecycle]` enum's `STATE_MACHINE_TRANSITIONS` table. Used by
/// `#[state_machine(lifecycle = ..., effects(...))]` codegen to reject at
/// compile time an effect declared on an edge the lifecycle does not permit
/// (which would otherwise silently drop the effect). Not part of the public API.
#[doc(hidden)]
#[must_use]
pub const fn __transition_edge_declared(
    table: &[(&str, &str, ::core::option::Option<&str>)],
    from: &str,
    to: &str,
) -> bool {
    // Iterators/`for` are not permitted in a const fn, so index with `while`.
    #[allow(clippy::needless_range_loop)]
    let mut i = 0;
    while i < table.len() {
        let (f, t, _) = table[i];
        if __const_str_eq(f, from) && __const_str_eq(t, to) {
            return true;
        }
        i += 1;
    }
    false
}

/// Internal: byte-wise `&str` equality usable in a const context (where the
/// `PartialEq` `==` operator on `str` is not available). Not part of the
/// public API.
#[doc(hidden)]
#[must_use]
pub const fn __const_str_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    // Iterators/`for` are not permitted in a const fn, so index with `while`.
    #[allow(clippy::needless_range_loop)]
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

// ── Maud re-exports ────────────────────────────────────────────────

/// Rendered HTML fragment produced by the [`html!`] macro.
///
/// This is the standard return type for handlers that render HTML.
/// Re-exported from [Maud](https://maud.lambda.xyz).
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn index() -> Markup {
///     html! { h1 { "Welcome" } }
/// }
/// ```
#[cfg(feature = "maud")]
pub use maud::Markup;

/// Wrap a pre-escaped string so Maud renders it verbatim.
///
/// Use this when you have HTML that was already escaped or generated
/// by another system and you want to embed it in a Maud template
/// without double-escaping.
///
/// Re-exported from [Maud](https://maud.lambda.xyz).
///
/// # Examples
///
/// ```rust
/// use autumn_web::PreEscaped;
///
/// let raw_html = PreEscaped("<em>already escaped</em>".to_string());
/// ```
#[cfg(feature = "maud")]
pub use maud::PreEscaped;

/// Type-safe HTML templating macro.
///
/// Produces a [`Markup`] value containing compiled HTML.
/// Re-exported from [Maud](https://maud.lambda.xyz). See the
/// [Maud book](https://maud.lambda.xyz) for full syntax reference.
///
/// # Examples
///
/// ```rust
/// use autumn_web::html;
///
/// let greeting = "world";
/// let page = html! {
///     h1 { "Hello, " (greeting) "!" }
/// };
/// ```
#[cfg(feature = "maud")]
pub use maud::html;

/// JSON request body extractor and response type.
///
/// When used as a handler parameter, deserializes the request body as JSON.
/// When returned from a handler, serializes the value as JSON with
/// `Content-Type: application/json`.
///
/// Wraps [Axum](https://docs.rs/axum)'s JSON extractor so parse failures use
/// Autumn's Problem Details error contract.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize)]
/// struct CreateItem { name: String }
///
/// #[derive(Serialize)]
/// struct Item { id: i64, name: String }
///
/// #[post("/items")]
/// async fn create(Json(input): Json<CreateItem>) -> Json<Item> {
///     Json(Item { id: 1, name: input.name })
/// }
/// ```
pub use crate::extract::Json;

/// Path extractor.
///
/// Extract typed path parameters from the URL.
///
/// Wraps [Axum](https://docs.rs/axum)'s path extractor so parse failures use
/// Autumn's Problem Details error contract.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/users/{id}")]
/// async fn get_user(Path(id): Path<i32>) -> String {
///     format!("User {id}")
/// }
/// ```
pub use crate::extract::Path;

/// Form data extractor.
pub use crate::extract::Form;

/// Query extractor.
pub use crate::extract::Query;

/// Resolved client IP address after trusted-proxy evaluation.
pub use crate::extract::ClientAddr;

/// Resolved external host after trusted-proxy evaluation.
pub use crate::extract::ClientHost;

/// Resolved external scheme (`"http"` / `"https"`) after trusted-proxy evaluation.
pub use crate::extract::ClientScheme;

/// State extractor.
/// Re-exported from [Axum](https://docs.rs/axum).
pub use axum::extract::State;

/// Re-exports of upstream crates used in macro-generated code.
///
/// These are public so that code generated by `autumn-macros` can reference
/// them as `autumn_web::reexports::axum`, etc. without requiring the user to
/// add those crates as direct dependencies.
///
/// **For advanced use cases only.** Prefer the types re-exported in
/// [`prelude`] or at the crate root. Reach into `reexports` when you
/// need direct access to the underlying framework types (e.g.,
/// `autumn_web::reexports::axum::Router` for custom middleware).
///
/// # Available crates
///
/// | Crate | Re-exported as | Use case |
/// |-------|---------------|----------|
/// | `axum` | `autumn_web::reexports::axum` | Custom routers, middleware, extractors |
/// | `diesel` | `autumn_web::reexports::diesel` | Raw Diesel queries, schema types |
/// | `http` | `autumn_web::reexports::http` | HTTP types (`StatusCode`, `Method`, headers) |
/// | `serde_json` | `autumn_web::reexports::serde_json` | JSON values and conversion helpers |
/// | `tokio` | `autumn_web::reexports::tokio` | Async runtime, spawn, timers |
pub mod reexports {
    pub use axum;
    pub use chrono;
    #[cfg(feature = "db")]
    pub use diesel;
    #[cfg(feature = "db")]
    pub use diesel_async;
    pub use http;
    pub use inventory;
    #[cfg(feature = "mail")]
    pub use lettre;
    pub use rust_decimal;
    #[cfg(feature = "db")]
    pub use scoped_futures;
    pub use serde;
    pub use serde_json;
    pub use tokio;
    pub use tokio_util;
    pub use tracing;
    pub use validator;
}

/// Shared application state passed to route handlers.
pub(crate) mod state;
#[cfg(feature = "system-tests")]
pub mod system_test;
#[allow(
    clippy::missing_panics_doc,
    clippy::must_use_candidate,
    clippy::field_reassign_with_default
)]
pub mod test;
/// Dependency-free HTML parser + CSS-selector matcher backing the structural
/// HTML assertions on [`test::TestResponse`].
mod test_html;
pub use config::ProcessRole;
pub use state::AppState;

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

    #[test]
    fn app_fn_creates_builder() {
        let builder = app::app();
        // Just verify it compiles and can accept routes
        let _builder = builder.routes(vec![]);
    }
}