mini-static 0.16.0

A secure, async static file server with streaming, traversal protection, and connection limits.
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
use std::convert::Infallible;
use std::fs;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime};

use bytes::Bytes;
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::http::response::Builder;
use hyper::service::service_fn;
use hyper::{HeaderMap, Method, Request, Response, StatusCode};
use hyper_util::rt::TokioExecutor;
use hyper_util::rt::TokioIo;
use hyper_util::server::conn::auto::Builder as AutoBuilder;
use tokio::fs::File;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::time::timeout;

use crate::css::{CssOptions, CssTool};
use crate::error::StaticError;
use crate::handler::{FileBody, ResponseBody};
use crate::js::{JsOptions, JsTool};
use crate::reload::{self, SseBody};
use crate::resolve;
use crate::source::SourcePipeline;
use crate::tool;
use crate::watcher::{start_watching, Broadcaster};

const ACCEPT_BACKOFF_INITIAL: Duration = Duration::from_millis(10);
const ACCEPT_BACKOFF_MAX: Duration = Duration::from_secs(1);

/// Default maximum concurrent connections, overridable via `Server::with_max_connections`.
const DEFAULT_MAX_CONNECTIONS: usize = 1024;

/// A source of accepted TCP connections. Abstracted so the accept-error backoff below
/// can be exercised against a listener that fails on demand, without needing to provoke
/// real OS-level accept errors (e.g. EMFILE) in tests.
trait TcpAccept {
    async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)>;
}

impl TcpAccept for TcpListener {
    async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)> {
        TcpListener::accept(self).await
    }
}

/// Accept a connection and reserve it a connection-limit permit.
///
/// `backoff` retries a failed `accept()` after an exponentially growing delay (reset on
/// the next success, capped at `ACCEPT_BACKOFF_MAX`) instead of ending the accept loop,
/// so a sustained failure — the process being out of file descriptors, say — degrades
/// into periodic retries rather than a CPU-bound busy spin or a permanently dead server.
///
/// Returns `None` only if the semaphore itself has been closed (never happens in normal
/// operation, since nothing ever calls `close()` on it — handled so a caller can still
/// fail safely rather than panic).
async fn accept_and_permit<L: TcpAccept>(
    listener: &L,
    backoff: &mut Duration,
    semaphore: &Arc<Semaphore>,
) -> Option<(TcpStream, OwnedSemaphorePermit)> {
    loop {
        let stream = match listener.accept().await {
            Ok((stream, _)) => {
                *backoff = ACCEPT_BACKOFF_INITIAL;
                stream
            }
            Err(_) => {
                tokio::time::sleep(*backoff).await;
                *backoff = (*backoff * 2).min(ACCEPT_BACKOFF_MAX);
                continue;
            }
        };
        return semaphore
            .clone()
            .acquire_owned()
            .await
            .ok()
            .map(|permit| (stream, permit));
    }
}

/// A predicate deciding whether a resolved file path should get an immutable cache
/// policy; see [`Server::with_immutable_assets`].
type ImmutablePredicate = Arc<dyn Fn(&Path) -> bool + Send + Sync>;

/// A static file server for serving files securely from a root directory.
///
/// `Server` canonicalizes the root directory once at creation time and uses the
/// canonical form for all subsequent requests, avoiding repeated filesystem calls.
///
/// # Security
///
/// The server protects against:
/// - Path traversal attacks (e.g., `../../etc/passwd`)
/// - Accessing files outside the root via symlinks
/// - Disclosing filesystem structure (traversal and missing files both return 404)
///
/// # Cloning
///
/// `Server` is cheap to clone: a `PathBuf`, a couple of primitives, and an `Arc`'d
/// predicate closure. Multiple clones can be used concurrently in async tasks without
/// synchronization overhead.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use mini_static::Server;
/// use std::path::Path;
/// use std::time::Duration;
///
/// let server = Server::new(Path::new("./public"))?;
/// let (port, _handle) = server.run(Duration::from_secs(30)).await?;
/// println!("Server running on port {}", port);
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Server {
    root_canon: PathBuf,
    bundle_roots: Vec<PathBuf>,
    max_connections: usize,
    live_reload: bool,
    broadcaster: Option<Broadcaster>,
    immutable_predicate: Option<ImmutablePredicate>,
    source_folders: Vec<PathBuf>,
    output_dir: PathBuf,
    css_tool: Option<(CssTool, CssOptions)>,
    js_tool: Option<(JsTool, JsOptions)>,
    prune_output: bool,
}

/// True when two canonical paths are the same path or one contains the other.
///
/// Used by the source/output overlap check: `Path::starts_with` compares component-wise, so
/// `/a/b` neither equals nor contains their sibling `/a/b/c` itself. This is the single
/// place the overlap rule is defined, so both `with_source_folder` and `with_output_dir`
/// cannot drift apart.
fn paths_overlap(a: &Path, b: &Path) -> bool {
    a.starts_with(b) || b.starts_with(a)
}

impl Server {
    /// Create a new server with the given root directory.
    ///
    /// Canonicalizes the root once at startup. All subsequent requests use the
    /// canonical root without re-canonicalizing it, making this suitable for long-lived servers.
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if the root cannot be canonicalized (e.g., doesn't exist,
    /// no read permissions).
    pub fn new(root: &Path) -> Result<Self, StaticError> {
        let root_canon = root.canonicalize().map_err(StaticError::Io)?;
        let output_dir = root_canon.clone();
        Ok(Server {
            root_canon,
            bundle_roots: Vec::new(),
            max_connections: DEFAULT_MAX_CONNECTIONS,
            live_reload: false,
            broadcaster: None,
            immutable_predicate: None,
            source_folders: Vec::new(),
            output_dir,
            css_tool: None,
            js_tool: None,
            prune_output: false,
        })
    }

    /// Set the maximum number of connections served concurrently (default 1024).
    ///
    /// Once this many connections are in flight, `run()`'s accept loop stops accepting
    /// new ones — without pausing the accept loop, a client that opens a connection and
    /// sends nothing (see the header-read timeout docs on [`Server::run_on`]) could
    /// otherwise be used, in enough parallel copies, to exhaust the process's file
    /// descriptors or memory with no bound at all.
    pub fn with_max_connections(mut self, max: usize) -> Self {
        self.max_connections = max;
        self
    }

    /// Enable live-reload for this server (disabled by default).
    ///
    /// Once enabled, the `run*` methods start a background watcher (mtime polling,
    /// bounded 500ms interval — see [`crate::start_watching`]) over the server's root
    /// the first time the server actually starts accepting connections, and:
    ///
    /// - serve a live-reload SSE stream at [`crate::LIVE_RELOAD_PATH`], broadcasting a
    ///   change event (with [`crate::ChangeType`]) whenever a served file is added,
    ///   modified, or removed;
    /// - inject a small `<script>` into every served `text/html` response that connects
    ///   to that stream and reloads the page (or hot-swaps stylesheet `<link>`s, for CSS
    ///   changes) — no manual client wiring required.
    ///
    /// This is meant for local development, not production: leave it disabled (the
    /// default) for any server serving real traffic. A typical call site gates it behind
    /// `#[cfg(debug_assertions)]` so a release build never pays for the watcher or the
    /// injected script.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?;
    /// #[cfg(debug_assertions)]
    /// let server = server.with_live_reload();
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_live_reload(mut self) -> Self {
        self.live_reload = true;
        self
    }

    /// Serve files matching `predicate` with a long-lived, immutable cache policy
    /// instead of the default `Cache-Control: no-cache`.
    ///
    /// `predicate` is evaluated against each resolved file's path; a match sends
    /// `Cache-Control: public, max-age=31536000, immutable` on that file's 200 and 304
    /// responses. This is correct only for fingerprinted assets (e.g.
    /// `main.a1b2c3.js`) where a content change always produces a new filename —
    /// caching a mutable filename indefinitely would serve stale content to every
    /// client that already has it cached.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_immutable_assets(|path| {
    ///         path.file_name()
    ///             .and_then(|name| name.to_str())
    ///             .is_some_and(|name| name.contains(".fingerprint."))
    ///     });
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_immutable_assets<F>(mut self, predicate: F) -> Self
    where
        F: Fn(&Path) -> bool + Send + Sync + 'static,
    {
        self.immutable_predicate = Some(Arc::new(predicate));
        self
    }

    /// The `Cache-Control` header value for a resolved file path: the immutable policy
    /// if `with_immutable_assets`'s predicate matches, `no-cache` otherwise.
    fn cache_control_for(&self, path: &Path) -> &'static str {
        match &self.immutable_predicate {
            Some(predicate) if predicate(path) => "public, max-age=31536000, immutable",
            _ => "no-cache",
        }
    }

