mini-static 0.14.7

A secure, async static file server with streaming, traversal protection, and connection limits.
Documentation
use std::path::{Path, PathBuf};
use std::fs;

use crate::bundle;
use crate::minify;

/// Bundle all CSS files from a source directory into a single output file.
///
/// Discovers all `.css` files in `src_dir`, reads and concatenates them (in sorted order),
/// follows `@import` statements within that directory, minifies the result, and writes it
/// to `output_path`.
///
/// The bundling process:
/// 1. Finds all `.css` files in src_dir (recursively, sorted by path)
/// 2. Reads and concatenates all CSS file contents
/// 3. Writes concatenated content to a temporary file
/// 4. Runs that through the bundler to resolve imports and minify
/// 5. Writes the final bytes to output_path
///
/// # Errors
///
/// Returns `Err` if:
/// - src_dir cannot be read
/// - output_path cannot be written to
/// - CSS parsing or bundling fails
pub async fn bundle_directory_css(
    src_dir: &Path,
    output_path: &Path,
) -> Result<(), CssBundlerError> {
    let src_dir_canon = src_dir.canonicalize().map_err(|e| {
        CssBundlerError::ReadSource {
            path: src_dir.to_path_buf(),
            reason: e.to_string(),
        }
    })?;

    let css_files = find_css_files(&src_dir_canon).map_err(|e| {
        CssBundlerError::ReadSource {
            path: src_dir.to_path_buf(),
            reason: e.to_string(),
        }
    })?;

    if css_files.is_empty() {
        return Err(CssBundlerError::NoFilesFound(src_dir.to_path_buf()));
    }

    let mut bundled_content = String::new();

    for css_file in &css_files {
        let (bytes, _deps) = bundle::bundle_and_minify_css(&[src_dir_canon.clone()], css_file)
            .await
            .map_err(|e| CssBundlerError::Bundle(format!("{:?}", e)))?;

        bundled_content.push_str(&String::from_utf8_lossy(&bytes));
    }

    let bundled_bytes_final = minify::minify(bundled_content.as_bytes(), crate::reload::ChangeType::Css)
        .map_err(|e| CssBundlerError::Bundle(format!("Minification failed: {:?}", e)))?;

    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            CssBundlerError::WriteOutput {
                path: output_path.to_path_buf(),
                reason: e.to_string(),
            }
        })?;
    }

    fs::write(output_path, &bundled_bytes_final).map_err(|e| {
        CssBundlerError::WriteOutput {
            path: output_path.to_path_buf(),
            reason: e.to_string(),
        }
    })?;

    Ok(())
}

/// Find all `.css` files in a directory tree.
fn find_css_files(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut css_files = Vec::new();
    let mut dirs = vec![dir.to_path_buf()];

    while let Some(current_dir) = dirs.pop() {
        let entries = fs::read_dir(&current_dir)?;
        for entry in entries {
            let entry = entry?;
            let path = entry.path();
            let file_type = entry.file_type()?;

            if file_type.is_dir() {
                dirs.push(path);
            } else if file_type.is_file() {
                if path.extension().and_then(|s| s.to_str()) == Some("css") {
                    css_files.push(path);
                }
            }
        }
    }

    css_files.sort();
    Ok(css_files)
}

/// Errors that can occur during CSS bundling.
#[derive(Debug)]
pub enum CssBundlerError {
    /// Failed to read the source directory.
    ReadSource { path: PathBuf, reason: String },
    /// Failed to write the output file.
    WriteOutput { path: PathBuf, reason: String },
    /// No CSS files found in the source directory.
    NoFilesFound(PathBuf),
    /// CSS bundling/minification failed.
    Bundle(String),
}

impl std::fmt::Display for CssBundlerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CssBundlerError::ReadSource { path, reason } => {
                write!(f, "failed to read source dir {}: {}", path.display(), reason)
            }
            CssBundlerError::WriteOutput { path, reason } => {
                write!(f, "failed to write output file {}: {}", path.display(), reason)
            }
            CssBundlerError::NoFilesFound(path) => {
                write!(f, "no CSS files found in {}", path.display())
            }
            CssBundlerError::Bundle(msg) => {
                write!(f, "CSS bundling failed: {}", msg)
            }
        }
    }
}

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