web_modules 0.5.1

Pure-Rust, buildless toolchain for ES modules and Web Components
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
//! A buildless **dev server**: serve a frontend straight from source, compiling
//! TypeScript and SCSS on the fly per request (mtime-cached) and live-reloading the
//! browser when files change.
//!
//! Sources are [`Mount`]s, each a URL prefix + a source dir; the default is one at
//! `/`. Resolution is **dir-observation-order-dominant**: most-specific prefix first,
//! then (among the dirs matching that prefix, **in the order given**) the first that
//! can produce the requested *target* wins — render `foo.tera`, else serve a literal
//! file, else compile `foo.{ts,tsx,mts}` → `foo.js` / `foo.scss` → `foo.css` — the
//! same precedence the build applies under `--skip-duplicates`. So overlaying several
//! dirs at one prefix resolves "first dir wins", as a side-effect; contested targets
//! are reported once at startup (silence with `skip_duplicates`). An optional embedded
//! fallback (a baked `include_dir!` tree) supplies whatever the source dirs don't:
//! vendored `web_modules/`, a baked `index.html`. The watcher watches every source dir
//! identically and reloads on any change.
//!
//! Enable the `dev` feature.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use axum::{
    extract::State,
    http::{header, StatusCode, Uri},
    response::{IntoResponse, Response},
    Router,
};
use include_dir::Dir;
use tower_livereload::LiveReloadLayer;

use super::serving::{
    content_type, has_source_extension, has_traversal, is_source_file, relative_under,
    resolve_file, Resolved,
};
use crate::build::Processors;
#[cfg(feature = "builder")]
use crate::builder_shared::source_builder_methods;
use crate::mount::Mount;

type Cache = Mutex<HashMap<PathBuf, (SystemTime, Vec<u8>)>>;

/// Which processors the dev server applies — **unified with the build pipeline's
/// [`Processors`](crate::build::Processors)**, so `dev` and `build` configure the same set
/// (minify/gzip are build *output* options in [`Output`](crate::build::Output), not here).
/// This is a type alias kept for the historical `dev::DevConfig` name; build one with
/// [`Processors::default`](crate::build::Processors) (all on, Lit decorators) and adjust
/// fields, or use the [`Dev`] builder.
pub type DevConfig = Processors;

/// Fluent builder for the dev server: compile TS/SCSS on the fly, render `*.tera`, watch
/// the source roots and live-reload the browser.
///
/// ```no_run
/// use web_modules::Dev;
///
/// # async fn run() -> std::io::Result<()> {
/// Dev::new().root("web").serve("127.0.0.1:8080".parse().unwrap()).await
/// # }
/// ```
///
/// Shared source inputs (`root`/`roots`, `typescript`/`scss`/`tera`, `decorators`,
/// `scss_load_path(s)`) come from [`source_builder_methods!`](crate::builder_shared); the
/// terminals are [`serve`](Self::serve) and [`router`](Self::router). For prefix-mounted
/// composition (several dirs under different URL prefixes), use [`Frontend`](crate::Frontend).
#[cfg(feature = "builder")]
#[derive(Clone, Debug, Default)]
pub struct Dev {
    roots: Vec<PathBuf>,
    processors: Processors,
}

#[cfg(feature = "builder")]
source_builder_methods!(Dev);

#[cfg(feature = "builder")]
impl Dev {
    /// A new builder with no roots and all processors on (Lit decorators).
    pub fn new() -> Self {
        Self::default()
    }

    /// The dev [`Router`] (compile-on-the-fly, watch, live-reload) over the roots, each
    /// mounted at `/` and resolved first-match-wins. Compose it into your own axum app, or
    /// use [`serve`](Self::serve) to bind and run.
    pub fn router(self) -> Router {
        dev_router_with(self.roots, self.processors)
    }

    /// Bind `addr` and serve [`router`](Self::router) until the process stops.
    pub async fn serve(self, addr: SocketAddr) -> std::io::Result<()> {
        serve_with(self.roots, addr, self.processors).await
    }
}

#[derive(Clone)]
struct DevState {
    mounts: Arc<Vec<Mount>>,
    cache: Arc<Cache>,
    /// Baked assets to fall back to when a request isn't a source file.
    fallback: Option<&'static Dir<'static>>,
    /// Which processors to apply (and how), shared with the bin's `--<name>` toggles.
    config: Arc<DevConfig>,
}

enum Kind {
    Ts,
    Scss,
    #[cfg(feature = "tera")]
    Tera,
}

/// Build the dev [`Router`] over flat source `roots` (each mounted at `/`, resolved in
/// order, first dir wins), with all processors on. For prefix-mounted composition use
/// [`dev_router_mounted`]; to choose which processors run, [`dev_router_with`].
pub fn dev_router(roots: Vec<PathBuf>) -> Router {
    dev_router_with(roots, DevConfig::default())
}