    /// Register `path` as an additional directory whose changes should trigger a CSS
    /// bundle rebuild, alongside the registered source folders.
    ///
    /// Useful for build pipelines where CSS partials referenced via `@import` live in a
    /// separate directory tree from the source folders proper: without registering that
    /// tree here, editing a partial wouldn't be noticed by the watcher and the bundle
    /// would go stale until something else touched it.
    ///
    /// Files under `path` are never directly HTTP-servable: `Server::resolve` and the
    /// request-handling path never consult bundle roots. This is purely a watch target,
    /// not a second served root, and — since `@import` resolution is delegated entirely
    /// to the configured [`CssTool`] (see [`Server::with_css_tool`]) — not an `@import`
    /// traversal boundary either; the external tool resolves its own imports with no
    /// root mini-static can enforce.
    ///
    /// This method is fallible and canonicalizes the path once at call time, matching
    /// `Server::new`'s canonicalize-once policy. Call it multiple times to register
    /// more than one external source tree.
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if the path cannot be canonicalized.
    pub fn with_bundle_root(mut self, path: &Path) -> Result<Self, StaticError> {
        let canon = path.canonicalize().map_err(StaticError::Io)?;
        self.bundle_roots.push(canon);
        Ok(self)
    }

    /// Designate `dir` as a source folder whose changes drive the build pipelines.
    ///
    /// Watched when `with_live_reload()` is enabled; `.css` files under it feed the single
    /// CSS bundle, `.js`/`.mjs` files are minified per-file into the output dir.
    ///
    /// Rejected if `dir` overlaps the output dir or an already-registered source folder: a
    /// source folder that is also the output would feed every pipeline its own output — the
    /// feedback loop this layering exists to prevent.
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if `dir` cannot be canonicalized, or
    /// `Err(StaticError::Traversal)` if it overlaps the output dir or another source folder.
    pub fn with_source_folder(mut self, dir: &Path) -> Result<Self, StaticError> {
        let canon = dir.canonicalize().map_err(StaticError::Io)?;

        if paths_overlap(&canon, &self.output_dir) {
            return Err(StaticError::Traversal(format!(
                "source folder {} overlaps the output dir {}",
                canon.display(),
                self.output_dir.display()
            )));
        }
        if self
            .source_folders
            .iter()
            .any(|existing| paths_overlap(&canon, existing))
        {
            return Err(StaticError::Traversal(format!(
                "source folder {} overlaps an already-registered source folder",
                canon.display()
            )));
        }

        self.source_folders.push(canon);
        Ok(self)
    }

    /// Designate `dir` as the output directory processed outputs are written to.
    ///
    /// Defaults to the served root. The output dir is never a watcher trigger: pipelines
    /// react to source folders only, so a pipeline's own output can never re-trigger it.
    /// Call this before `with_css_tool` so a bundle output path reflects the override.
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if `dir` cannot be canonicalized, or
    /// `Err(StaticError::Traversal)` if it overlaps a registered source folder.
    pub fn with_output_dir(mut self, dir: &Path) -> Result<Self, StaticError> {
        let canon = dir.canonicalize().map_err(StaticError::Io)?;

        if self
            .source_folders
            .iter()
            .any(|existing| paths_overlap(&canon, existing))
        {
            return Err(StaticError::Traversal(format!(
                "output dir {} overlaps a registered source folder",
                canon.display()
            )));
        }

        self.output_dir = canon;
        Ok(self)
    }

    /// Configure CSS bundling/minification via an external tool (disabled by default).
    ///
    /// `tool` is a preset naming the CLI mini-static invokes (see [`CssTool`]) —
    /// mini-static does not install or manage the binary, only looks it up on `PATH`;
    /// [`Server::run_on`] fails fast at startup if it's missing. `options` selects
    /// `bundle`/`minify` independently (see [`CssOptions`]):
    ///
    /// - Neither: every `.css` under the source folders is copied through unchanged,
    ///   mirrored into the output dir.
    /// - `minify` only: each file is minified independently and mirrored (no `@import`
    ///   following).
    /// - `bundle` only: every `.css` under the source folders is discovered,
    ///   `@import`-resolved, and concatenated into one output file, unminified.
    /// - Both: the bundle above, minified.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::{CssOptions, CssTool, Server};
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_css_tool(CssTool::LightningCss, CssOptions::new().bundle(true).minify(true));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_css_tool(mut self, tool: CssTool, options: CssOptions) -> Self {
        self.css_tool = Some((tool, options));
        self
    }

    /// Configure JS bundling/minification via an external tool (disabled by default).
    ///
    /// `tool` is a preset naming the CLI mini-static invokes (see [`JsTool`]) —
    /// mini-static does not install or manage the binary, only looks it up on `PATH`;
    /// [`Server::run_on`] fails fast at startup if it's missing. Unlike CSS, JS bundling
    /// requires an explicit entry point ([`JsOptions::bundle_entry`]) since a JS module
    /// graph has no well-defined "concatenate everything" meaning; without it, `options`
    /// runs in per-file mode (every `.js`/`.mjs` under the source folders processed and
    /// mirrored independently).
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if `options` specifies a bundle entry that cannot
    /// be canonicalized, or `Err(StaticError::Traversal)` if it doesn't lie under a
    /// registered source folder — checked eagerly here so a bad entry path fails at
    /// configuration time, not on the first rebuild.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::{JsOptions, JsTool, Server};
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_source_folder(Path::new("./js-src"))?
    ///     .with_js_tool(
    ///         JsTool::Esbuild,
    ///         JsOptions::new()
    ///             .bundle_entry(Path::new("./js-src/main.js"), "bundle.js")
    ///             .minify(true),
    ///     )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_js_tool(mut self, tool: JsTool, options: JsOptions) -> Result<Self, StaticError> {
        if let Some(entry) = options.entry() {
            let entry_canon = entry.canonicalize().map_err(StaticError::Io)?;
            let under_source_folder = self
                .source_folders
                .iter()
                .any(|folder| entry_canon.starts_with(folder));
            if !under_source_folder {
                return Err(StaticError::Traversal(format!(
                    "js bundle entry {} is not under any registered source folder",
                    entry_canon.display()
                )));
            }
        }

