bundla 0.8.0

Bundle HTML, CSS, and JS/TS: prod build with minification and hashed filenames by default, dev build with sourcemaps, composable watch and serve
Documentation
use std::path::{Path, PathBuf};

use tokio::sync::broadcast::{self, Sender, error::RecvError};
use webadev::ReloadType;

use crate::{BuildOptions, build};

/// What triggered a build during watch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildCause {
    /// The first build, which runs before `watch` returns.
    Startup,
    /// A detected source change triggered the build.
    Change,
    /// Source events were dropped, so the whole tree is rebuilt conservatively.
    Lagged,
}

/// A runtime log line from the watch loop, sent on the caller's broadcast
/// channel so the library never prints directly.
///
/// The variants report the outcome of each build attempt;
/// [`WatchLog::Built`] also carries the cause that triggered it.
#[derive(Clone, Debug)]
pub enum WatchLog {
    /// A build succeeded and `dist` is in place.
    Built {
        /// What triggered the build.
        cause: BuildCause,
        /// Full page or CSS only.
        reload_type: ReloadType,
        /// Changed files for [`BuildCause::Change`].
        /// Empty for [`BuildCause::Startup`] and [`BuildCause::Lagged`].
        paths: Vec<PathBuf>,
    },
    /// A non-fatal build warning (unreadable asset skipped, etc.).
    Warn(String),
    /// A build failure during watch; the previous build is kept.
    Error(String),
}

/// Headless watch handle returned by [`watch`].
///
/// No server is involved: no port, no HTTP, no browser. The build
/// loop runs while the [`Watch::run`] future is alive; dropping it stops
/// watching. Nothing is ever injected into the written files.
#[derive(Debug)]
pub struct Watch {
    rx_src: broadcast::Receiver<(ReloadType, Vec<PathBuf>)>,
    src: PathBuf,
    dist: PathBuf,
    options: BuildOptions,
    tx_log: Sender<WatchLog>,
    // Dist-change events for the server: a successful build
    // triggers a browser reload. `None` when headless.
    tx_dist: Option<Sender<(ReloadType, Vec<PathBuf>)>>,
}

/// Watch `src` and build it into `dist` on startup and on every
/// change, without serving. Headless: no server, no port, no browser.
///
/// `filter` narrows the build to files whose name matches an item, e.g.
/// `&["html", "css", "one-file.html"]`. An item matches when the file name
/// equals `<item>` or ends with `.<item>`. Items are trimmed and lowercased,
/// a leading dot or path separator is rejected, and empty items are ignored.
/// An empty `filter` (including `&[""]`) watches every file under `src`.
///
/// The first build runs before `watch` returns, so a failure aborts with `Err`.
/// Every detected change triggers a build.
///
/// Runtime logs are reported on `tx_log`:
/// - [`WatchLog::Built`]: a successful build, after `dist` is replaced.
///   - [`BuildCause::Startup`] for the first build,
///   - [`BuildCause::Change`] for a rebuild with changed files,
///   - [`BuildCause::Lagged`] for a conservative full rebuild
/// - [`WatchLog::Warn`]: build warnings
/// - [`WatchLog::Error`]: build failures (previous build kept)
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// use bundla::{BuildOptions, WatchLog, watch};
/// use tempfile::tempdir;
/// use tokio::sync::broadcast;
///
/// #[tokio::main]
/// async fn main() {
///     let dir = tempdir().unwrap();
///     let src = dir.path().join("src");
///     std::fs::create_dir_all(&src).unwrap();
///     std::fs::write(src.join("index.html"), "<html><body>v1</body></html>").unwrap();
///
///     let (tx_log, _rx_log) = broadcast::channel::<WatchLog>(100);
///     let dist = dir.path().join("dev");
///     // build on `.html` changes only; `&[]` watches every file
///     let watcher = watch(&src, &dist, &BuildOptions::DEV, tx_log, &["html"])
///         .await
///         .unwrap();
///
///     // `src` is built once before `watch` returns
///     assert!(std::fs::read_to_string(dist.join("index.html")).unwrap().contains("v1"));
///
///     // `run` rebuilds on every change, until its future is dropped
///     let handle = tokio::spawn(watcher.run());
///     std::fs::write(src.join("index.html"), "<html><body>v2</body></html>").unwrap();
///     handle.abort(); // stop watching
/// }
/// ```
pub async fn watch(
    src: &Path,
    dist: &Path,
    options: &BuildOptions,
    tx_log: Sender<WatchLog>,
    filter: &[&str],
) -> Result<Watch, String> {
    watch_setup(src, dist, options, tx_log, filter, None).await
}