/// Like [`dev_router`], but with an explicit [`DevConfig`] (which processors run, and
/// how) — the toggle-aware entry the `web-modules dev` command uses.
pub fn dev_router_with(roots: Vec<PathBuf>, config: DevConfig) -> Router {
    build_router(roots.into_iter().map(Mount::root).collect(), None, config)
}

/// Like [`dev_router`], but unmatched requests fall back to a baked `include_dir!`
/// tree (vendored modules, `index.html`, …).
pub fn dev_router_with_embedded(roots: Vec<PathBuf>, embedded: &'static Dir<'static>) -> Router {
    build_router(
        roots.into_iter().map(Mount::root).collect(),
        Some(embedded),
        DevConfig::default(),
    )
}

/// Build the dev [`Router`] over prefix-mounted sources: each [`Mount`]'s dir is served
/// (and, when watched, live-reloaded) under its URL prefix, with TS/SCSS compiled on
/// the fly.
pub fn dev_router_mounted(mounts: Vec<Mount>) -> Router {
    build_router(mounts, None, DevConfig::default())
}

/// Like [`dev_router_mounted`], with a baked `include_dir!` fallback.
pub fn dev_router_mounted_with_embedded(
    mounts: Vec<Mount>,
    embedded: &'static Dir<'static>,
) -> Router {
    build_router(mounts, Some(embedded), DevConfig::default())
}

pub(crate) fn build_router(
    mounts: Vec<Mount>,
    fallback: Option<&'static Dir<'static>>,
    config: DevConfig,
) -> Router {
    // The same preflight the build runs, warn-only: a contested target is served by
    // its winner and an escaping symlink is refused per-request, but both are worth
    // a line on the console.
    for warning in preflight_warnings(&mounts, &config) {
        eprintln!("{warning}");
    }
    let livereload = LiveReloadLayer::new();
    spawn_watcher(mounts.clone(), livereload.reloader());
    let state = DevState {
        mounts: Arc::new(mounts),
        cache: Arc::new(Mutex::new(HashMap::new())),
        fallback,
        config: Arc::new(config),
    };
    Router::new()
        .fallback(serve_asset)
        .with_state(state)
        .layer(livereload)
}

/// The preflight warnings the dev server prints at startup: per URL prefix, the
/// mounted dirs (declaration order) run through the same preflight the build uses.
/// Every contested target is reported once with its winner — those lines are silenced
/// by `skip_duplicates`. A source resolving outside its mount (an escaping symlink,
/// which per-request containment will refuse), any walk problem, and every reject-list
/// drop are always reported; the flag arbitrates precedence, not policy. Mounts at different
/// prefixes are never compared — most-specific-prefix routing is deliberate
/// composition, not an accident.
fn preflight_warnings(mounts: &[Mount], config: &DevConfig) -> Vec<String> {
    let steps = crate::build::steps::enabled_steps(config, Default::default());
    let preflights: Vec<&dyn crate::build::steps::Preflight> = steps
        .iter()
        .map(|step| step.as_ref() as &dyn crate::build::steps::Preflight)
        .collect();
    // Group the mounted dirs by URL prefix, keeping declaration order per group.
    let mut prefixes: Vec<&str> = Vec::new();
    let mut groups: HashMap<&str, Vec<PathBuf>> = HashMap::new();
    for mount in mounts {
        let prefix = mount.url_prefix();
        if !groups.contains_key(prefix) {
            prefixes.push(prefix);
        }
        groups
            .entry(prefix)
            .or_default()
            .push(mount.dir().to_path_buf());
    }
    let mut lines = Vec::new();
    for prefix in prefixes {
        let roots = &groups[prefix];
        let report = crate::build::steps::preflight(
            roots,
            &preflights,
            crate::build::steps::WalkPolicy {
                reject: &config.reject,
                symlinks: config.symlinks,
            },
        );
        for error in report.walk_errors() {
            lines.push(format!("web-modules: preflight: {error}"));
        }
        for source in report.escaping_sources() {
            lines.push(format!(
                "web-modules: {} resolves outside its mount ({}) - not served",
                roots[source.root].join(&source.rel).display(),
                source.target.display(),
            ));
        }
        for skipped in report.skipped_symlinks() {
            lines.push(format!(
                "web-modules: {} is a symlink - served as a redirect, skipped by build",
                roots[skipped.root].join(&skipped.rel).display(),
            ));
        }
        // Reject-list drops are policy, not precedence — `skip_duplicates` (below)
        // never silences them.
        for rejected in report.rejected_claims() {
            lines.push(format!("web-modules: {}", rejected.describe(roots)));
        }
        if config.skip_duplicates {
            continue;
        }
        for conflict in report.conflicts() {
            let target = if prefix.ends_with('/') {
                format!("{prefix}{}", conflict.out_rel.display())
            } else {
                format!("{prefix}/{}", conflict.out_rel.display())
            };
            let winner = &conflict.claimants[0];
            let losers = conflict.claimants[1..]
                .iter()
                .map(|claim| roots[claim.root].join(&claim.rel).display().to_string())
                .collect::<Vec<_>>()
                .join(", ");
            lines.push(format!(
                "web-modules: duplicate target {target}: {} wins over {losers} \
                 (--skip-duplicates silences this)",
                roots[winner.root].join(&winner.rel).display()
            ));
        }
    }
    lines
}