        self.js_tool = Some((tool, options));
        Ok(self)
    }

    /// Remove stale CSS bundle output at build time — specifically, delete the bundle file
    /// when no CSS sources remain, rather than serving an orphan. Applies only to the
    /// one-shot startup build, never during live-reload.
    pub fn with_prune_output(mut self) -> Self {
        self.prune_output = true;
        self
    }

    /// True when any build pipeline is configured (a CSS/JS tool and/or a source
    /// folder), i.e. the server should run a startup build.
    fn has_pipeline(&self) -> bool {
        self.css_tool.is_some() || self.js_tool.is_some() || !self.source_folders.is_empty()
    }

    /// Every external tool binary this configuration actually needs at some point
    /// (bundle and/or minify enabled — a pure passthrough config never spawns its
    /// configured tool, so it has nothing to fail-fast on), paired with its
    /// human-readable install hint for a fail-fast startup error.
    fn required_tool_binaries(&self) -> Vec<(&'static str, &'static str)> {
        let mut required = Vec::new();
        if let Some((css_tool, options)) = &self.css_tool {
            if options.is_bundle() || options.is_minify() {
                required.push((css_tool.binary_name(), css_tool.install_hint()));
            }
        }
        if let Some((js_tool, options)) = &self.js_tool {
            if options.is_bundle() || options.is_minify() {
                required.push((js_tool.binary_name(), js_tool.install_hint()));
            }
        }
        required
    }

    /// Every directory to watch for source changes: the source folders plus the CSS
    /// `@import` roots, deduplicated so a directory registered as both is watched once.
    fn watch_targets(&self) -> Vec<PathBuf> {
        let mut targets = Vec::new();
        for dir in self.source_folders.iter().chain(self.bundle_roots.iter()) {
            if !targets.contains(dir) {
                targets.push(dir.clone());
            }
        }
        targets
    }

    /// Resolve a request path under the server's root.
    ///
    /// This is a lower-level API for resolving paths without generating HTTP responses.
    /// For most use cases, prefer [`Server::handle_request`] or the `run*` methods.
    ///
    /// # Returns
    ///
    /// - `Ok(PathBuf)` if the path resolves to a file within root.
    /// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
    pub fn resolve(&self, request_path: &str) -> Result<PathBuf, StaticError> {
        resolve::resolve_with_canonical_root(&self.root_canon, request_path)
    }

    /// Run the server on a specific address with a configurable header-read timeout.
    ///
    /// Spawns the server in a background Tokio task and returns immediately with the
    /// assigned port number and a [`ServerHandle`]. Call `handle.shutdown().await` to
    /// stop accepting new connections and wait for in-flight connections to finish.
    /// Dropping the handle instead leaves the server running for the life of the process.
    ///
    /// # Header-Read Timeout
    ///
    /// Connections that don't send complete HTTP headers within `header_timeout` are closed.
    /// This prevents slowloris attacks and resource exhaustion from incomplete requests. The
    /// timeout applies only to the header-read phase — once a complete header block has been
    /// read, the connection is handed off with no further time bound, so long-lived response
    /// bodies (e.g. the live-reload SSE stream from [`Server::with_live_reload`]) are not cut
    /// off mid-stream.
    ///
    /// # Precompressed Sidecars
    ///
    /// If a request's `Accept-Encoding` allows `br` or `gzip` (preferring `br`) and a
    /// sibling `<path>.br`/`<path>.gz` exists next to the resolved file, its bytes are
    /// served instead with a matching `Content-Encoding`. Every file response carries
    /// `Vary: Accept-Encoding` so intermediate caches don't serve the wrong variant to a
    /// differently-capable client.
    ///
    /// # Arguments
    ///
    /// * `addr` - Socket address to bind to (e.g., `127.0.0.1:0` for loopback ephemeral,
    ///   or `0.0.0.0:8080` to bind all interfaces on a fixed port).
    /// * `header_timeout` - Maximum time to wait for complete HTTP headers on each connection.
    ///
    /// # Returns
    ///
    /// - `Ok((u16, ServerHandle))` with the assigned port number and a handle for graceful shutdown.
    /// - `Err(StaticError::Io)` if binding to the socket fails.
    /// - `Err(StaticError::PipelineSetup)` if a configured [`CssTool`]/[`JsTool`]'s binary
    ///   is not found on `PATH`. Checked before the listener binds: a deployment whose
    ///   configured pipeline can never run should fail visibly at boot, not be discovered
    ///   later as a missing/stale asset.
    pub async fn run_on(
        &self,
        addr: SocketAddr,
        header_timeout: Duration,
    ) -> Result<(u16, ServerHandle), StaticError> {
        for (binary, install_hint) in self.required_tool_binaries() {
            if !tool::locate_on_path(binary) {
                return Err(StaticError::PipelineSetup(format!(
                    "{binary} not found on PATH ({install_hint})"
                )));
            }
        }

        let listener = TcpListener::bind(addr).await.map_err(StaticError::Io)?;
        let port = listener.local_addr().map_err(StaticError::Io)?.port();

        let mut server = self.clone();
        if server.live_reload {
            let broadcaster = Broadcaster::new();

            // The build pipelines react to SOURCE folders only; the output dir is never
            // watched. Watching the output would feed each pipeline its own writes back
            // into its trigger — the feedback loop this layering exists to prevent.
            if server.has_pipeline() {
                let pipeline = Arc::new(SourcePipeline::new(
                    server.source_folders.clone(),
                    server.bundle_roots.clone(),
                    server.output_dir.clone(),
                    server.css_tool.clone(),
                    server.js_tool.clone(),
                    server.prune_output,
                    broadcaster.clone(),
                ));
                let mut rx = broadcaster.subscribe();
                tokio::spawn(async move {
                    // One-shot startup build (and optional prune) first, so the earliest
                    // request already sees fresh output rather than yesterday's.
                    if let Err(e) = pipeline.full_build().await {
                        eprintln!("source pipeline build error: {e}");
                    }
                    while let Some(event) = rx.recv().await {
                        if let Err(e) = pipeline
                            .process_change(&event.path, &event.change_type)
                            .await
                        {
                            eprintln!("source pipeline error: {e}");
                        }
                    }
                });
            }

            for dir in server.watch_targets() {
                start_watching(Arc::new(dir), broadcaster.clone());
            }

            server.broadcaster = Some(broadcaster);
        } else if server.has_pipeline() {
            // No live-reload: still run the one-shot build so a release boot reflects the
            // current sources. The broadcaster is a throwaway — there is no browser to
            // notify, so broadcasting into it is a no-op.
            let pipeline = Arc::new(SourcePipeline::new(
                server.source_folders.clone(),
                server.bundle_roots.clone(),
                server.output_dir.clone(),
                server.css_tool.clone(),
                server.js_tool.clone(),
                server.prune_output,
                Broadcaster::new(),
            ));
            tokio::spawn(async move {
                if let Err(e) = pipeline.full_build().await {
                    eprintln!("source pipeline build error: {e}");
                }
            });
        }
        let semaphore = Arc::new(Semaphore::new(server.max_connections));
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();

        let accept_task = tokio::spawn(async move {
            let mut backoff = ACCEPT_BACKOFF_INITIAL;
            let mut join_set: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
            let mut shutdown_pin = std::pin::pin!(shutdown_rx);
            let mut shutting_down = false;

            loop {
                if !shutting_down {
                    // The accept-and-permit step and the shutdown signal race in a single
                    // `select!` so shutdown can preempt a pending accept or a permit wait
                    // cleanly, at any point — not just between loop iterations.
                    tokio::select! {
                        accepted = accept_and_permit(&listener, &mut backoff, &semaphore) => {
                            match accepted {
                                Some((stream, permit)) => {
                                    let server = server.clone();
                                    join_set.spawn(async move {
                                        let _permit = permit;
                                        serve_connection(stream, server, header_timeout).await;
                                    });
                                }
                                None => shutting_down = true,
                            }
                        }
                        _ = shutdown_pin.as_mut() => {
                            shutting_down = true;
                        }
                    }
                    continue;
                }

                // Stop accepting; drain already-spawned connections before returning.
                match join_set.join_next().await {
                    Some(_) => continue,
                    None => break,
                }
            }
        });

        Ok((
            port,
            ServerHandle {
                shutdown_tx: Some(shutdown_tx),
                accept_task,
            },
        ))
    }

    /// Run the server on loopback (127.0.0.1), binding an ephemeral port.
    ///
    /// Thin wrapper around [`Server::run_on`] — see it for the header-read timeout and
    /// sidecar semantics, and for what the returned [`ServerHandle`] does.
    pub async fn run(&self, header_timeout: Duration) -> Result<(u16, ServerHandle), StaticError> {
        self.run_on(([127, 0, 0, 1], 0).into(), header_timeout)
            .await
    }

    /// Run the server on all interfaces (0.0.0.0) at `port` (0 for an ephemeral port).
    ///
    /// Useful for containerized deployments and reverse-proxy setups. Thin wrapper
    /// around [`Server::run_on`] — see it for the header-read timeout and sidecar
    /// semantics, and for what the returned [`ServerHandle`] does.
    pub async fn run_all(
        &self,
        port: u16,
        header_timeout: Duration,
    ) -> Result<(u16, ServerHandle), StaticError> {
        self.run_on(([0, 0, 0, 0], port).into(), header_timeout)
            .await
    }

    /// Run the server on loopback with the default 30-second header-read timeout.
    ///
    /// The recommended entry point for tests and lightweight services that don't need a
    /// custom timeout. Thin wrapper around [`Server::run`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?;
    /// let (port, handle) = server.run_ephemeral().await?;
    /// println!("Server ready on http://127.0.0.1:{}", port);
    /// handle.shutdown().await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run_ephemeral(&self) -> Result<(u16, ServerHandle), StaticError> {
        self.run(DEFAULT_HEADER_TIMEOUT).await
    }

    /// Produce the HTTP response for a request, streaming file bodies to the client.
    ///
    /// This is the crate's single request-handling path: the `run*` accept loop calls it,
    /// and so should any async server embedding `mini-static` as a fallback route (e.g.
    /// `mini-unified`). It never blocks the calling task — path resolution runs on Tokio's
    /// blocking-thread pool via `spawn_blocking`, and the file is read via async I/O.
    ///
    /// File responses are backed by `FileBody`, which hands hyper one 64 KB chunk at a
    /// time as `poll_frame` is driven: memory use stays bounded to one chunk per in-flight
    /// response regardless of file size.
    ///
    /// `headers` are the request's headers; `If-None-Match` (304 on a matching ETag) and
    /// `Accept-Encoding` (precompressed sidecar selection, see [`Server::run_on`]) are the
    /// ones read today. Only `GET` and `HEAD` are allowed; anything else gets a 405 with an
    /// `Allow` header. Missing files and traversal attempts both get an identical 404, so a
    /// response never discloses whether a path exists outside the root.
    pub async fn handle_request(
        &self,
        method: &Method,
        request_path: &str,
        headers: &HeaderMap,
    ) -> Response<ResponseBody> {
        if method != Method::GET && method != Method::HEAD {
            return text(
                response(StatusCode::METHOD_NOT_ALLOWED).header("Allow", "GET, HEAD"),
                "method not allowed\n",
            );
        }

        // Live-reload SSE stream — only reachable when `with_live_reload()` was called
        // and the server was started via a `run*` method (those are the only paths that
        // populate `broadcaster`).
        if *method == Method::GET && request_path == reload::LIVE_RELOAD_PATH {
            if let Some(broadcaster) = &self.broadcaster {
                return finish(
                    response(StatusCode::OK)
                        .header("Content-Type", "text/event-stream")
                        .header("Cache-Control", "no-cache")
                        .header("Connection", "keep-alive")
                        .body(ResponseBody::Sse(SseBody::new(broadcaster.subscribe()))),
                );
            }
        }

        // `resolve()` does blocking filesystem syscalls (`canonicalize()`, up to two per
        // request). Running those directly in this `async fn` would block whichever
        // Tokio worker thread happens to be driving it, stalling every other task
        // scheduled on that thread for the duration of the syscalls. `spawn_blocking`
        // moves the work onto Tokio's dedicated blocking thread pool instead.
        let server = self.clone();
        let owned_request_path = request_path.to_string();
        let resolved =
            tokio::task::spawn_blocking(move || server.resolve(&owned_request_path)).await;
        let path = match resolved {
            Err(_) => return internal_error_response(),
            Ok(Err(e)) => {
                return text(
                    response(StatusCode::NOT_FOUND),
                    format!("{}\n", e.user_message()),
                )
            }
            Ok(Ok(path)) => path,
        };

        // A directory served via its `index.html` needs a trailing slash to establish the
        // correct base for the page's relative links. Compare against the *decoded*
        // request path so a percent-encoded explicit request for index.html (e.g.
        // `/docs/index.htm%6c`) is recognized as such instead of producing a redirect to a
        // still-encoded, broken Location.
        let decoded_request_path = resolve::decode_request_path(request_path);
        if path.file_name().is_some_and(|name| name == "index.html")
            && !decoded_request_path.ends_with('/')
            && !decoded_request_path.ends_with("index.html")
        {
            // `location` is built from the (attacker-controlled) request path; `finish()`
            // degrades to 400 instead of panicking if it ever contains bytes invalid in a
            // header value.
            let location = format!("{}/", request_path.trim_end_matches('/'));
            return text(
                response(StatusCode::MOVED_PERMANENTLY).header("Location", location),
                "moved\n",
            );
        }

        let Ok(file) = File::open(&path).await else {
            return internal_error_response();
        };
        let Ok(metadata) = file.metadata().await else {
            return internal_error_response();
        };

        let content_type = mime_type_for_path(&path);
        // Live-reload HTML injection needs the original, uncompressed bytes to splice the
        // reload script into — never substitute a precompressed sidecar on this path.
        let html_injection = self.broadcaster.is_some() && content_type.starts_with("text/html");

        let accept_encoding = header_str(headers, "accept-encoding");
        let sidecar = if html_injection {
            None
        } else {
            select_precompressed_sidecar(&path, accept_encoding).await
        };
        let (mut file, metadata, content_encoding) = match sidecar {
            Some((sidecar_file, sidecar_metadata, encoding)) => {
                (sidecar_file, sidecar_metadata, Some(encoding))
            }
            None => (file, metadata, None),
        };

        // HTML injection is skipped for a served precompressed sidecar (already final
        // bytes from a build step) — see `html_injection`'s definition above.
        let etag = generate_etag(&metadata);
        let cache_control = self.cache_control_for(&path);

        if header_str(headers, "if-none-match").is_some_and(|value| is_etag_match(value, &etag)) {
            return finish(
                Response::builder()
                    .status(StatusCode::NOT_MODIFIED)
                    .header("Cache-Control", cache_control)
                    .header("Vary", "Accept-Encoding")
                    .header("ETag", etag)
                    .body(ResponseBody::Buffered(Full::new(Bytes::new()))),
            );
        }

        // `Some` when the served representation differs from the file's raw bytes and had
        // to be built in memory; `None` means stream the open file as-is. Computed before
        // the HEAD check below because RFC 9110 requires a HEAD response's headers —
        // `Content-Length` included — to match what a GET would send, even though the body
        // itself is dropped.
        let transformed: Option<Bytes> = if html_injection {
            let mut html = Vec::with_capacity(metadata.len() as usize);
            if file.read_to_end(&mut html).await.is_err() {
                return internal_error_response();
            }
            reload::inject_reload_script(&mut html);
            Some(Bytes::from(html))
        } else {
            None
        };

        let file_size = transformed
            .as_ref()
            .map_or(metadata.len(), |bytes| bytes.len() as u64);

        // HEAD must not return a body (RFC 9110).
        let body = if *method == Method::HEAD {
            ResponseBody::Buffered(Full::new(Bytes::new()))
        } else {
            match transformed {
                Some(bytes) => ResponseBody::Buffered(Full::new(bytes)),
                None => ResponseBody::Streamed(FileBody::new(file)),
            }
        };

        let mut builder = response(StatusCode::OK)
            .header("Content-Type", content_type)
            .header("Content-Length", file_size.to_string())
            .header("Cache-Control", cache_control)
            .header("Vary", "Accept-Encoding")
            .header("ETag", etag);
        if let Some(encoding) = content_encoding {
            builder = builder.header("Content-Encoding", encoding);
        }
        finish(builder.body(body))
    }
}

