footing 0.4.2

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

use super::{DocsError, resource};

/// Version of the bundle supplied by `redoc-embedded`.
#[cfg(feature = "redoc-embedded")]
pub const EMBEDDED_REDOC_VERSION: &str = "2.5.4";
/// Version of the bundle supplied by `rapidoc-embedded`.
#[cfg(feature = "rapidoc-embedded")]
pub const EMBEDDED_RAPIDOC_VERSION: &str = "9.3.8";

/// Documentation renderer and its explicitly selected JavaScript source.
///
/// Both renderers are available with `openapi`. Embedded constructors require
/// their respective feature and bind the bundle to the matching renderer.
/// Native options belong to the selected renderer; they are not interchangeable.
#[derive(Debug)]
#[non_exhaustive]
pub enum DocsUi {
    /// ReDoc 2.x, exposing the `Redoc.init` interface.
    Redoc(DocsAssets),
    /// RapiDoc 9.x, registering the `rapi-doc` custom element.
    RapiDoc(DocsAssets),
}

impl DocsUi {
    /// Uses the fixed ReDoc bundle, attribution image and third-party notices.
    #[cfg(feature = "redoc-embedded")]
    pub fn embedded_redoc() -> Self {
        Self::Redoc(DocsAssets::bundled(
            include_bytes!("embedded/redoc/redoc.standalone.js"),
            include_bytes!("embedded/redoc/LICENSES.txt"),
        ))
    }

    /// Uses the fixed RapiDoc bundle and third-party notices.
    ///
    /// Keep the preset's `load-fonts: false` for offline deployment.
    /// The bundled OAuth helpers use random per-attempt PKCE verifiers and
    /// validate callback origins, windows and state. Redirect callbacks must
    /// remain on the documentation origin; use HTTPS or localhost for Web Crypto.
    #[cfg(feature = "rapidoc-embedded")]
    pub fn embedded_rapidoc() -> Self {
        Self::RapiDoc(DocsAssets::bundled(
            include_bytes!("embedded/rapidoc/rapidoc-min.js"),
            include_bytes!("embedded/rapidoc/LICENSES.txt"),
        ))
    }

    pub(super) fn name(&self) -> &'static str {
        match self {
            Self::Redoc(_) => "redoc",
            Self::RapiDoc(_) => "rapidoc",
        }
    }

    pub(super) fn assets(&self) -> &DocsAssets {
        match self {
            Self::Redoc(assets) | Self::RapiDoc(assets) => assets,
        }
    }

    pub(super) fn into_assets(self) -> DocsAssets {
        match self {
            Self::Redoc(assets) | Self::RapiDoc(assets) => assets,
        }
    }
}

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

/// JavaScript loaded by a documentation renderer.
///
/// Local bytes are served as `ui.js` within the documentation router. URL sources
/// are loaded directly by the browser; their hosting application controls access.
/// No files, environment variables or URLs are read by this type.
#[must_use]
pub struct DocsAssets(Source);

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

impl DocsAssets {
    /// Serves a caller-supplied standalone bundle within the docs router.
    ///
    /// Use `include_bytes!(...).as_slice()` or explicitly read a file at startup.
    /// The caller manages the bundle's compatibility, dependencies and notices.
    /// Both renderers expect a classic script, not an ES module entry point.
    pub fn local(bundle: impl Into<Bytes>) -> Self {
        Self(Source::Local {
            bundle: bundle.into(),
            notices: None,
        })
    }

    /// Uses a trusted script URL without serving a bundle or fetching it in Rust.
    ///
    /// Absolute HTTP(S), root-relative and page-relative URLs are accepted.
    /// Relative URLs resolve against the documentation page's trailing slash.
    pub fn url(url: impl Into<String>) -> Self {
        Self(Source::Url(url.into()))
    }

    #[cfg(any(feature = "redoc-embedded", feature = "rapidoc-embedded"))]
    fn bundled(bundle: &'static [u8], notices: &'static [u8]) -> Self {
        Self(Source::Local {
            bundle: Bytes::from_static(bundle),
            notices: Some(Bytes::from_static(notices)),
        })
    }

    pub(super) fn script_url(&self) -> Result<&str, DocsError> {
        match &self.0 {
            Source::Local { .. } => Ok("./ui.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(DocsError::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}/ui.js"),
                resource("text/javascript; charset=utf-8", bundle),
            );
            if let Some(notices) = notices {
                router = router.route(
                    &format!("{mount}/ui.LICENSE.txt"),
                    resource("text/plain; charset=utf-8", notices),
                );
            }
        }
        router
    }
}