/// Bind `addr` and serve [`dev_router`] over `roots` (all processors on) until the
/// process stops.
pub async fn serve(roots: Vec<PathBuf>, addr: SocketAddr) -> std::io::Result<()> {
    serve_with(roots, addr, DevConfig::default()).await
}

/// Like [`serve`], but with an explicit [`DevConfig`] (which processors run, and how).
pub async fn serve_with(
    roots: Vec<PathBuf>,
    addr: SocketAddr,
    config: DevConfig,
) -> std::io::Result<()> {
    let app = dev_router_with(roots, config);
    let listener = tokio::net::TcpListener::bind(addr).await?;
    println!("web-modules dev server on http://{addr}/  (Ctrl-C to stop)");
    axum::serve(listener, app).await
}

async fn serve_asset(State(state): State<DevState>, uri: Uri) -> Response {
    let raw = uri.path().trim_start_matches('/');
    let requested = if raw.is_empty() || raw.ends_with('/') {
        format!("{raw}index.html")
    } else {
        raw.to_string()
    };
    // Layer 1: reject a traversing request path before it reaches the filesystem.
    if has_traversal(&requested) {
        return StatusCode::NOT_FOUND.into_response();
    }
    // Resolution reads sources and compiles them on the calling thread; run it on the
    // blocking pool so one slow compile doesn't stall unrelated requests.
    let task = {
        let state = state.clone();
        let requested = requested.clone();
        tokio::task::spawn_blocking(move || resolve(&state, &requested)).await
    };
    let Ok(resolved) = task else {
        // A panic inside resolution is this request's 500, not a dead worker.
        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
    };
    match resolved {
        Ok(Some(Served::Bytes { body, content_type })) => {
            ([(header::CONTENT_TYPE, content_type)], body).into_response()
        }
        #[cfg(feature = "symlink-move")]
        Ok(Some(Served::Redirect {
            location,
            permanent,
        })) => match super::symlink_move::redirect_response(&location, permanent) {
            Some(response) => response,
            // `location_value` pre-sanitized; an unbuildable header is a refusal.
            None => (StatusCode::NOT_FOUND, format!("404 Not Found: {requested}")).into_response(),
        },
        Ok(None) => (StatusCode::NOT_FOUND, format!("404 Not Found: {requested}")).into_response(),
        Err(message) => {
            eprintln!("web-modules: compile error for /{requested}:\n{message}");
            (StatusCode::INTERNAL_SERVER_ERROR, message).into_response()
        }
    }
}

/// What [`resolve`] produced: response bytes, or — the redirect symlink modes only —
/// the redirect a symlink stands for.
enum Served {
    Bytes {
        body: Vec<u8>,
        content_type: String,
    },
    #[cfg(feature = "symlink-move")]
    Redirect {
        location: String,
        permanent: bool,
    },
}

/// A probe for a *source* candidate (a `.tera`, `.ts`, `.scss`): only a real file
/// counts. Under the redirect modes a symlinked source is skipped — never served,
/// never redirected (a redirect would name a hidden source) — matching the build,
/// which skips it with a warning.
fn source_candidate(mount: &Mount, rel: &str, mode: crate::SymlinkMode) -> Option<PathBuf> {
    match resolve_file(mount.dir(), rel, mode) {
        Some(Resolved::File(path)) => Some(path),
        _ => None,
    }
}

/// The mounts whose URL prefix matches `requested`, most-specific (longest prefix)
/// first, each paired with the request path relative to that mount. Equal-specificity
/// mounts keep declaration (observation) order (stable sort).
fn matching<'a>(state: &'a DevState, requested: &str) -> Vec<(&'a Mount, String)> {
    let mut hits: Vec<(&Mount, String)> = state
        .mounts
        .iter()
        .filter_map(|m| relative_under(m.url_prefix(), requested).map(|rel| (m, rel)))
        .collect();
    hits.sort_by_key(|hit| std::cmp::Reverse(hit.0.url_prefix().len()));
    hits
}