/// Ceiling on how many bytes `read_header_prefix` buffers before giving up. Without this,
/// a client that trickles bytes forever without ever sending the terminating blank line
/// could grow the buffer without limit — the header-read timeout alone doesn't bound
/// memory, only wall-clock time, and a sufficiently patient sender could still send
/// unbounded data before the deadline fires.
const MAX_HEADER_BYTES: usize = 64 * 1024;

/// Why `read_header_prefix` gave up before seeing a complete header block. Every variant
/// is a legitimate reason to drop the connection — none is treated specially by the
/// caller today, but the distinction is worth preserving for anyone debugging this later.
#[derive(Debug)]
enum HeaderReadError {
    /// The client closed the connection (or shut down its write half) before sending a
    /// complete header block.
    ConnectionClosed,
    /// More than `MAX_HEADER_BYTES` were buffered without seeing `\r\n\r\n`.
    TooLarge,
    /// The underlying socket read failed. Kept rather than discarded so a future `log`
    /// feature has the real I/O error to report instead of an opaque unit variant.
    #[allow(dead_code)]
    Io(std::io::Error),
}

/// Reads from `stream` until a complete HTTP header block (`\r\n\r\n`) has been buffered,
/// returning every byte read so far — which may include bytes past the header block
/// (request body, or a second pipelined request) if the client sent them in the same
/// read. Callers pair this with `tokio::time::timeout` to bound how long the header phase
/// itself may take; this function has no timeout of its own, only the size ceiling in
/// `MAX_HEADER_BYTES`.
async fn read_header_prefix(stream: &mut TcpStream) -> Result<Vec<u8>, HeaderReadError> {
    let mut buf = Vec::new();
    let mut chunk = [0u8; 4096];

    loop {
        let n = stream.read(&mut chunk).await.map_err(HeaderReadError::Io)?;
        if n == 0 {
            return Err(HeaderReadError::ConnectionClosed);
        }
        buf.extend_from_slice(&chunk[..n]);

        if buf.len() > MAX_HEADER_BYTES {
            return Err(HeaderReadError::TooLarge);
        }
        // Only the tail can hold a terminator this read completed: the `n` new bytes plus
        // the 3 before them. Rescanning the whole buffer every time would make the header
        // read quadratic in the bytes received.
        let scan_from = buf.len().saturating_sub(n + 3);
        if buf[scan_from..].windows(4).any(|w| w == b"\r\n\r\n") {
            return Ok(buf);
        }
    }
}

