mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
#![cfg_attr(docsrs, feature(doc_cfg))]
//! Unified async Rust client for the Minecraft ecosystem.
//!
//! All HTTP platform clients can share a single `Arc`-backed [`HttpClient`] (and its connection
//! pool, [`Mirror`] routing, and [`ResiliencePolicy`]) either directly via `::from_http(http)`
//! or through the lightweight [`McApi`] entry point (`McApi::builder()`).
//!
//! Every module returns the unified [`Error`] and [`Result`] types, uses [`McUuid`] for Minecraft
//! UUIDs, and re-exports public dependency crates under [`reexports`].
//!
//! Enable only the modules you need via Cargo features (`mojang`, `modrinth`, `modrinth-write`,
//! `curseforge`, `curseforge-cdn-fallback`, `yggdrasil`, `yggdrasil-authlib`,
//! `yggdrasil-verify`, `blessing`, `loaders`, `bmclapi`, `java`, `stream`, `tracing`) or keep
//! the default `full` feature set. When any HTTP feature is enabled, select exactly one TLS
//! backend: `tls-aws-lc` (default), `tls-native`, `tls-native-vendored`, or
//! `tls-rustls-no-provider`.

pub mod error;
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub mod http;
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub mod mirror;
#[cfg(feature = "profile")]
#[cfg_attr(docsrs, doc(cfg(feature = "profile")))]
pub mod profile;
#[cfg(all(test, feature = "http"))]
#[path = "../tests/integration/common.rs"]
pub(crate) mod test_common;
#[cfg(feature = "http")]
pub(crate) mod util;
pub mod uuid;

#[cfg(feature = "curseforge")]
#[cfg_attr(docsrs, doc(cfg(feature = "curseforge")))]
pub mod curseforge;

#[cfg(feature = "modrinth")]
#[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
pub mod modrinth;

#[cfg(feature = "mojang")]
#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
pub mod mojang;

#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
pub mod yggdrasil;

#[cfg(feature = "blessing")]
#[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
pub mod blessing;

#[cfg(feature = "loaders")]
#[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
pub mod loaders;

#[cfg(feature = "bmclapi")]
#[cfg_attr(docsrs, doc(cfg(feature = "bmclapi")))]
pub mod bmclapi;

#[cfg(feature = "java")]
#[cfg_attr(docsrs, doc(cfg(feature = "java")))]
pub mod java;

#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub use error::ApiStatusError;
#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
pub use error::YggdrasilError;
pub use error::{Error, Result};
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub use http::{HttpClient, HttpClientBuilder, ResiliencePolicy};
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub use mirror::{Mirror, RewriteRule};
pub use uuid::McUuid;

/// Re-exports of upstream dependency crates exposed in `mcapi` public types and signatures.
///
/// Using these re-exports prevents Cargo semver/version-mismatch issues when callers accept
/// or construct types such as [`reqwest::Client`], [`url::Url`], [`jiff::Timestamp`],
/// [`uuid::Uuid`], [`rsa::RsaPublicKey`], or [`serde_json::Value`].
pub mod reexports {
    /// Re-export of the `uuid` crate used by [`McUuid`](crate::McUuid).
    pub use ::uuid;
    /// Re-export of the `jiff` crate used for timestamps.
    #[cfg(any(
        feature = "curseforge",
        feature = "modrinth",
        feature = "mojang",
        feature = "java"
    ))]
    #[cfg_attr(
        docsrs,
        doc(cfg(any(
            feature = "curseforge",
            feature = "modrinth",
            feature = "mojang",
            feature = "java"
        )))
    )]
    pub use jiff;
    /// Re-export of the `reqwest` crate used by [`HttpClient`](crate::HttpClient).
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    pub use reqwest;
    /// Re-export of the `rsa` crate used by `yggdrasil-verify`.
    #[cfg(feature = "yggdrasil-verify")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-verify")))]
    pub use rsa;
    /// Re-export of the `serde_json` crate used in [`Error::Json`](crate::Error::Json) and extensible model fields.
    pub use serde_json;
    /// Re-export of the `url` crate used for endpoint and asset URLs.
    #[cfg(any(feature = "http", feature = "profile"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "http", feature = "profile"))))]
    pub use url;
}

/// Builder for [`McApi`].
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[derive(Clone, Debug, Default)]
pub struct McApiBuilder {
    http: HttpClientBuilder,
}

#[cfg(feature = "http")]
impl McApiBuilder {
    /// Creates a new [`McApiBuilder`] with default [`HttpClient`] settings.
    #[must_use]
    pub fn new() -> Self {
        Self {
            http: HttpClientBuilder::new(),
        }
    }

    /// Sets the `User-Agent` header used when building an internal `reqwest::Client`.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.http = self.http.user_agent(user_agent);
        self
    }

    /// Configures the [`Mirror`] routing strategy shared across clients.
    #[must_use]
    pub fn mirror(mut self, mirror: Mirror) -> Self {
        self.http = self.http.mirror(mirror);
        self
    }

    /// Configures the [`ResiliencePolicy`] (retries, backoff, and official fallback).
    #[must_use]
    pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
        self.http = self.http.resilience(resilience);
        self
    }

    /// Sets the request timeout when building an internal `reqwest::Client`.
    #[must_use]
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.http = self.http.timeout(timeout);
        self
    }

    /// Adds a default header when building an internal `reqwest::Client`.
    #[must_use]
    pub fn default_header(
        mut self,
        name: reqwest::header::HeaderName,
        value: reqwest::header::HeaderValue,
    ) -> Self {
        self.http = self.http.default_header(name, value);
        self
    }

    /// Injects a pre-configured `reqwest::Client` (for connection pool sharing or custom TLS).
    #[must_use]
    pub fn reqwest_client(mut self, client: reqwest::Client) -> Self {
        self.http = self.http.reqwest_client(client);
        self
    }

    /// Builds a [`McApi`] facade backed by the configured [`HttpClient`].
    pub fn build(self) -> Result<McApi> {
        Ok(McApi::from_http(self.http.build()?))
    }
}