/// Resolve a request to `(bytes, content-type)`, **dir-observation-order-dominant**:
/// for each matching mount in order, the first that can produce the requested target
/// wins — render a `.tera`, else serve a literal file, else compile a source
/// `.ts`/`.scss` — then the embedded fallback. The same within-dir precedence the
/// build's preflight ranks (Tera over a literal over a transformed sibling), so `dev`
/// and `build` resolve a shadowed target alike.
fn resolve(state: &DevState, requested: &str) -> Result<Option<Served>, String> {
    // Reject list: never serve config / secret / source-code paths (see `reject`). Checked on the
    // request string here, and on the resolved file below, so case-folding / a trailing dot can't
    // smuggle a rejected file past.
    if state.config.reject.rejects(requested) {
        crate::reject::warn_rejected(requested);
        return Ok(None);
    }
    let mode = state.config.symlinks;
    for (mount, rel) in matching(state, requested) {
        // `/foo.html` (any rendered target) ← render `foo.html.tera` from this dir, the live
        // counterpart of the build pipeline's `.tera` step. Checked **first** so a `.tera`
        // takes precedence over a same-named literal/compiled target — the top of the
        // build's within-root ranking. The `.tera` source itself stays hidden from raw
        // serving (it's a source extension).
        #[cfg(feature = "tera")]
        if state.config.tera && !rel.is_empty() {
            if let Some(src) = source_candidate(mount, &format!("{rel}.tera"), mode) {
                // Never render a `_`-prefixed partial as a page (matches the build tree).
                let is_partial = src
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.starts_with('_'));
                if !is_partial {
                    let body = compile_cached(state, &src, Kind::Tera)?;
                    return Ok(Some(Served::Bytes {
                        body,
                        content_type: content_type(&rel),
                    }));
                }
            }
        }
        // Literal file in this dir — checked before the compilers, so a literal
        // `app.js` outranks a sibling `app.ts`, exactly as the build ranks the static
        // copy over a transform. Never serve a *source* raw (a `.scss`/`.ts` is
        // reachable only through its compiled target, below). Re-check the resolved
        // path, not just the request string: on a case-insensitive / name-folding FS
        // the OS can open a source the request didn't reveal (`app.SCSS`, `app.scss.`).
        if !rel.is_empty() && !is_source_file(&rel) {
            match resolve_file(mount.dir(), &rel, mode) {
                Some(Resolved::File(path)) => {
                    // Re-check the resolved file *name* (the fold-prone part; not the absolute path,
                    // whose parent dirs are out of our control) so OS case-folding / a trailing dot
                    // can't smuggle a rejected file past the lexical check above.
                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                    if state.config.reject.rejects(name) {
                        crate::reject::warn_rejected(&rel);
                        return Ok(None);
                    }
                    if !has_source_extension(&path) {
                        let body = std::fs::read(&path).map_err(|e| e.to_string())?;
                        return Ok(Some(Served::Bytes {
                            body,
                            content_type: content_type(&rel),
                        }));
                    }
                }
                // Redirect modes: a symlink on the literal path answers with its
                // own content as the Location — the target is never opened.
                #[cfg(feature = "symlink-move")]
                Some(Resolved::Redirect(location)) => {
                    return Ok(Some(Served::Redirect {
                        location,
                        permanent: mode == crate::SymlinkMode::Move,
                    }));
                }
                None => {}
            }
        }
        // `/foo.js` ← compile `foo.{ts,tsx,mts}` from this dir.
        if state.config.typescript {
            if let Some(stem) = rel.strip_suffix(".js") {
                for ext in ["ts", "tsx", "mts"] {
                    if let Some(src) = source_candidate(mount, &format!("{stem}.{ext}"), mode) {
                        let body = compile_cached(state, &src, Kind::Ts)?;
                        return Ok(Some(Served::Bytes {
                            body,
                            content_type: "text/javascript; charset=utf-8".into(),
                        }));
                    }
                }
            }
        }
        // `/foo.css` ← compile `foo.scss` from this dir.
        if state.config.scss {
            if let Some(stem) = rel.strip_suffix(".css") {
                if let Some(src) = source_candidate(mount, &format!("{stem}.scss"), mode) {
                    let body = compile_cached(state, &src, Kind::Scss)?;
                    return Ok(Some(Served::Bytes {
                        body,
                        content_type: "text/css; charset=utf-8".into(),
                    }));
                }
            }
        }
    }
    // Baked fallback (vendored modules, index.html, …), keyed by the full path.
    // Embedded trees carry no symlinks, so the mode has nothing to decide here.
    if let Some(dir) = state.fallback {
        if !is_source_file(requested) {
            if let Some(file) = dir.get_file(requested) {
                return Ok(Some(Served::Bytes {
                    body: file.contents().to_vec(),
                    content_type: content_type(requested),
                }));
            }
        }
    }
    Ok(None)
}