/// Wraps an accepted `TcpStream` whose header block has already been drained into
/// `prefix` (by `read_header_prefix`, ahead of the connection being handed to hyper).
/// Reads replay `prefix` first, then fall through to the live socket — so hyper sees
/// exactly the byte stream it would have seen without the pre-read, just sourced from two
/// buffers back-to-back instead of one continuous one. Writes pass straight through.
struct PrefixedIo {
    prefix: Bytes,
    prefix_pos: usize,
    inner: TcpStream,
}

impl PrefixedIo {
    fn new(prefix: Vec<u8>, inner: TcpStream) -> Self {
        PrefixedIo {
            prefix: Bytes::from(prefix),
            prefix_pos: 0,
            inner,
        }
    }
}

impl AsyncRead for PrefixedIo {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        let this = self.get_mut();
        if this.prefix_pos < this.prefix.len() {
            let remaining = &this.prefix[this.prefix_pos..];
            let n = remaining.len().min(buf.remaining());
            buf.put_slice(&remaining[..n]);
            this.prefix_pos += n;
            return Poll::Ready(Ok(()));
        }
        Pin::new(&mut this.inner).poll_read(cx, buf)
    }
}

impl AsyncWrite for PrefixedIo {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
    }
}

/// Wires an accepted connection up to the hyper HTTP/1 service.
///
/// `header_timeout` bounds only the header-read phase (`read_header_prefix`, run before
/// hyper ever sees the connection). Once a complete header block has been read, the
/// connection is handed to hyper with no further time bound — deliberately, since a
/// response body may legitimately outlive `header_timeout` by design (the live-reload SSE
/// stream is the motivating case: it stays open until a watched file changes, which may
/// be minutes or hours after the request). Wrapping the whole connection lifetime in
/// `header_timeout` — the prior implementation — silently truncated exactly that stream
/// once `header_timeout` elapsed, aborting the response mid-write after headers had
/// already been sent (the client observes this as a chunked-encoding error, not a clean
/// close). The connection-count ceiling (`Server::with_max_connections`) is what bounds
/// resource use from connections held open indefinitely, not this timeout.
async fn serve_connection(mut stream: TcpStream, server: Server, header_timeout: Duration) {
    let prefix = match timeout(header_timeout, read_header_prefix(&mut stream)).await {
        Ok(Ok(prefix)) => prefix,
        Ok(Err(_)) | Err(_) => return,
    };

    let io = TokioIo::new(PrefixedIo::new(prefix, stream));
    let svc = service_fn(move |req: Request<Incoming>| {
        let server = server.clone();
        async move {
            let resp = server
                .handle_request(req.method(), req.uri().path(), req.headers())
                .await;
            Ok::<_, Infallible>(resp)
        }
    });
    let _ = AutoBuilder::new(TokioExecutor::new())
        .serve_connection(io, svc)
        .await;
}

/// Default header-read timeout used by [`Server::run_ephemeral`].
const DEFAULT_HEADER_TIMEOUT: Duration = Duration::from_secs(30);

/// Default grace period `ServerHandle::shutdown()` waits for in-flight connections to
/// finish on their own before aborting whatever is left. A connection with no
/// self-imposed end — an open live-reload SSE stream, or any keep-alive connection whose
/// peer simply never closes it — would otherwise let `shutdown()` hang forever waiting
/// for it to finish naturally. Every wait in this crate has a stated upper bound;
/// shutdown is no exception.
const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);

/// A handle to a server started by one of the `Server::run*` methods.
///
/// Dropping this handle without calling `shutdown()` leaves the server running in the
/// background for the life of the process. Call `shutdown()` to stop accepting new
/// connections and wait for already-accepted connections to finish before returning.
pub struct ServerHandle {
    shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
    accept_task: tokio::task::JoinHandle<()>,
}

impl ServerHandle {
    /// Stop accepting new connections and wait up to `DEFAULT_SHUTDOWN_DRAIN_TIMEOUT`
    /// (5s) for in-flight connections to finish on their own. Equivalent to
    /// `shutdown_with_timeout(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT)` — see that method for what
    /// happens to connections still open once the grace period elapses.
    pub async fn shutdown(self) {
        self.shutdown_with_timeout(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT)
            .await;
    }

    /// Stop accepting new connections and wait up to `drain_timeout` for in-flight
    /// connections to finish on their own.
    ///
    /// Connections still open once `drain_timeout` elapses are aborted rather than
    /// waited on further: dropping the accept task drops its `JoinSet`, which aborts
    /// every task still tracked in it (see `tokio::task::JoinSet`'s own drop behavior) —
    /// which in turn drops each connection's socket, closing it. This is what bounds
    /// shutdown when a connection has no natural end of its own (the live-reload SSE
    /// stream is the motivating case: it stays open until a watched file changes, which
    /// may never happen before the process needs to exit).
    pub async fn shutdown_with_timeout(mut self, drain_timeout: Duration) {
        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(());
        }
        if timeout(drain_timeout, &mut self.accept_task).await.is_err() {
            self.accept_task.abort();
        }
    }
}

/// Read a request header as a `&str`, or `None` if it's absent or not valid ASCII.
fn header_str<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> {
    headers.get(name).and_then(|value| value.to_str().ok())
}

/// Start a response carrying the baseline security header every response in this crate
/// sends. The 304 path is the one exception and builds its own — a 304 repeats only the
/// caching validators, not the full header set.
fn response(status: StatusCode) -> Builder {
    Response::builder()
        .status(status)
        .header("X-Content-Type-Options", "nosniff")
}

/// Finish `builder` with a plain-text body. `&'static str` bodies borrow rather than
/// allocate; `String` bodies (the 404 message) are moved in.
fn text(builder: Builder, body: impl Into<Bytes>) -> Response<ResponseBody> {
    finish(builder.body(ResponseBody::Buffered(Full::new(body.into()))))
}

/// Finishes building a response, degrading to a generic 400 instead of panicking if any
/// header value turns out to be invalid for use as an HTTP header value.
///
/// Every header value that reaches `Response::builder()` in this module is either a
/// static string or formatted from internal, already-validated data (a byte count, an
/// mtime, a fixed method list) — none of it can actually fail today. But `.unwrap()`
/// on that assumption is exactly the kind of thing that turns "can't happen" into a
/// production panic the day someone adds a header built from new input without
/// re-deriving that guarantee. Routing every response through this one fallible path
/// means that mistake fails safe instead of panicking.
fn finish(built: Result<Response<ResponseBody>, hyper::http::Error>) -> Response<ResponseBody> {
    built.unwrap_or_else(|_| bad_request_response())
}

