saola-kit 0.1.3

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
#[cfg(feature = "context")]
pub mod context;
#[cfg(feature = "envelope")]
pub mod envelope;
#[cfg(feature = "i18n")]
pub mod i18n;
#[cfg(feature = "masks")]
pub mod masks;
#[cfg(feature = "module")]
pub mod module;
#[cfg(feature = "repository")]
pub mod repository;
#[cfg(feature = "smtp")]
mod smtp;
#[cfg(feature = "tokens")]
pub mod tokens;
#[cfg(feature = "view")]
pub mod view;

#[cfg(feature = "i18n")]
use std::collections::BTreeMap;
#[cfg(any(feature = "context", feature = "envelope", feature = "i18n", feature = "view"))]
use std::sync::Arc;
#[cfg(feature = "context")]
use std::sync::Mutex;

use laravel::config::{Config, Env, Section};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
#[cfg(feature = "envelope")]
use laravel::http::Request;
#[cfg(feature = "envelope")]
use serde_json::Value;

#[cfg(feature = "context")]
use context::{ContextRegistry, ContextSpec, RouteEntry, SharedRouteIndex};
#[cfg(feature = "envelope")]
use envelope::ClientShare;
#[cfg(feature = "i18n")]
use i18n::{ClientCatalogs, LanguageStore, MemoryLanguageStore, ScopeDefinition, TextResolver};
#[cfg(feature = "module")]
use module::{ModuleRegistry, SaolaModule};

#[derive(Debug, Clone, Section)]
pub struct SaolaConfig {
    #[env("SAOLA_PRIMARY_HOST", default = "")]
    pub primary_host: String,
    #[env("SAOLA_DEFAULT_LOCALE", default = "vi")]
    pub default_locale: String,
    #[env("SAOLA_FALLBACK_LOCALE", default = "en")]
    pub fallback_locale: String,
}

#[cfg(feature = "envelope")]
type ShareInit = Box<dyn Fn(&ClientShare) + Send + Sync>;

/// Service provider integrating `saola-kit` subsystems into a `laravel-rust` application.
#[derive(Default)]
pub struct SaolaServiceProvider {
    #[cfg(feature = "context")]
    context_registry: ContextRegistry,
    #[cfg(feature = "module")]
    module_registry: ModuleRegistry,
    #[cfg(feature = "envelope")]
    share_inits: Vec<ShareInit>,
    #[cfg(feature = "i18n")]
    language_store: Option<Arc<dyn LanguageStore>>,
    #[cfg(feature = "i18n")]
    language_scopes: BTreeMap<String, ScopeDefinition>,
    #[cfg(feature = "view")]
    enable_view_helpers: bool,
    #[cfg(feature = "view")]
    ssr_site: Option<Arc<dyn view::SsrSite>>,
}

impl std::fmt::Debug for SaolaServiceProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SaolaServiceProvider").finish_non_exhaustive()
    }
}

impl SaolaServiceProvider {
    pub fn new() -> Self {
        Self::default()
    }

    #[cfg(feature = "context")]
    pub fn with_context(mut self, spec: ContextSpec) -> Self {
        self.context_registry.add_context(spec);
        self
    }

    #[cfg(feature = "context")]
    pub fn with_route(mut self, entry: RouteEntry) -> Self {
        self.context_registry.add_route(entry);
        self
    }

    #[cfg(feature = "module")]
    pub fn with_module<M: SaolaModule>(mut self, module: M) -> Self {
        self.module_registry.add(module);
        self
    }