/// Compile `src` (TS, SCSS, or Tera), caching by modification time. SCSS `@use`/`@import`
/// load paths span every mounted dir (plus any `extra_scss_load_paths`); Tera renders
/// with an empty `importmap` variable (the dev server doesn't vendor).
fn compile_cached(state: &DevState, src: &Path, kind: Kind) -> Result<Vec<u8>, String> {
    let mtime = std::fs::metadata(src)
        .and_then(|m| m.modified())
        .map_err(|e| e.to_string())?;
    if let Some((cached_mtime, bytes)) = state
        .cache
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(src)
    {
        if *cached_mtime == mtime {
            return Ok(bytes.clone());
        }
    }
    let out = match kind {
        Kind::Ts => {
            let source = std::fs::read_to_string(src).map_err(|e| e.to_string())?;
            let options = crate::typescript::TranspileOptions {
                decorators: state.config.ts_decorators,
                ..Default::default()
            };
            crate::typescript::compile_str_with(&source, src, &options)
                .map_err(|e| e.to_string())?
                .into_bytes()
        }
        Kind::Scss => {
            let mut load_paths: Vec<&Path> = state.mounts.iter().map(|m| m.dir()).collect();
            load_paths.extend(
                state
                    .config
                    .extra_scss_load_paths
                    .iter()
                    .map(PathBuf::as_path),
            );
            crate::scss::compile_file(src, &load_paths)
                .map_err(|e| e.to_string())?
                .into_bytes()
        }
        #[cfg(feature = "tera")]
        Kind::Tera => {
            // dev doesn't vendor, so the import map is empty here (a no-op `<script>`).
            // Live TS/SCSS still load by their relative URLs; a baked fallback may carry
            // a real map, but live source serving doesn't need one.
            let ctx = crate::templates::importmap_context(&crate::importmap::Importmap::new());
            crate::templates::render_file(src, &ctx)
                .map_err(|e| e.to_string())?
                .into_bytes()
        }
    };
    state
        .cache
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .insert(src.to_path_buf(), (mtime, out.clone()));
    Ok(out)
}