// `internal_error_response()` and `bad_request_response()` are the fallback responses
// `finish()` itself degrades to — every header and body here is a fixed string with no
// external input, so `.body(...)` cannot fail. They can't be routed through `finish()`
// without it degrading to itself on failure.
fn internal_error_response() -> Response<ResponseBody> {
    response(StatusCode::INTERNAL_SERVER_ERROR)
        .body(ResponseBody::Buffered(Full::new(Bytes::from_static(
            b"internal server error\n",
        ))))
        .unwrap()
}

fn bad_request_response() -> Response<ResponseBody> {
    response(StatusCode::BAD_REQUEST)
        .body(ResponseBody::Buffered(Full::new(Bytes::from_static(
            b"bad request\n",
        ))))
        .unwrap()
}

/// `Content-Encoding` name and sidecar file extension for each supported precompressed
/// variant, in preference order — brotli wins when a client accepts both and both
/// sidecars exist.
const SIDECAR_ENCODINGS: [(&str, &str); 2] = [("br", ".br"), ("gzip", ".gz")];

/// Whether `accept_encoding` allows `encoding`.
///
/// Matches by substring rather than parsing `q`-value weights or the `identity`/`*`
/// directives — a lighter-weight negotiation than a general HTTP client would need,
/// sufficient for deciding between two static sidecar files.
fn accepts_encoding(accept_encoding: Option<&str>, encoding: &str) -> bool {
    accept_encoding.is_some_and(|header| header.contains(encoding))
}

/// Look for a precompressed sidecar (`<path>.br` / `<path>.gz`) matching the client's
/// `Accept-Encoding`, and return its open file, metadata, and encoding name if found.
///
/// `path` must already be the fully resolved, canonicalized path `resolve()` produced.
/// The sidecar path is built by appending an extension to it — never by re-resolving a
/// modified request path — so this lookup can't become a second traversal surface: any
/// path this function reads is provably a sibling of a path `resolve()` already cleared.
async fn select_precompressed_sidecar(
    path: &Path,
    accept_encoding: Option<&str>,
) -> Option<(File, fs::Metadata, &'static str)> {
    for (encoding, ext) in SIDECAR_ENCODINGS {
        if !accepts_encoding(accept_encoding, encoding) {
            continue;
        }
        let mut sidecar = path.as_os_str().to_os_string();
        sidecar.push(ext);
        let sidecar_path = PathBuf::from(sidecar);

        // Tripwire for the traversal boundary: a sidecar path built by appending a suffix
        // must stay in the same directory as `path` (which `resolve()` already proved is
        // inside root). `ext` is always one of the two static literals in
        // `SIDECAR_ENCODINGS`, never derived from request input, so this can only fire if
        // a future change starts deriving `sidecar` some other way.
        debug_assert_eq!(
            sidecar_path.parent(),
            path.parent(),
            "sidecar path must stay in the same directory as the already-resolved path"
        );

        if let Ok(sidecar_file) = File::open(&sidecar_path).await {
            if let Ok(sidecar_metadata) = sidecar_file.metadata().await {
                return Some((sidecar_file, sidecar_metadata, encoding));
            }
        }
    }
    None
}

/// Generate an ETag for a file based on modification time and size.
///
/// Format: `"<size>-<mtime_secs>"`
fn generate_etag(metadata: &fs::Metadata) -> String {
    let mtime = metadata
        .modified()
        .ok()
        .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
        .map(|d| d.as_secs())
        .unwrap_or(0);
    format!("\"{}-{}\"", metadata.len(), mtime)
}

/// Determine MIME type from file path extension.
fn mime_type_for_path(path: &Path) -> &'static str {
    let ext = path
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or_default()
        .to_lowercase();

    match ext.as_str() {
        "html" | "htm" => "text/html; charset=utf-8",
        "css" => "text/css; charset=utf-8",
        "js" => "application/javascript; charset=utf-8",
        "json" => "application/json; charset=utf-8",
        "svg" => "image/svg+xml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "ico" => "image/x-icon",
        "woff" => "font/woff",
        "woff2" => "font/woff2",
        "ttf" => "font/ttf",
        "md" | "markdown" => "text/markdown; charset=utf-8",
        "txt" => "text/plain; charset=utf-8",
        "xml" => "application/xml",
        "pdf" => "application/pdf",
        "zip" => "application/zip",
        _ => "application/octet-stream",
    }
}

/// Check if the If-None-Match header matches the current ETag.
/// Handles both exact match and wildcard (*) comparison per RFC 9110.
fn is_etag_match(if_none_match: &str, etag: &str) -> bool {
    if if_none_match == "*" {
        return true;
    }
    if_none_match.split(',').any(|tag| tag.trim() == etag)
}

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

    // `select_precompressed_sidecar` only ever appends a static extension literal
    // (".br"/".gz") to the `path` it's given — it never re-joins against `root` or
    // re-parses a request-path string, so it structurally cannot become a second
    // traversal surface the way re-running `resolve()` on modified input could. This
    // test locks that in by construction: the sidecar it finds must live in exactly
    // the same directory as the resolved file, for every encoding preference branch.
    #[tokio::test]
    async fn sidecar_never_leaves_the_resolved_files_directory() {
        let root = tempfile::TempDir::new().unwrap();
        let sub = root.path().join("assets");
        fs::create_dir(&sub).unwrap();
        let resolved = sub.join("app.js");
        fs::write(&resolved, b"plain").unwrap();
        fs::write(sub.join("app.js.br"), b"brotli-bytes").unwrap();
        fs::write(sub.join("app.js.gz"), b"gzip-bytes").unwrap();

        let (_, _, encoding) = select_precompressed_sidecar(&resolved, Some("br, gzip"))
            .await
            .expect("both sidecars present, br should be preferred");
        assert_eq!(
            encoding, "br",
            "br must be preferred over gzip when both are accepted"
        );

        let (_, _, encoding) = select_precompressed_sidecar(&resolved, Some("gzip"))
            .await
            .expect("gzip sidecar present");
        assert_eq!(encoding, "gzip");

        assert!(
            select_precompressed_sidecar(&resolved, None)
                .await
                .is_none(),
            "no Accept-Encoding header should never select a sidecar"
        );
    }

    #[test]
    fn accepts_encoding_matches_only_listed_directives() {
        assert!(!accepts_encoding(None, "br"));
        assert!(!accepts_encoding(Some("identity"), "br"));
        assert!(!accepts_encoding(Some("identity"), "gzip"));
        assert!(accepts_encoding(Some("gzip, br"), "br"));
        assert!(accepts_encoding(Some("gzip"), "gzip"));
        assert!(!accepts_encoding(Some("gzip"), "br"));
    }
}

#[cfg(test)]
mod file_body_tests {
    use super::*;
    use crate::handler::FILE_CHUNK_SIZE;
    use http_body_util::BodyExt;

    // Disproves the prior implementation, which read every chunk into a `Vec` and
    // only wrapped the whole result in a single `Full` frame at the end — that
    // implementation would fail this test with `frame_count == 1` and
    // `max_frame_len == file size`, regardless of `FILE_CHUNK_SIZE`.
    #[tokio::test]
    async fn file_body_yields_multiple_bounded_chunks_not_one_buffered_frame() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("big.bin");
        let content = vec![7u8; FILE_CHUNK_SIZE * 3 + 12_345];
        fs::write(&path, &content).unwrap();

        let file = File::open(&path).await.unwrap();
        let mut body = FileBody::new(file);

        let mut frame_count = 0usize;
        let mut max_frame_len = 0usize;
        let mut reassembled = Vec::new();

