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
use std::path::{Path, PathBuf};

use crate::css::{self, CssOptions, CssTool};
use crate::js::{self, JsOptions, JsTool};
use crate::reload::ChangeType;
use crate::watcher::{Broadcaster, ChangeEvent};

/// Routes source-folder file changes to the pipeline that turns them into served output.
///
/// The watcher layer runs over *source folders only*. The designated output dir is never
/// watched and never a trigger: every pipeline below writes its own output, and a pipeline
/// that listened to its own output would re-trigger itself forever (the feedback-loop bug
/// this design fixes). Instead, after a build finishes, the pipeline broadcasts the reload
/// event for the output it wrote, so the browser still hot-swaps/reloads.
///
/// CSS and JS are each independently configured via an optional `(tool, options)` pair.
/// `options.bundle()` selects between two disjoint modes per language: bundle (a single
/// discovered/entry-driven output, rebuilt in full on any relevant change) or per-file
/// (every source file mirrored independently into the output dir).
pub(crate) struct SourcePipeline {
    source_folders: Vec<PathBuf>,
    bundle_roots: Vec<PathBuf>,
    output_dir: PathBuf,
    css_tool: Option<(CssTool, CssOptions)>,
    js_tool: Option<(JsTool, JsOptions)>,
    prune_output: bool,
    broadcaster: Broadcaster,
}