    #[cfg(feature = "envelope")]
    pub fn with_share<F>(mut self, key: &'static str, resolver: F) -> Self
    where
        F: Fn(&Request) -> laravel::Result<Option<Value>> + Send + Sync + 'static,
    {
        let resolver = Arc::new(resolver);
        self.share_inits.push(Box::new(move |share| {
            let resolver = Arc::clone(&resolver);
            if let Err(err) = share.share(key, move |req| resolver(req)) {
                tracing::error!(error = %err, "Failed to register Saola share key");
            }
        }));
        self
    }

    #[cfg(feature = "i18n")]
    pub fn with_language_store(mut self, store: Arc<dyn LanguageStore>) -> Self {
        self.language_store = Some(store);
        self
    }

    #[cfg(feature = "i18n")]
    pub fn with_language_scope(
        mut self,
        name: impl Into<String>,
        definition: ScopeDefinition,
    ) -> Self {
        self.language_scopes.insert(name.into(), definition);
        self
    }

    #[cfg(feature = "view")]
    pub fn with_minijinja_helpers(mut self) -> Self {
        self.enable_view_helpers = true;
        self
    }

    /// Cấp các hàm `site_url/site_app_url/site_asset/site_languages` cho template SSR (bật luôn helper MiniJinja).
    #[cfg(feature = "view")]
    pub fn with_ssr_site(mut self, site: Arc<dyn view::SsrSite>) -> Self {
        self.enable_view_helpers = true;
        self.ssr_site = Some(site);
        self
    }
}

impl ServiceProvider for SaolaServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
        #[cfg(feature = "smtp")]
        smtp::configure(config, env);
    }

    fn register(&self, app: &mut Registrar) {
        let _ = app;
        #[cfg(feature = "smtp")]
        smtp::register(app);
        #[cfg(any(feature = "context", feature = "i18n"))]
        let saola_config = app.config().section::<SaolaConfig>().clone();

        #[cfg(feature = "context")]
        #[allow(unused_variables)]
        let (shared_registry, shared_route_index) = {
            let primary = if saola_config.primary_host.is_empty() {
                app.config().app.url.clone()
            } else {
                saola_config.primary_host.clone()
            };
            let registry = Arc::new(Mutex::new(self.context_registry.clone()));
            let shared_index = SharedRouteIndex::new(Arc::clone(&registry), primary);
            app.instance(self.context_registry.clone());
            app.instance(shared_index.clone());

            let shared_for_singleton = shared_index.clone();
            app.singleton(move |_| {
                let shared = shared_for_singleton.clone();
                async move {
                    shared
                        .index()
                        .map(|arc| (*arc).clone())
                        .map_err(|err| laravel::Error::msg(err.to_string()))
                }
            });

            (registry, shared_index)
        };

        #[cfg(feature = "envelope")]
        {
            let share = ClientShare::new();
            for init in &self.share_inits {
                init(&share);
            }
            app.instance(share);
        }

        #[cfg(feature = "i18n")]
        #[allow(unused_variables)]
        let text_resolver = {
            let store: Arc<dyn LanguageStore> = self
                .language_store
                .clone()
                .unwrap_or_else(|| Arc::new(MemoryLanguageStore::new()));
            let resolver = TextResolver::new(
                store,
                saola_config.default_locale,
                saola_config.fallback_locale,
            );
            // Each context is an implicit scope: its client receives the `<context>.*` subtree of the catalog.
            #[cfg(feature = "context")]
            let contexts: Vec<String> = self.context_registry.contexts().iter().map(|c| c.slug.clone()).collect();
            #[cfg(not(feature = "context"))]
            let contexts: Vec<String> = Vec::new();
            let catalogs = ClientCatalogs::new(resolver.clone(), self.language_scopes.clone()).with_contexts(contexts);
            let resolver_arc = Arc::new(resolver.clone());
            app.instance(resolver);
            app.instance(catalogs);
            resolver_arc
        };

        #[cfg(feature = "module")]
        {
            app.instance(self.module_registry.clone());
            self.module_registry.register_all(app);
            let specs = shared_registry
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .contexts()
                .to_vec();
            self.module_registry
                .register_context_routes(app, specs, Arc::clone(&shared_registry));
        }

        #[cfg(feature = "view")]
        if self.enable_view_helpers {
            let resolver = Arc::clone(&text_resolver);
            let routes = Some(shared_route_index.clone());
            let site = self.ssr_site.clone();
            app.views().minijinja(move |env| {
                view::register_ssr_helpers(env, Arc::clone(&resolver), routes.clone(), site.clone());
            });
        }
    }
}

pub mod prelude {
    pub use crate::{SaolaConfig, SaolaServiceProvider};

    #[cfg(feature = "context")]
    pub use crate::context::{
        ContextError, ContextHosts, ContextLinksRule, ContextRegistry, ContextRoute, ContextRoutes,
        ContextSpec, ContextTarget, HrefOptions, RouteEntry, RouteIndex, SetCurrentContext,
        SharedRouteIndex, current_context, set_current_context,
    };

    #[cfg(feature = "envelope")]
    pub use crate::envelope::{
        AppBootConfig, ClientAuthProjection, ClientAuthUser, ClientShare, Envelope, PageResponse,
        ViewContextState, render, wants_saola_json,
    };

    #[cfg(feature = "i18n")]
    pub use crate::i18n::{
        ClientCatalogs, FileLanguageStore, LanguageJson, LanguageNode, LanguageStore,
        LanguageTree, MemoryLanguageStore, ScopeDefinition, TextResolver,
    };

    #[cfg(feature = "masks")]
    pub use crate::masks::{Mask, MaskExt, PiiMask, mask_all};

    #[cfg(feature = "module")]
    pub use crate::module::{ModuleMeta, ModuleRegistry, SaolaModule};

    #[cfg(feature = "repository")]
    pub use crate::repository::{CursorParams, PageMeta, PageParams, PageResult};

    #[cfg(feature = "tokens")]
    pub use crate::tokens::{
        CurrentAccessToken, NewAccessToken, PersonalAccessToken, SanctumGuard, TokenStore,
        create_personal_access_tokens_table, current_access_token, has_token_ability,
        require_ability, token_can,
    };
}