        while let Some(frame) = body.frame().await {
            let frame = frame.unwrap();
            let data = frame.into_data().unwrap();
            frame_count += 1;
            max_frame_len = max_frame_len.max(data.len());
            reassembled.extend_from_slice(&data);
        }

        assert!(
            frame_count > 1,
            "expected the file to be delivered as multiple frames, got {frame_count}"
        );
        assert!(
            max_frame_len <= FILE_CHUNK_SIZE,
            "no single frame should exceed the chunk size ({FILE_CHUNK_SIZE}), got {max_frame_len}"
        );
        assert_eq!(
            reassembled, content,
            "reassembled chunks must match original file content exactly"
        );
    }
}

#[cfg(test)]
mod accept_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Mutex;

    /// Fails `accept()` a fixed number of times, recording the (paused, virtual)
    /// instant of each attempt, before delegating to a real listener so the caller can
    /// eventually succeed.
    struct FlakyListener {
        inner: TcpListener,
        remaining_failures: AtomicUsize,
        attempts: Mutex<Vec<tokio::time::Instant>>,
    }

    impl TcpAccept for FlakyListener {
        async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)> {
            self.attempts
                .lock()
                .unwrap()
                .push(tokio::time::Instant::now());
            if self.remaining_failures.fetch_sub(1, Ordering::SeqCst) > 0 {
                Err(std::io::Error::other("simulated accept error"))
            } else {
                TcpAccept::accept(&self.inner).await
            }
        }
    }

    // Disproves the prior implementation, which broke out of the accept loop entirely
    // on the first `accept()` error — permanently ending the server. This test would
    // also fail against a naive `continue`-only fix (no backoff): the recorded gaps
    // between attempts would collapse to ~0 (a busy spin) instead of the expected
    // exponentially growing delays.
    #[tokio::test(start_paused = true)]
    async fn accept_loop_backs_off_between_repeated_errors_instead_of_busy_spinning() {
        let inner = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = inner.local_addr().unwrap();

        let flaky = FlakyListener {
            inner,
            remaining_failures: AtomicUsize::new(5),
            attempts: Mutex::new(Vec::new()),
        };

        tokio::spawn(async move {
            let _ = TcpStream::connect(addr).await;
        });

        let semaphore = Arc::new(Semaphore::new(1));
        let mut backoff = ACCEPT_BACKOFF_INITIAL;
        let result = accept_and_permit(&flaky, &mut backoff, &semaphore).await;
        assert!(
            result.is_some(),
            "accept should eventually succeed once the flaky listener stops failing"
        );

        let recorded = flaky.attempts.lock().unwrap();
        assert_eq!(recorded.len(), 6, "5 failures then 1 success");

        let expected_gaps = [
            ACCEPT_BACKOFF_INITIAL,
            ACCEPT_BACKOFF_INITIAL * 2,
            ACCEPT_BACKOFF_INITIAL * 4,
            ACCEPT_BACKOFF_INITIAL * 8,
            ACCEPT_BACKOFF_INITIAL * 16,
        ];
        for (i, expected) in expected_gaps.iter().enumerate() {
            let gap = recorded[i + 1] - recorded[i];
            assert_eq!(
                gap,
                *expected,
                "gap between attempt {i} and {} should reflect the backoff delay, not a busy spin",
                i + 1
            );
        }

        // The delay must stop doubling at the cap rather than growing without bound.
        let mut capped = ACCEPT_BACKOFF_MAX;
        capped = (capped * 2).min(ACCEPT_BACKOFF_MAX);
        assert_eq!(capped, ACCEPT_BACKOFF_MAX);
    }

    // A successful accept must clear the accumulated delay, so an isolated error later
    // on doesn't inherit a second-long wait from an unrelated earlier failure.
    #[tokio::test(start_paused = true)]
    async fn a_successful_accept_resets_the_backoff() {
        let inner = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = inner.local_addr().unwrap();
        let flaky = FlakyListener {
            inner,
            remaining_failures: AtomicUsize::new(3),
            attempts: Mutex::new(Vec::new()),
        };
        tokio::spawn(async move {
            let _ = TcpStream::connect(addr).await;
        });

        let semaphore = Arc::new(Semaphore::new(1));
        let mut backoff = ACCEPT_BACKOFF_INITIAL * 32;
        accept_and_permit(&flaky, &mut backoff, &semaphore).await;

        assert_eq!(
            backoff, ACCEPT_BACKOFF_INITIAL,
            "the delay must return to its initial value once an accept succeeds"
        );
    }
}

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

    // Disproves a bare `.unwrap()` on the same builder: CR/LF is not a legal header
    // value byte (it would enable header/response splitting), so this construction is
    // guaranteed to make `.body(...)` return `Err`. Every real call site in this module
    // only ever builds header values from static strings or internally-formatted
    // numbers, so this test can't happen through normal use — it exists to prove
    // `finish()`'s fallback path actually works, not to exercise a reachable case.
    #[test]
    fn finish_degrades_to_400_on_invalid_header_value_instead_of_panicking() {
        let built = Response::builder()
            .status(StatusCode::OK)
            .header("X-Test", "invalid\r\nvalue")
            .body(ResponseBody::Buffered(Full::new(Bytes::new())));
        assert!(
            built.is_err(),
            "CR/LF in a header value should be rejected by the builder"
        );

        let response = finish(built);
        assert_eq!(
            response.status(),
            StatusCode::BAD_REQUEST,
            "finish() should degrade to 400 rather than panicking on an invalid header value"
        );
    }
}

#[cfg(test)]
mod header_prefix_tests {
    use super::*;
    use tokio::io::AsyncWriteExt;

    /// Binds an ephemeral listener, connects a client to it, and returns both ends —
    /// `(server_side, client_side)` — so a test can drive `read_header_prefix` against a
    /// real socket without a full `Server`/`serve_connection` in the loop.
    async fn connected_pair() -> (TcpStream, TcpStream) {
        let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
        let addr = listener.local_addr().unwrap();
        let client = TcpStream::connect(addr).await.unwrap();
        let (server_side, _) = listener.accept().await.unwrap();
        (server_side, client)
    }