// Shared by `watch` and the server `watch_serve`:
// - start the filesystem watcher on `src`
// - build once on startup
// - keep the change receiver for the build loop (`Watch::run`)
//
// `filter`: watched file name suffixes; empty watches every file.
//
// `tx_dist`:
// - forwards dist-change events to the server (browser reload),
// - `None` without a server.
pub(crate) async fn watch_setup(
    src: &Path,
    dist: &Path,
    options: &BuildOptions,
    tx_log: Sender<WatchLog>,
    filter: &[&str],
    tx_dist: Option<Sender<(ReloadType, Vec<PathBuf>)>>,
) -> Result<Watch, String> {
    // Src-change events: when the user updates files in the src directory
    let (tx_src, rx_src) = broadcast::channel(100);

    webadev::watch(tx_src, src, filter)
        .map_err(|err| format!("failed to watch {}: {err}", src.display()))?;

    // Build once on startup
    build(src, dist, options)
        .await
        .map_err(|err| format!("build error: {err}"))?
        .into_iter()
        .for_each(|warning| {
            let _ = tx_log.send(WatchLog::Warn(warning));
        });

    let _ = tx_log.send(WatchLog::Built {
        cause: BuildCause::Startup,
        reload_type: ReloadType::Page,
        paths: vec![],
    });

    Ok(Watch {
        rx_src,
        src: src.to_path_buf(),
        dist: dist.to_path_buf(),
        options: options.clone(),
        tx_log,
        tx_dist,
    })
}

// Wait for the next source event.
//
// `Closed` ends the watch loop.
// `Lagged` must never close so silently.
// A lag means events were dropped: rebuild everything once and ask for a full
// page reload, since the type of the dropped burst is unknown.

async fn src_event_recv(
    rx: &mut broadcast::Receiver<(ReloadType, Vec<PathBuf>)>,
) -> Option<(BuildCause, ReloadType, Vec<PathBuf>)> {
    match rx.recv().await {
        Ok((reload_type, paths)) => Some((BuildCause::Change, reload_type, paths)),
        Err(RecvError::Lagged(_)) => Some((BuildCause::Lagged, ReloadType::Page, vec![])),
        Err(RecvError::Closed) => None,
    }
}

impl Watch {
    /// Build on every source change, forever, until the future is dropped.
    ///
    /// Each detected change rebuilds the whole `src` directory.
    ///
    /// A successful build is reported on the log channel as [`WatchLog::Built`]
    /// with its [`BuildCause`], *after* `dist` has been replaced.
    ///
    /// Warnings are reported as [`WatchLog::Warn`].
    /// A failed build is reported as [`WatchLog::Error`]
    /// and the previous output is kept.
    pub async fn run(mut self) -> Result<(), String> {
        while let Some((cause, reload_type, paths)) = src_event_recv(&mut self.rx_src).await {
            match build(&self.src, &self.dist, &self.options).await {
                Ok(warnings) => {
                    warnings.into_iter().for_each(|warning| {
                        let _ = self.tx_log.send(WatchLog::Warn(warning));
                    });

                    // `dist` is in place: report the type browsers (and
                    // headless consumers) should use, once per build.
                    let reload_type = browser_reload(reload_type, &self.options);

                    if let Some(tx_dist) = &self.tx_dist {
                        let _ = tx_dist.send((reload_type, paths.clone()));
                    }

                    let _ = self.tx_log.send(WatchLog::Built {
                        cause,
                        reload_type,
                        paths,
                    });
                }
                Err(err) => {
                    // Keep the previous build
                    let _ = self
                        .tx_log
                        .send(WatchLog::Error(format!("build error: {err}")));
                }
            }
        }

        Ok(())
    }
}

// How a successful build tells connected browsers to reload.
//
// Css hot-reload re-fetches the stylesheet href held by the page.
// It only works with stable filenames.
// With hashed filenames the build change the name so the stale href would 404.
// Ask for a full page reload instead, which picks up the fresh hashed references.
fn browser_reload(reload_type: ReloadType, options: &BuildOptions) -> ReloadType {
    if options.hash {
        ReloadType::Page
    } else {
        reload_type
    }
}

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

    #[test]
    fn hashed_css_changes_reload_full_page() {
        assert_eq!(
            browser_reload(ReloadType::Css, &BuildOptions::PROD),
            ReloadType::Page
        );
        assert_eq!(
            browser_reload(ReloadType::Page, &BuildOptions::PROD),
            ReloadType::Page
        );
    }

    #[test]
    fn unhashed_css_changes_hot_reload() {
        assert_eq!(
            browser_reload(ReloadType::Css, &BuildOptions::DEV),
            ReloadType::Css
        );
        assert_eq!(
            browser_reload(ReloadType::Page, &BuildOptions::DEV),
            ReloadType::Page
        );
    }

    #[tokio::test]
    async fn src_event_recovers_from_lag() {
        let (tx, mut rx) = broadcast::channel::<(ReloadType, Vec<PathBuf>)>(1);
        tx.send((ReloadType::Css, vec![PathBuf::from("a.css")]))
            .unwrap();
        tx.send((ReloadType::Css, vec![PathBuf::from("b.css")]))
            .unwrap();
        tx.send((ReloadType::Css, vec![PathBuf::from("c.css")]))
            .unwrap();
        drop(tx);

        let (cause, reload_type, paths) = src_event_recv(&mut rx).await.expect("a lagged event");
        assert_eq!(cause, BuildCause::Lagged);
        assert_eq!(reload_type, ReloadType::Page);
        assert!(paths.is_empty());

        let (cause, reload_type, paths) = src_event_recv(&mut rx).await.expect("a buffered event");
        assert_eq!(cause, BuildCause::Change);
        assert_eq!(reload_type, ReloadType::Css);
        assert_eq!(paths, vec![PathBuf::from("c.css")]);

        assert!(src_event_recv(&mut rx).await.is_none(), "channel closed");
    }
}