/// Lightweight shared entry point holding a single [`HttpClient`] (one `reqwest::Client`
/// connection pool, [`Mirror`], and [`ResiliencePolicy`]) and vending zero-cost platform clients.
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[derive(Clone, Debug)]
pub struct McApi {
    http: HttpClient,
}

#[cfg(feature = "http")]
impl McApi {
    /// Creates a new [`McApi`] with default [`HttpClient`] settings.
    pub fn new() -> Result<Self> {
        Ok(Self {
            http: HttpClient::new()?,
        })
    }

    /// Returns a [`McApiBuilder`] for configuring mirrors, resilience policies, and headers.
    #[must_use]
    pub fn builder() -> McApiBuilder {
        McApiBuilder::new()
    }

    /// Wraps an existing shared [`HttpClient`].
    #[must_use]
    pub const fn from_http(http: HttpClient) -> Self {
        Self { http }
    }

    /// Returns a reference to the underlying shared [`HttpClient`].
    #[must_use]
    pub fn http(&self) -> &HttpClient {
        &self.http
    }

    /// Returns a [`mojang::MojangClient`] sharing this instance's [`HttpClient`].
    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[must_use]
    pub fn mojang(&self) -> mojang::MojangClient {
        mojang::MojangClient::from_http(self.http.clone())
    }

    /// Returns a [`modrinth::ModrinthClient`] sharing this instance's [`HttpClient`].
    #[cfg(feature = "modrinth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
    #[must_use]
    pub fn modrinth(&self) -> modrinth::ModrinthClient {
        modrinth::ModrinthClient::from_http(self.http.clone())
    }

    /// Returns a [`curseforge::CurseForgeClient`] sharing this instance's [`HttpClient`].
    ///
    /// - When `api_key` is `Some(key)` (non-blank), attaches `x-api-key` only for direct
    ///   unrewritten requests (never forwarded to third-party mirrors).
    /// - When `api_key` is `None` (or blank) and the active [`Mirror`] rewrites
    ///   `https://api.curseforge.com`, constructs a keyless mirror client (skipping official
    ///   fallback).
    /// - Otherwise returns [`Error::InvalidInput`].
    #[cfg(feature = "curseforge")]
    #[cfg_attr(docsrs, doc(cfg(feature = "curseforge")))]
    pub fn curseforge(&self, api_key: Option<&str>) -> Result<curseforge::CurseForgeClient> {
        curseforge::CurseForgeClient::from_http(self.http.clone(), api_key)
    }

    /// Returns a [`yggdrasil::YggdrasilClient`] targeting `api_root` and sharing this instance's [`HttpClient`].
    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    pub fn yggdrasil(&self, api_root: impl AsRef<str>) -> Result<yggdrasil::YggdrasilClient> {
        yggdrasil::YggdrasilClient::from_http(self.http.clone(), api_root)
    }

    /// Returns an [`AuthlibInjectorClient`](yggdrasil::authlib_injector::AuthlibInjectorClient) sharing this instance's [`HttpClient`].
    #[cfg(feature = "yggdrasil-authlib")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-authlib")))]
    #[must_use]
    pub fn authlib_injector(&self) -> yggdrasil::authlib_injector::AuthlibInjectorClient {
        yggdrasil::authlib_injector::AuthlibInjectorClient::from_http(self.http.clone())
    }

    /// Returns a [`blessing::BlessingClient`] targeting `site_url` and sharing this instance's [`HttpClient`].
    #[cfg(feature = "blessing")]
    #[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
    pub fn blessing(&self, site_url: impl AsRef<str>) -> Result<blessing::BlessingClient> {
        blessing::BlessingClient::from_http(self.http.clone(), site_url)
    }

    /// Returns a [`loaders::LoadersClient`] sharing this instance's [`HttpClient`].
    #[cfg(feature = "loaders")]
    #[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
    #[must_use]
    pub fn loaders(&self) -> loaders::LoadersClient {
        loaders::LoadersClient::from_http(self.http.clone())
    }

    /// Returns a [`bmclapi::BmclapiClient`] sharing this instance's [`HttpClient`].
    #[cfg(feature = "bmclapi")]
    #[cfg_attr(docsrs, doc(cfg(feature = "bmclapi")))]
    #[must_use]
    pub fn bmclapi(&self) -> bmclapi::BmclapiClient {
        bmclapi::BmclapiClient::from_http(self.http.clone())
    }

    /// Returns a [`java::JavaClient`] sharing this instance's [`HttpClient`].
    #[cfg(feature = "java")]
    #[cfg_attr(docsrs, doc(cfg(feature = "java")))]
    #[must_use]
    pub fn java(&self) -> java::JavaClient {
        java::JavaClient::from_http(self.http.clone())
    }
}

#[cfg(feature = "http")]
impl From<HttpClient> for McApi {
    fn from(http: HttpClient) -> Self {
        Self { http }
    }
}