/// Watch each watched mount's dir and trigger a browser reload on any change.
fn spawn_watcher(mounts: Vec<Mount>, reloader: tower_livereload::Reloader) {
    std::thread::spawn(move || {
        use notify::{RecursiveMode, Watcher};
        let mut watcher =
            match notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
                if let Ok(event) = res {
                    if event.kind.is_modify() || event.kind.is_create() || event.kind.is_remove() {
                        reloader.reload();
                    }
                }
            }) {
                Ok(w) => w,
                Err(e) => {
                    eprintln!("web-modules: file watcher unavailable ({e}); live-reload off");
                    return;
                }
            };
        for mount in &mounts {
            if mount.is_watched() {
                if let Err(e) = watcher.watch(mount.dir(), RecursiveMode::Recursive) {
                    eprintln!("web-modules: cannot watch {}: {e}", mount.dir().display());
                }
            }
        }
        loop {
            std::thread::park();
        }
    });
}

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

    fn state(mounts: Vec<Mount>) -> DevState {
        state_with(mounts, DevConfig::default())
    }

    impl Served {
        /// The `(body, content-type)` of a byte response; panics on a redirect.
        fn bytes(self) -> (Vec<u8>, String) {
            match self {
                Served::Bytes { body, content_type } => (body, content_type),
                #[cfg(feature = "symlink-move")]
                Served::Redirect { location, .. } => {
                    panic!("expected bytes, got a redirect to {location}")
                }
            }
        }
    }

    fn state_with(mounts: Vec<Mount>, config: DevConfig) -> DevState {
        DevState {
            mounts: Arc::new(mounts),
            cache: Arc::new(Mutex::new(HashMap::new())),
            fallback: None,
            config: Arc::new(config),
        }
    }

    #[test]
    fn dev_rejects_config_and_dotfiles() {
        // The default (all-presets) reject list 404s config / secret / dotfile paths even though
        // the files exist on disk; legitimate assets still serve.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("index.html"), b"<x>").unwrap();
        std::fs::write(root.join("package.json"), b"{}").unwrap();
        std::fs::write(root.join(".env"), b"S=1").unwrap();
        let state = state(vec![Mount::root(root)]);
        assert!(resolve(&state, "index.html").unwrap().is_some());
        assert!(
            resolve(&state, "package.json").unwrap().is_none(),
            "config manifest rejected"
        );
        assert!(
            resolve(&state, ".env").unwrap().is_none(),
            "dotfile rejected"
        );
    }

    #[test]
    fn dev_rejects_templated_and_compiled_secret_targets() {
        // Parity with `build`: a `.env.tera` template or a `.env.ts` source must not
        // make the rejected target reachable — the target check fires before any
        // candidate resolution.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join(".env.tera"), "SECRET={{ 1 }}").unwrap();
        std::fs::write(root.join(".env.ts"), "export const x = 1;").unwrap();
        let state = state(vec![Mount::root(root)]);
        assert!(
            resolve(&state, ".env").unwrap().is_none(),
            "templated target rejected"
        );
        assert!(
            resolve(&state, ".env.js").unwrap().is_none(),
            "compiled target rejected"
        );
    }

    #[test]
    fn resolve_serves_inside_and_blocks_traversal() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("data.json"), b"{}").unwrap();
        std::fs::write(tmp.path().join("secret"), b"s").unwrap();
        let state = state(vec![Mount::root(root)]);
        assert!(resolve(&state, "data.json").unwrap().is_some());
        // Even bypassing Layer 1, resolve's own containment blocks the escape.
        assert!(resolve(&state, "../secret").unwrap().is_none());
    }

    #[test]
    fn dev_serves_literal_js_over_compiling_sibling_ts() {
        // A literal `app.js` outranks the sibling `app.ts` — the build's precedence
        // under `--skip-duplicates`, so dev serves what build would ship.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("app.js"), b"literal();").unwrap();
        std::fs::write(root.join("app.ts"), "export const compiled = 1;").unwrap();
        let state = state(vec![Mount::root(root)]);
        let (bytes, _) = resolve(&state, "app.js").unwrap().unwrap().bytes();
        assert_eq!(bytes, b"literal();", "the literal file wins");
    }

    #[test]
    fn dev_serves_literal_css_over_scss() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("style.css"), b"a{color:red}").unwrap();
        std::fs::write(root.join("style.scss"), "a { color: blue; }").unwrap();
        let state = state(vec![Mount::root(root)]);
        let (bytes, _) = resolve(&state, "style.css").unwrap().unwrap().bytes();
        assert_eq!(bytes, b"a{color:red}", "the literal file wins");
    }

    #[test]
    fn duplicate_warnings_lists_conflicts_and_names_the_winner() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("app.js"), b"literal();").unwrap();
        std::fs::write(root.join("app.ts"), "export const compiled = 1;").unwrap();

        let mounts = vec![Mount::root(root)];
        let warnings = preflight_warnings(&mounts, &DevConfig::default());
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains("/app.js")
                && warnings[0].contains("app.js wins over")
                && warnings[0].contains("app.ts")
                && warnings[0].contains("--skip-duplicates"),
            "got: {}",
            warnings[0]
        );
    }

    #[cfg(unix)]
    #[test]
    fn follow_unsafe_serves_an_escaping_link_but_keeps_the_other_guards() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("outside.js"), b"outside").unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::os::unix::fs::symlink(tmp.path().join("outside.js"), root.join("link.js")).unwrap();
        std::fs::write(root.join(".env"), b"S=1").unwrap();

        let state = state_with(
            vec![Mount::root(root)],
            DevConfig {
                symlinks: crate::SymlinkMode::FollowUnsafe,
                ..DevConfig::default()
            },
        );
        let (bytes, _) = resolve(&state, "link.js").unwrap().unwrap().bytes();
        assert_eq!(bytes, b"outside", "the mode's contract: the link serves");
        assert!(
            resolve(&state, ".env").unwrap().is_none(),
            "reject still applies"
        );
    }

    #[cfg(all(unix, feature = "symlink-move"))]
    #[test]
    fn redirect_mode_answers_with_the_link_content_and_hides_symlinked_sources() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("real.txt"), b"data").unwrap();
        std::os::unix::fs::symlink(Path::new("real.txt"), root.join("link.txt")).unwrap();
        // A symlinked compile candidate: never served, never redirected.
        std::fs::write(tmp.path().join("app.ts"), "export const x = 1;").unwrap();
        std::os::unix::fs::symlink(tmp.path().join("app.ts"), root.join("app.ts")).unwrap();

        let state = state_with(
            vec![Mount::root(root)],
            DevConfig {
                symlinks: crate::SymlinkMode::Redirect,
                ..DevConfig::default()
            },
        );
        match resolve(&state, "link.txt").unwrap().unwrap() {
            Served::Redirect {
                location,
                permanent,
            } => {
                assert_eq!(location, "real.txt", "the link content is the Location");
                assert!(!permanent, "Redirect is the temporary mode");
            }
            Served::Bytes { .. } => panic!("expected a redirect"),
        }
        assert!(
            resolve(&state, "app.js").unwrap().is_none(),
            "a symlinked source is skipped, not redirected"
        );
        let (bytes, _) = resolve(&state, "real.txt").unwrap().unwrap().bytes();
        assert_eq!(bytes, b"data", "plain files keep the full guard chain");
    }

    #[cfg(all(unix, feature = "symlink-move"))]
    #[test]
    fn move_mode_marks_the_redirect_permanent() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("real.txt"), b"data").unwrap();
        std::os::unix::fs::symlink(Path::new("real.txt"), root.join("link.txt")).unwrap();

        let state = state_with(
            vec![Mount::root(root)],
            DevConfig {
                symlinks: crate::SymlinkMode::Move,
                ..DevConfig::default()
            },
        );
        match resolve(&state, "link.txt").unwrap().unwrap() {
            Served::Redirect { permanent, .. } => assert!(permanent),
            Served::Bytes { .. } => panic!("expected a redirect"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn follow_unsafe_suppresses_escape_warnings() {
        // Escapes are the mode's contract, so the startup line disappears with them.
        let tmp = tempfile::tempdir().unwrap();
        let private = tmp.path().join("private");
        std::fs::create_dir_all(&private).unwrap();
        std::fs::write(private.join("credentials.txt"), "secret").unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::os::unix::fs::symlink(&private, root.join("exposed")).unwrap();

        let config = DevConfig {
            symlinks: crate::SymlinkMode::FollowUnsafe,
            ..DevConfig::default()
        };
        let warnings = preflight_warnings(&[Mount::root(root)], &config);
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[cfg(all(unix, feature = "symlink-move"))]
    #[test]
    fn redirect_mode_warns_about_skipped_symlinks() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("real.txt"), "data").unwrap();
        std::os::unix::fs::symlink(root.join("real.txt"), root.join("link.txt")).unwrap();

        let config = DevConfig {
            symlinks: crate::SymlinkMode::Redirect,
            ..DevConfig::default()
        };
        let warnings = preflight_warnings(&[Mount::root(root)], &config);
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains("link.txt")
                && warnings[0].contains("redirect")
                && warnings[0].contains("skipped by build"),
            "got: {}",
            warnings[0]
        );
    }

    #[cfg(unix)]
    #[test]
    fn dev_warns_about_a_symlink_escaping_the_mount() {
        // Containment warnings are not silenced by `skip_duplicates` — the flag
        // arbitrates precedence, not the sandbox boundary.
        let tmp = tempfile::tempdir().unwrap();
        let private = tmp.path().join("private");
        std::fs::create_dir_all(&private).unwrap();
        std::fs::write(private.join("credentials.txt"), "secret").unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::os::unix::fs::symlink(&private, root.join("exposed")).unwrap();

        let config = DevConfig {
            skip_duplicates: true,
            ..DevConfig::default()
        };
        let warnings = preflight_warnings(&[Mount::root(root)], &config);
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains("exposed/credentials.txt")
                && warnings[0].contains("outside its mount")
                && warnings[0].contains("not served"),
            "got: {}",
            warnings[0]
        );
    }

    #[test]
    fn skip_duplicates_suppresses_dev_warnings() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("app.js"), b"literal();").unwrap();
        std::fs::write(root.join("app.ts"), "export const compiled = 1;").unwrap();

        let config = DevConfig {
            skip_duplicates: true,
            ..DevConfig::default()
        };
        let warnings = preflight_warnings(&[Mount::root(root)], &config);
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn dev_reports_reject_list_drops_even_under_skip_duplicates() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("index.html"), b"<x>").unwrap();
        std::fs::write(root.join(".env"), b"S=1").unwrap();

        let warnings = preflight_warnings(&[Mount::root(root.clone())], &DevConfig::default());
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains(".env") && warnings[0].contains("dropped by the reject list"),
            "got: {}",
            warnings[0]
        );

        // Policy, not precedence: the flag silences duplicate lines only.
        let config = DevConfig {
            skip_duplicates: true,
            ..DevConfig::default()
        };
        let warnings = preflight_warnings(&[Mount::root(root)], &config);
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
    }

    #[cfg(feature = "tera")]
    #[test]
    fn dev_reports_a_template_materializing_a_rejected_target() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join(".env.tera"), "S={{ 1 }}").unwrap();

        let warnings = preflight_warnings(&[Mount::root(root)], &DevConfig::default());
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains(".env.tera") && warnings[0].contains("would emit .env"),
            "got: {}",
            warnings[0]
        );
    }

    #[test]
    fn resolve_routes_by_prefix_mount() {
        let tmp = tempfile::tempdir().unwrap();
        let ui = tmp.path().join("ui");
        let api = tmp.path().join("api");
        std::fs::create_dir_all(&ui).unwrap();
        std::fs::create_dir_all(&api).unwrap();
        std::fs::write(ui.join("a.json"), b"\"ui\"").unwrap();
        std::fs::write(api.join("a.json"), b"\"api\"").unwrap();
        let state = state(vec![Mount::new("ui", ui), Mount::new("api", api)]);
        assert_eq!(
            &resolve(&state, "ui/a.json").unwrap().unwrap().bytes().0,
            b"\"ui\""
        );
        assert_eq!(
            &resolve(&state, "api/a.json").unwrap().unwrap().bytes().0,
            b"\"api\""
        );
        assert!(resolve(&state, "nope/a.json").unwrap().is_none());
    }

    #[test]
    fn overlay_same_prefix_first_dir_wins() {
        // Two dirs at the same (root) prefix offering the same target → first wins.
        let tmp = tempfile::tempdir().unwrap();
        let first = tmp.path().join("first");
        let second = tmp.path().join("second");
        std::fs::create_dir_all(&first).unwrap();
        std::fs::create_dir_all(&second).unwrap();
        std::fs::write(first.join("page.html"), b"first").unwrap();
        std::fs::write(second.join("page.html"), b"second").unwrap();
        let state = state(vec![Mount::root(first), Mount::root(second)]);
        assert_eq!(
            &resolve(&state, "page.html").unwrap().unwrap().bytes().0,
            b"first"
        );
    }

    #[test]
    fn sources_are_not_served_raw() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("app.scss"), "a{color:red}").unwrap();
        std::fs::write(root.join("app.ts"), "export const x = 1;").unwrap();
        let state = state(vec![Mount::root(root)]);
        // Originals are hidden; only the compiled targets are reachable.
        assert!(resolve(&state, "app.scss").unwrap().is_none());
        assert!(resolve(&state, "app.ts").unwrap().is_none());
        assert!(resolve(&state, "app.css").unwrap().is_some()); // compiled from app.scss
        assert!(resolve(&state, "app.js").unwrap().is_some()); // compiled from app.ts
    }

    #[cfg(feature = "tera")]
    #[test]
    fn dev_renders_tera_to_target() {
        // The live counterpart of the build pipeline's tree-wide `.tera`: a request for
        // the stripped target renders the `.tera` (the dev import map is empty).
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join("index.html.tera"),
            "<head>{{ importmap | safe }}</head>",
        )
        .unwrap();
        let state = state(vec![Mount::root(root)]);
        let (bytes, ct) = resolve(&state, "index.html").unwrap().unwrap().bytes();
        let html = String::from_utf8(bytes).unwrap();
        assert!(
            html.contains("<script type=\"importmap\">"),
            "rendered with the importmap var; got:\n{html}"
        );
        assert!(ct.starts_with("text/html"), "served as html; got {ct}");
    }

    #[cfg(feature = "tera")]
    #[test]
    fn dev_hides_tera_source() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("index.html.tera"), "<p>hi</p>").unwrap();
        let state = state(vec![Mount::root(root)]);
        // The rendered target is reachable; the raw `.tera` source is not.
        assert!(resolve(&state, "index.html").unwrap().is_some());
        assert!(resolve(&state, "index.html.tera").unwrap().is_none());
    }

    #[test]
    fn dev_respects_disabled_processor() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("app.scss"), "a{color:red}").unwrap();
        // SCSS disabled ⇒ no on-the-fly compile, and the `.scss` source stays hidden,
        // so `/app.css` 404s.
        let config = DevConfig {
            scss: false,
            ..DevConfig::default()
        };
        let state = state_with(vec![Mount::root(root)], config);
        assert!(resolve(&state, "app.css").unwrap().is_none());
    }

    #[cfg(feature = "tera")]
    #[test]
    fn dev_tera_wins_over_literal_same_target() {
        // Lock-step with the build pipeline: a `.tera` overlays a same-named literal (dev checks
        // `.tera` first, build renders it as a final overlay).
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("web");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("index.html"), "LITERAL").unwrap();
        std::fs::write(root.join("index.html.tera"), "TERA").unwrap();
        let state = state(vec![Mount::root(root)]);
        let (bytes, _) = resolve(&state, "index.html").unwrap().unwrap().bytes();
        assert_eq!(
            String::from_utf8(bytes).unwrap(),
            "TERA",
            "dev renders the .tera over the literal same-target"
        );
    }
}