laravel-rust-devtools 0.3.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! The files `frontend/` builds into the crate: the launcher a page loads, and the panel's script and
//! styles. Each has a version, which each new build changes, so a browser asks for it anew.

use laravel::http::{Request, Response, StatusCode, header};

/// One built file, served from memory.
pub(crate) struct Asset {
    bytes: &'static [u8],
    content_type: &'static str,
    /// FNV-1a of the bytes: the file's version and entity tag.
    hash: u64,
}

impl Asset {
    const fn new(bytes: &'static [u8], content_type: &'static str) -> Self {
        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
        let mut at = 0;
        while at < bytes.len() {
            hash = (hash ^ bytes[at] as u64).wrapping_mul(0x0100_0000_01b3);
            at += 1;
        }
        Self {
            bytes,
            content_type,
            hash,
        }
    }

    /// The file's version, for the `?v=` of a tag that loads it.
    pub(crate) fn version(&self) -> String {
        format!("{:016x}", self.hash)
    }

    /// The file, or `304` for a browser that holds this version.
    fn serve(&self, request: &Request) -> Response {
        let tag = format!("\"{}\"", self.version());
        let held = request
            .header(header::IF_NONE_MATCH)
            .is_some_and(|tags| tags.split(',').map(str::trim).any(|held| held == "*" || held == tag));
        let response = if held {
            Response::new(StatusCode::NOT_MODIFIED)
        } else {
            Response::new(self.bytes)
        };

        // The browser asks each time whether it still holds the newest build; the files exist only
        // for those let in, so no shared cache keeps them.
        response.with_headers([
            (header::CONTENT_TYPE, self.content_type),
            (header::CACHE_CONTROL, "private, no-cache"),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
            (header::ETAG, tag.as_str()),
        ])
    }
}

const SCRIPT: &str = "text/javascript; charset=utf-8";

/// The script that shows the toolbar on a page.
pub(crate) static LAUNCHER: Asset = Asset::new(include_bytes!("../../dist/launcher.js"), SCRIPT);
/// The panel's script.
pub(crate) static PANEL_SCRIPT: Asset = Asset::new(include_bytes!("../../dist/panel.js"), SCRIPT);
/// The panel's styles.
pub(crate) static PANEL_STYLES: Asset = Asset::new(include_bytes!("../../dist/panel.css"), "text/css; charset=utf-8");

/// `GET /_devtools/launcher.js`.
pub(crate) async fn launcher(request: Request) -> Response {
    LAUNCHER.serve(&request)
}

/// `GET /_devtools/panel.js`.
pub(crate) async fn panel_script(request: Request) -> Response {
    PANEL_SCRIPT.serve(&request)
}

/// `GET /_devtools/panel.css`.
pub(crate) async fn panel_styles(request: Request) -> Response {
    PANEL_STYLES.serve(&request)
}