impl SourcePipeline {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        source_folders: Vec<PathBuf>,
        bundle_roots: Vec<PathBuf>,
        output_dir: PathBuf,
        css_tool: Option<(CssTool, CssOptions)>,
        js_tool: Option<(JsTool, JsOptions)>,
        prune_output: bool,
        broadcaster: Broadcaster,
    ) -> Self {
        SourcePipeline {
            source_folders,
            bundle_roots,
            output_dir,
            css_tool,
            js_tool,
            prune_output,
            broadcaster,
        }
    }

    /// Rebuild every enabled output once, then prune stale output if configured.
    ///
    /// Runs at server startup. Never during live-reload — see [`Self::prune_stale_output`].
    pub(crate) async fn full_build(&self) -> Result<(), SourceError> {
        let css_written = self.build_css_bundle().await?;
        self.build_js_bundle().await?;
        self.build_all_per_file().await?;

        if self.prune_output {
            self.prune_stale_output(css_written.as_deref()).await?;
        }

        Ok(())
    }

    /// Handle a single change event for `path` (which must be under a watched source
    /// folder or import root), rebuilding output as needed and broadcasting the reload
    /// event for whatever was written.
    pub(crate) async fn process_change(
        &self,
        path: &Path,
        change_type: &ChangeType,
    ) -> Result<(), SourceError> {
        if change_type == &ChangeType::Css && self.is_input(path) {
            if let Some((_, options)) = &self.css_tool {
                let written = if options.is_bundle() {
                    self.build_css_bundle().await?
                } else {
                    self.rebuild_css_file(path).await?
                };
                if let Some(output) = written {
                    self.broadcast_change(&output);
                }
                return Ok(());
            }
        }

        if change_type == &ChangeType::Script && self.is_input(path) {
            if let Some((_, options)) = &self.js_tool {
                let written = if options.is_bundle() {
                    self.build_js_bundle().await?
                } else {
                    self.rebuild_js_file(path).await?
                };
                if let Some(output) = written {
                    self.broadcast_change(&output);
                }
                return Ok(());
            }
        }

        // No pipeline owns this file kind. Re-broadcast only genuine watched-input
        // changes so the client reloads and re-fetches whatever external builder produced
        // the output. The watcher never watches the output dir, so the ONLY paths that
        // reach here without being under a watched root are this pipeline's own broadcast
        // echoes (e.g. a rebuilt bundle) — re-broadcasting those would make the pipeline
        // loop on its own output forever, flooding the SSE stream (the `_mr` cycling bug).
        if self.is_input(path) {
            self.broadcaster.broadcast(ChangeEvent {
                path: path.to_path_buf(),
                change_type: change_type.clone(),
            });
        }
        Ok(())
    }

    /// Rebuild the single CSS bundle from every source folder, if CSS bundle mode is
    /// configured. Returns the output path it wrote, or `None` when bundle mode isn't
    /// configured or no CSS sources exist (nothing to produce).
    async fn build_css_bundle(&self) -> Result<Option<PathBuf>, SourceError> {
        let Some((css_tool, options)) = &self.css_tool else {
            return Ok(None);
        };
        if !options.is_bundle() || !self.has_css_sources() {
            return Ok(None);
        }

        let output = self.output_dir.join(options.output_file_name());
        css::build_css_bundle(*css_tool, options, &self.source_folders, &output)
            .await
            .map_err(SourceError::Css)?;

        Ok(Some(output))
    }

    /// Rebuild the JS bundle from its configured entry point, if JS bundle mode is
    /// configured. Returns the output path it wrote, or `None` when bundle mode isn't
    /// configured.
    async fn build_js_bundle(&self) -> Result<Option<PathBuf>, SourceError> {
        let Some((js_tool, options)) = &self.js_tool else {
            return Ok(None);
        };
        let (true, Some(entry)) = (options.is_bundle(), options.entry()) else {
            return Ok(None);
        };

        let name = options.output_file_name().unwrap_or("bundle.js");
        let output = self.output_dir.join(name);
        js::build_js_bundle(*js_tool, options, entry, &output)
            .await
            .map_err(SourceError::Js)?;

        Ok(Some(output))
    }

    /// Process every file under every source folder through whichever per-file (i.e.
    /// non-bundle) pipeline claims its extension. Bundle-mode CSS/JS is handled
    /// separately by [`Self::build_css_bundle`]/[`Self::build_js_bundle`].
    async fn build_all_per_file(&self) -> Result<(), SourceError> {
        for folder in &self.source_folders {
            let files = list_files(folder).await.map_err(SourceError::Io)?;
            for file in files {
                if is_css(&file) {
                    if let Some((css_tool, options)) = &self.css_tool {
                        if !options.is_bundle() {
                            let output = self.mirror_output(folder, &file)?;
                            css::build_css_file(*css_tool, options, &file, &output)
                                .await
                                .map_err(SourceError::Css)?;
                        }
                    }
                } else if is_script(&file) {
                    if let Some((js_tool, options)) = &self.js_tool {
                        if !options.is_bundle() {
                            let output = self.mirror_output(folder, &file)?;
                            js::build_js_file(*js_tool, options, &file, &output)
                                .await
                                .map_err(SourceError::Js)?;
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Rebuild a single changed CSS file into its mirrored output path (per-file mode
    /// only — bundle mode always rebuilds the whole bundle via [`Self::build_css_bundle`]).
    async fn rebuild_css_file(&self, source: &Path) -> Result<Option<PathBuf>, SourceError> {
        let Some(folder) = self.containing_source_folder(source) else {
            return Ok(None);
        };
        if !is_css(source) {
            return Ok(None);
        }
        let Some((css_tool, options)) = &self.css_tool else {
            return Ok(None);
        };

        let output = self.mirror_output(folder, source)?;
        css::build_css_file(*css_tool, options, source, &output)
            .await
            .map_err(SourceError::Css)?;
        Ok(Some(output))
    }

    /// Rebuild a single changed JS file into its mirrored output path (per-file mode
    /// only — bundle mode always rebuilds the whole bundle via [`Self::build_js_bundle`]).
    async fn rebuild_js_file(&self, source: &Path) -> Result<Option<PathBuf>, SourceError> {
        let Some(folder) = self.containing_source_folder(source) else {
            return Ok(None);
        };
        if !is_script(source) {
            return Ok(None);
        }
        let Some((js_tool, options)) = &self.js_tool else {
            return Ok(None);
        };

        let output = self.mirror_output(folder, source)?;
        js::build_js_file(*js_tool, options, source, &output)
            .await
            .map_err(SourceError::Js)?;
        Ok(Some(output))
    }

    /// The output path for `source`, mirroring its path relative to `folder` under the
    /// output dir.
    fn mirror_output(&self, folder: &Path, source: &Path) -> Result<PathBuf, SourceError> {
        let relative = source
            .strip_prefix(folder)
            .map_err(|_| SourceError::NotUnderSource(source.to_path_buf()))?;
        Ok(self.output_dir.join(relative))
    }

    /// Broadcast a reload event for `output`, deriving its change type from the output's
    /// own extension so the browser hot-swaps/reloads exactly as it would for that file.
    fn broadcast_change(&self, output: &Path) {
        self.broadcaster.broadcast(ChangeEvent {
            path: output.to_path_buf(),
            change_type: ChangeType::from_path(output),
        });
    }

    /// True when `path` lives under any watched root (a source folder or a CSS `@import`
    /// root). These are the only paths the watcher emits, so an event whose path fails
    /// this check must be the pipeline's own output echo and must not be re-broadcast.
    fn is_input(&self, path: &Path) -> bool {
        self.source_folders
            .iter()
            .chain(self.bundle_roots.iter())
            .any(|root| path.starts_with(root))
    }

    /// The source folder containing `path`, if any.
    fn containing_source_folder(&self, path: &Path) -> Option<&PathBuf> {
        self.source_folders
            .iter()
            .find(|folder| path.starts_with(folder))
    }

    /// True when at least one `.css` file exists under the source folders.
    fn has_css_sources(&self) -> bool {
        for folder in &self.source_folders {
            if walk_dir(folder).any(|path| is_css(&path)) {
                return true;
            }
        }
        false
    }

    /// The CSS bundle's output path, if CSS bundle mode is configured.
    fn css_bundle_output_path(&self) -> Option<PathBuf> {
        let (_, options) = self.css_tool.as_ref()?;
        if !options.is_bundle() {
            return None;
        }
        Some(self.output_dir.join(options.output_file_name()))
    }

    /// Remove stale output at build time, never during live-reload.
    ///
    /// The only output this server can own *by identity* is the CSS bundle file — a single
    /// exact path that no hand-written file shares. If bundling is enabled but no CSS
    /// sources remain, the leftover bundle is removed. Per-file outputs are deliberately
    /// NOT auto-pruned: their mirrored paths can coincide with hand-written files, and
    /// deleting files the server doesn't own is a surprise (A1) the caller can't opt into
    /// by accident.
    async fn prune_stale_output(&self, css_written: Option<&Path>) -> Result<(), SourceError> {
        let Some(bundle) = self.css_bundle_output_path() else {
            return Ok(());
        };

        let wrote_bundle = css_written.is_some_and(|written| written == bundle);
        if wrote_bundle {
            return Ok(());
        }

        if tokio::fs::metadata(&bundle).await.is_err() {
            return Ok(());
        }

        tokio::fs::remove_file(&bundle)
            .await
            .map_err(SourceError::Io)?;
        eprintln!("pruned stale css bundle output: {}", bundle.display());
        Ok(())
    }
}

/// Why [`SourcePipeline`] could not produce output for a change or build.
#[derive(Debug)]
pub(crate) enum SourceError {
    /// The CSS tool step failed.
    Css(css::CssError),
    /// The JS tool step failed.
    Js(js::JsError),
    /// A filesystem operation failed.
    Io(std::io::Error),
    /// A changed path was not under the source folder claimed to contain it.
    NotUnderSource(PathBuf),
}

impl std::fmt::Display for SourceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SourceError::Css(e) => write!(f, "css tool step failed: {e}"),
            SourceError::Js(e) => write!(f, "js tool step failed: {e}"),
            SourceError::Io(e) => write!(f, "io error: {e}"),
            SourceError::NotUnderSource(p) => {
                write!(f, "path not under any source folder: {}", p.display())
            }
        }
    }
}

impl std::error::Error for SourceError {}

/// True if `path` names a CSS file (by extension).
fn is_css(path: &Path) -> bool {
    path.extension().and_then(|e| e.to_str()) == Some("css")
}

/// True if `path` names a script the tool accepts (`js`/`mjs`).
fn is_script(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("js" | "mjs")
    )
}

/// Recursively list every file under `dir`.
///
/// Bounded by the filesystem: `walk_dir` pushes directories onto a stack and terminates
/// when none remain — a directory tree is finite, so this loop always ends.
async fn list_files(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    let mut dirs = vec![dir.to_path_buf()];

    while let Some(current) = dirs.pop() {
        let mut entries = tokio::fs::read_dir(&current).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if entry.file_type().await?.is_dir() {
                dirs.push(path);
            } else {
                files.push(path);
            }
        }
    }

    Ok(files)
}

/// Synchronously walk `dir` and yield every file path. Used by the cheap existence check
/// in [`SourcePipeline::has_css_sources`] (runs at build boundaries, not per request).
fn walk_dir(dir: &Path) -> impl Iterator<Item = PathBuf> {
    let mut dirs = vec![dir.to_path_buf()];
    std::iter::from_fn(move || {
        while let Some(current) = dirs.pop() {
            let Ok(entries) = std::fs::read_dir(&current) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if entry.file_type().is_ok_and(|t| t.is_dir()) {
                    dirs.push(path);
                } else {
                    return Some(path);
                }
            }
        }
        None
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::time::Duration;
    use tempfile::TempDir;

    /// Regression: the pipeline must not loop on its own output. The pipeline subscribes
    /// to the same broadcaster it broadcasts into. After rebuilding the CSS bundle it
    /// broadcasts a `css` event for the output path — that echo must NOT be re-broadcast,
    /// or the pipeline loops forever and floods the SSE stream (the bug where the browser
    /// kept cycling fresh `_mr` values). Here one source change must produce exactly two
    /// events (the source change itself plus the bundle broadcast), then stop.
    #[tokio::test]
    async fn pipeline_does_not_rebroadcast_its_own_output_echo() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(src.path().join("style.css"), "body { margin: 0; }")
            .await
            .unwrap();

        let broadcaster = Broadcaster::new();
        let pipeline = Arc::new(SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            Some((CssTool::TestEcho, CssOptions::new().bundle(true))),
            None,
            false,
            broadcaster.clone(),
        ));

        // The pipeline consumes the same broadcaster it writes to, exactly as in `run_on`.
        // Subscribe both receivers here so they are registered before the broadcast (the
        // spawned task alone could miss it while still scheduling on the test runtime).
        let mut pipeline_rx = broadcaster.subscribe();
        let mut observer = broadcaster.subscribe();
        let pipeline_task = tokio::spawn(async move {
            while let Some(event) = pipeline_rx.recv().await {
                if let Err(e) = pipeline
                    .process_change(&event.path, &event.change_type)
                    .await
                {
                    eprintln!("source pipeline error: {e}");
                }
            }
        });

        broadcaster.broadcast(ChangeEvent {
            path: src.path().join("style.css"),
            change_type: ChangeType::Css,
        });

        // Collect every event the SSE clients would see during a bounded window.
        let mut count = 0usize;
        let window = Duration::from_millis(400);
        let deadline = tokio::time::Instant::now() + window;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                break;
            }
            match tokio::time::timeout(remaining, observer.recv()).await {
                Ok(Some(_)) => count += 1,
                Ok(None) | Err(_) => break,
            }
        }

        pipeline_task.abort();

        assert_eq!(
            count, 2,
            "a single source css change must emit exactly the source event + the bundle \
             broadcast, and then stop — not feed back forever (got {count})"
        );
    }

    #[tokio::test]
    async fn css_bundle_mode_concatenates_into_the_configured_output_name() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(src.path().join("a.css"), "A")
            .await
            .unwrap();

        let pipeline = SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            Some((
                CssTool::TestEcho,
                CssOptions::new()
                    .bundle(true)
                    .bundle_output_name("main.css"),
            )),
            None,
            false,
            Broadcaster::new(),
        );

        pipeline.full_build().await.unwrap();

        assert_eq!(fs_read(out.path().join("main.css")), "A");
    }

    #[tokio::test]
    async fn css_per_file_mode_mirrors_every_source_file() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(src.path().join("a.css"), "A")
            .await
            .unwrap();
        tokio::fs::write(src.path().join("b.css"), "B")
            .await
            .unwrap();

        let pipeline = SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            Some((CssTool::TestEcho, CssOptions::new())),
            None,
            false,
            Broadcaster::new(),
        );

        pipeline.full_build().await.unwrap();

        assert_eq!(fs_read(out.path().join("a.css")), "A");
        assert_eq!(fs_read(out.path().join("b.css")), "B");
    }

    #[tokio::test]
    async fn js_bundle_mode_writes_the_entry_through_the_tool() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        let entry = src.path().join("main.js");
        tokio::fs::write(&entry, "const x = 1;").await.unwrap();

        let pipeline = SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            None,
            Some((
                JsTool::TestEcho,
                JsOptions::new().bundle_entry(&entry, "bundle.js"),
            )),
            false,
            Broadcaster::new(),
        );

        pipeline.full_build().await.unwrap();

        assert_eq!(fs_read(out.path().join("bundle.js")), "const x = 1;");
    }

    #[tokio::test]
    async fn no_tool_configured_processes_nothing() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(src.path().join("app.css"), "body{}")
            .await
            .unwrap();
        tokio::fs::write(src.path().join("app.js"), "x=1;")
            .await
            .unwrap();

        let pipeline = SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            None,
            None,
            false,
            Broadcaster::new(),
        );

        pipeline.full_build().await.unwrap();

        assert!(
            !out.path().join("app.css").exists() && !out.path().join("app.js").exists(),
            "with no css/js tool configured, nothing should be written to the output dir"
        );
    }

    #[tokio::test]
    async fn prune_output_removes_stale_css_bundle_when_no_css_sources_remain() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(out.path().join("styles.css"), "/* stale */")
            .await
            .unwrap();

        let pipeline = SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            Some((CssTool::TestEcho, CssOptions::new().bundle(true))),
            None,
            true,
            Broadcaster::new(),
        );

        pipeline.full_build().await.unwrap();

        assert!(
            !out.path().join("styles.css").exists(),
            "prune is opt-in: with_prune_output should delete the stale bundle produced by no css sources"
        );
    }

    #[tokio::test]
    async fn without_prune_stale_css_bundle_is_left_in_place() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(out.path().join("styles.css"), "/* stale */")
            .await
            .unwrap();

        let pipeline = SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            Some((CssTool::TestEcho, CssOptions::new().bundle(true))),
            None,
            false,
            Broadcaster::new(),
        );

        pipeline.full_build().await.unwrap();

        assert!(
            out.path().join("styles.css").exists(),
            "without with_prune_output the stale bundle must be left in place"
        );
    }

    fn fs_read(path: PathBuf) -> String {
        std::fs::read_to_string(path).unwrap()
    }
}