    #[tokio::test]
    async fn reads_exactly_up_to_and_including_the_terminating_blank_line() {
        let (mut server_side, mut client) = connected_pair().await;

        client
            .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
            .await
            .unwrap();

        let prefix = read_header_prefix(&mut server_side)
            .await
            .unwrap_or_else(|_| {
                panic!("expected a complete header block to be read");
            });

        assert_eq!(prefix, b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n");
    }

    // Disproves a version that only inspects the newest chunk for `\r\n\r\n`: writing the
    // blank line in a separate write (and thus, almost always, a separate read) after the
    // rest of the headers would make that version wait forever, since the terminator
    // never appears within a single chunk. Also pins the tail-only scan in
    // `read_header_prefix` — a terminator straddling two reads must still be seen.
    #[tokio::test]
    async fn assembles_a_header_block_split_across_multiple_writes() {
        let (mut server_side, mut client) = connected_pair().await;

        client
            .write_all(b"GET /page HTTP/1.1\r\nHost: localhost\r")
            .await
            .unwrap();
        client.write_all(b"\n\r\n").await.unwrap();

        let prefix = read_header_prefix(&mut server_side)
            .await
            .unwrap_or_else(|_| {
                panic!("expected a complete header block to be read across multiple writes");
            });

        assert_eq!(prefix, b"GET /page HTTP/1.1\r\nHost: localhost\r\n\r\n");
    }

    // Bytes past the header block (a pipelined second request, here) must be preserved
    // verbatim in the returned prefix — `PrefixedIo` depends on this to replay them to
    // hyper untouched.
    #[tokio::test]
    async fn preserves_bytes_sent_past_the_header_block() {
        let (mut server_side, mut client) = connected_pair().await;

        let first = b"GET /a HTTP/1.1\r\nHost: localhost\r\n\r\n";
        let second = b"GET /b HTTP/1.1\r\nHost: localhost\r\n\r\n";
        let mut sent = Vec::new();
        sent.extend_from_slice(first);
        sent.extend_from_slice(second);
        client.write_all(&sent).await.unwrap();

        let prefix = read_header_prefix(&mut server_side)
            .await
            .unwrap_or_else(|_| {
                panic!("expected a complete header block to be read");
            });

        assert_eq!(
            &prefix, &sent,
            "pipelined bytes past the first header block must survive intact"
        );
    }

    #[tokio::test]
    async fn errors_with_connection_closed_when_client_disconnects_before_headers_complete() {
        let (mut server_side, client) = connected_pair().await;
        drop(client);

        match read_header_prefix(&mut server_side).await {
            Err(HeaderReadError::ConnectionClosed) => {}
            Err(_) => panic!("expected ConnectionClosed, got a different error variant"),
            Ok(_) => {
                panic!("expected an error, got a complete header block from a closed connection")
            }
        }
    }

    // Disproves an unbounded buffer: without the `MAX_HEADER_BYTES` check, this would
    // hang consuming memory forever instead of erroring, since the client never sends the
    // terminating blank line.
    #[tokio::test]
    async fn errors_with_too_large_once_max_header_bytes_is_exceeded_without_a_terminator() {
        let (mut server_side, mut client) = connected_pair().await;

        let garbage = vec![b'a'; MAX_HEADER_BYTES + 1];
        client.write_all(&garbage).await.unwrap();

        match read_header_prefix(&mut server_side).await {
            Err(HeaderReadError::TooLarge) => {}
            Err(_) => panic!("expected TooLarge, got a different error variant"),
            Ok(_) => {
                panic!("expected an error, got a complete header block from unterminated garbage")
            }
        }
    }

    #[tokio::test]
    async fn prefixed_io_replays_the_prefix_before_reading_from_the_live_socket() {
        let (server_side, mut client) = connected_pair().await;
        let mut io = PrefixedIo::new(b"buffered-prefix".to_vec(), server_side);

        client.write_all(b"-live-bytes").await.unwrap();

        let mut collected = Vec::new();
        let mut chunk = [0u8; 8];
        while collected.len() < b"buffered-prefix-live-bytes".len() {
            let n = io.read(&mut chunk).await.unwrap();
            assert!(n > 0, "read returned 0 before all expected bytes arrived");
            collected.extend_from_slice(&chunk[..n]);
        }

        assert_eq!(collected, b"buffered-prefix-live-bytes");
    }
}

#[cfg(test)]
mod css_bundle_tests {
    use super::*;
    use std::fs;
    use std::time::Duration;
    use tempfile::TempDir;
    use tokio::time::sleep;

    #[tokio::test]
    async fn source_folder_overlapping_output_dir_is_rejected() {
        let root = TempDir::new().unwrap();

        // The output dir defaults to the served root, so registering that root as a source
        // folder must be refused: watching the output would feed every pipeline its own
        // writes back into its trigger.
        let result = Server::new(root.path())
            .unwrap()
            .with_source_folder(root.path());
        assert!(
            result.is_err(),
            "a source folder equal to the output dir must be rejected"
        );
    }

    #[tokio::test]
    async fn source_folder_inside_output_dir_is_rejected() {
        let root = TempDir::new().unwrap();
        let nested = root.path().join("nested");
        fs::create_dir(&nested).unwrap();

        let result = Server::new(root.path())
            .unwrap()
            .with_source_folder(&nested);
        assert!(
            result.is_err(),
            "a source folder nested in the output dir must be rejected"
        );
    }

    #[tokio::test]
    async fn output_dir_overlapping_source_folder_is_rejected() {
        let root = TempDir::new().unwrap();
        let source = TempDir::new().unwrap();

        let server = Server::new(root.path())
            .unwrap()
            .with_source_folder(source.path())
            .unwrap();

        let result = server.with_output_dir(source.path());
        assert!(
            result.is_err(),
            "an output dir equal to a source folder must be rejected"
        );
    }

    #[tokio::test]
    async fn css_bundle_creates_output_on_startup_with_live_reload() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();

        fs::write(src.path().join("style.css"), "body { margin: 0; }").unwrap();

        let server = Server::new(out.path())
            .unwrap()
            .with_live_reload()
            .with_source_folder(src.path())
            .unwrap()
            .with_css_tool(CssTool::TestEcho, CssOptions::new().bundle(true));

        let (_port, handle) = server.run_ephemeral().await.unwrap();

        sleep(Duration::from_millis(800)).await;

        let bundle = out.path().join("styles.css");
        assert!(
            bundle.exists(),
            "bundle should be written to the default <output>/styles.css"
        );
        let content = fs::read_to_string(&bundle).unwrap();
        assert!(!content.is_empty(), "bundle should contain CSS");

        handle.shutdown().await;
    }

    #[tokio::test]
    async fn css_bundle_rebuilds_once_and_settles_when_source_css_changes() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let src_path = src.path();
        let bundle = out.path().join("styles.css");

        fs::write(src_path.join("style.css"), "body { margin: 0; }").unwrap();

        let server = Server::new(out.path())
            .unwrap()
            .with_live_reload()
            .with_source_folder(src_path)
            .unwrap()
            .with_css_tool(CssTool::TestEcho, CssOptions::new().bundle(true));

        let (_port, handle) = server.run_ephemeral().await.unwrap();

        // Let the startup build and the watcher's first poll pass (500ms) complete.
        sleep(Duration::from_millis(800)).await;
        assert!(bundle.exists());

        fs::write(
            src_path.join("style.css"),
            "body { margin: 0; color: blue; }",
        )
        .unwrap();

        // Wait long enough for the watcher poll + rebundle to land at least once.
        sleep(Duration::from_millis(1500)).await;
        let content_v2 = fs::read_to_string(&bundle).unwrap();
        assert!(
            content_v2.contains("color"),
            "rebundle should contain the new color rule"
        );

        let mtime_after = fs::metadata(&bundle).unwrap().modified().unwrap();
        sleep(Duration::from_millis(1200)).await;
        let mtime_later = fs::metadata(&bundle).unwrap().modified().unwrap();

        // The regression this guards: the output write must NOT re-trigger another rebuild
        // (the feedback loop would keep mutating the bundle's mtime here). A settled mtime
        // over a full poll interval proves a single rebuild, not a loop.
        assert_eq!(
            mtime_after, mtime_later,
            "bundle mtime must settle after one rebuild — an ongoing loop would keep changing it"
        );

        handle.shutdown().await;
    }

    #[tokio::test]
    async fn css_bundle_creates_output_on_startup_without_live_reload() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();

        fs::write(src.path().join("style.css"), "body { margin: 0; }").unwrap();

        let server = Server::new(out.path())
            .unwrap()
            .with_source_folder(src.path())
            .unwrap()
            .with_css_tool(CssTool::TestEcho, CssOptions::new().bundle(true));

        let (_port, handle) = server.run_ephemeral().await.unwrap();

        sleep(Duration::from_millis(200)).await;

        let bundle = out.path().join("styles.css");
        assert!(
            bundle.exists(),
            "bundle should be created even without live_reload"
        );
        let content = fs::read_to_string(&bundle).unwrap();
        assert!(!content.is_empty(), "bundle should contain CSS");

        handle.shutdown().await;
    }

    #[tokio::test]
    async fn css_bundle_concatenates_multiple_source_css_files() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();

        fs::write(src.path().join("reset.css"), "* { margin: 0; padding: 0; }").unwrap();
        fs::write(src.path().join("theme.css"), "body { background: white; }").unwrap();

        let server = Server::new(out.path())
            .unwrap()
            .with_live_reload()
            .with_source_folder(src.path())
            .unwrap()
            .with_css_tool(CssTool::TestEcho, CssOptions::new().bundle(true));

        let (_port, handle) = server.run_ephemeral().await.unwrap();

        sleep(Duration::from_millis(800)).await;

        let content = fs::read_to_string(out.path().join("styles.css")).unwrap();
        assert!(
            content.contains("margin"),
            "output should contain reset CSS"
        );
        assert!(
            content.contains("background"),
            "output should contain theme CSS"
        );

        handle.shutdown().await;
    }
}