footing 0.1.13

Feature-gated foundations for Rust backend services
Documentation
use axum::{Router, body::Bytes, http::Uri};

use super::{RedocDocsError, resource};

/// Version of ReDoc supplied by the `redoc-embedded` feature and tested presets.
#[cfg(feature = "redoc-embedded")]
pub const EMBEDDED_REDOC_VERSION: &str = "2.5.4";

enum Source {
    Local {
        bundle: Bytes,
        notices: Option<Bytes>,
    },
    Url(String),
}

/// Explicit source of the ReDoc 2.x standalone JavaScript bundle.
///
/// A feature never silently changes the selected resource source. Bundles passed
/// as bytes are served within the documentation router; URL sources are loaded
/// directly by the browser and are protected by their hosting application's
/// middleware. This type never fetches URLs or opens local files.
#[must_use]
pub struct RedocAssets(Source);

impl std::fmt::Debug for RedocAssets {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            Source::Local { bundle, .. } => f
                .debug_struct("RedocAssets::Local")
                .field("bytes", &bundle.len())
                .finish_non_exhaustive(),
            Source::Url(url) => f.debug_tuple("RedocAssets::Url").field(url).finish(),
        }
    }
}

impl RedocAssets {
    /// Serves caller-supplied bundle bytes as `redoc.js` within the docs router.
    ///
    /// Use `include_bytes!(...).as_slice()` or explicitly read a file at startup.
    /// The caller supplies a compatible bundle and manages its dependencies and
    /// license notices. No CDN fallback is used.
    ///
    /// ```no_run
    /// use footing::http::openapi::{RedocAssets, RedocDocs};
    /// # use footing::http::openapi::utoipa::openapi::{OpenApi, Info, path::Paths};
    /// # let document = OpenApi::new(Info::new("Inventory API", "1"), Paths::new());
    ///
    /// // Read an application-selected file explicitly during startup.
    /// let bundle = std::fs::read("assets/redoc.standalone.js")?;
    /// let docs = RedocDocs::new(document, "/docs", RedocAssets::local(bundle))
    ///     .into_router::<()>()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn local(bundle: impl Into<Bytes>) -> Self {
        Self(Source::Local {
            bundle: bundle.into(),
            notices: None,
        })
    }

    /// Uses a trusted, application-specified script URL without serving a bundle.
    ///
    /// Absolute HTTP(S), root-relative and page-relative URLs are accepted.
    /// Page-relative URLs resolve against the documentation page with a trailing
    /// slash. The caller manages access control, CSP and dependencies at this URL.
    pub fn url(url: impl Into<String>) -> Self {
        Self(Source::Url(url.into()))
    }

    /// Serves the fixed, offline bundle and notices included in this crate.
    ///
    /// Requires `redoc-embedded`. The bundle's attribution logo is embedded as a
    /// data URL; no CDN or font stylesheet is used. Original and dependency
    /// notices are served as `redoc.LICENSE.txt` alongside `redoc.js`.
    #[cfg(feature = "redoc-embedded")]
    pub fn embedded() -> Self {
        Self(Source::Local {
            bundle: Bytes::from_static(include_bytes!("embedded/redoc.standalone.js")),
            notices: Some(Bytes::from_static(include_bytes!("embedded/LICENSES.txt"))),
        })
    }

    pub(super) fn script_url(&self) -> Result<&str, RedocDocsError> {
        match &self.0 {
            Source::Local { .. } => Ok("./redoc.js"),
            Source::Url(url) => {
                let valid = !url.is_empty()
                    && !url.starts_with("//")
                    && !url
                        .chars()
                        .any(|c| c.is_whitespace() || c.is_control() || c == '\\')
                    && url.parse::<Uri>().is_ok_and(|uri| match uri.scheme_str() {
                        Some("http" | "https") => uri.host().is_some(),
                        Some(_) => false,
                        None => !url.split('/').next().unwrap_or_default().contains(':'),
                    });
                if valid {
                    Ok(url)
                } else {
                    Err(RedocDocsError::InvalidAssetUrl(url.clone()))
                }
            }
        }
    }

    pub(super) fn mount<S: Clone + Send + Sync + 'static>(
        self,
        mut router: Router<S>,
        mount: &str,
    ) -> Router<S> {
        if let Source::Local { bundle, notices } = self.0 {
            router = router.route(
                &format!("{mount}/redoc.js"),
                resource("text/javascript; charset=utf-8", bundle),
            );
            if let Some(notices) = notices {
                router = router.route(
                    &format!("{mount}/redoc.LICENSE.txt"),
                    resource("text/plain; charset=utf-8", notices),
                );
            }
        }
        router
    }
}