saola-kit 0.1.4

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
use std::collections::BTreeMap;

use serde::Serialize;
use sha2::{Digest, Sha256};

use super::store::TextResolver;
use super::tree::{I18nError, LanguageNode, LanguageTree};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeDefinition {
    pub keys: Vec<String>,
}

impl ScopeDefinition {
    pub fn new<I, S>(keys: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            keys: keys.into_iter().map(Into::into).collect(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ScopedCatalog {
    pub revision: i64,
    pub scope: String,
    pub messages: BTreeMap<String, LanguageNode>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ScopedClientConfig {
    pub locale: String,
    #[serde(rename = "fallbackLocale")]
    pub fallback_locale: String,
    pub scope: String,
    pub catalogs: BTreeMap<String, ScopedCatalog>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dictionary: Option<String>,
}

/// Scope-filtered client dictionary projector matching `ClientCatalogs` and `X-Saola-Language`.
#[derive(Debug, Clone)]
pub struct ClientCatalogs {
    resolver: TextResolver,
    scopes: BTreeMap<String, ScopeDefinition>,
    contexts: Vec<String>,
}

impl ClientCatalogs {
    pub fn new(resolver: TextResolver, scopes: BTreeMap<String, ScopeDefinition>) -> Self {
        Self { resolver, scopes, contexts: Vec::new() }
    }

    /// Scope = context: key là `{context}.key`, nên mỗi context đã khai tự có từ điển là nhánh `{context}`
    /// mà không cần `add_scope` (scope khai tường minh vẫn thắng). Như `ClientCatalogs::definition` của PHP.
    pub fn with_contexts<I, S>(mut self, contexts: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.contexts = contexts.into_iter().map(Into::into).collect();
        self
    }

    pub fn add_scope(&mut self, name: impl Into<String>, definition: ScopeDefinition) -> &mut Self {
        self.scopes.insert(name.into(), definition);
        self
    }

    pub fn definition(&self, scope: &str) -> Result<Vec<String>, I18nError> {
        let implicit;
        let def = match self.scopes.get(scope) {
            Some(def) => def,
            None if self.contexts.iter().any(|c| c == scope) => {
                implicit = ScopeDefinition::new([scope]);
                &implicit
            }
            None => return Err(I18nError::UnknownScope(scope.to_owned())),
        };
        for path in &def.keys {
            if path.is_empty() || path == "*" || path.starts_with('.') || path.ends_with('.') {
                return Err(I18nError::InvalidScopePath(path.clone()));
            }
        }
        let mut paths = def.keys.clone();
        paths.sort();
        paths.dedup();
        Ok(paths)
    }

    pub fn scope_id(scope: &str, sorted_unique_paths: &[String]) -> String {
        let json = serde_json::to_string(sorted_unique_paths).unwrap_or_else(|_| "[]".to_owned());
        let hash = hex::encode(Sha256::digest(json.as_bytes()));
        format!("{scope}:{}", &hash[..16])
    }

    pub fn snapshot(&self, scope: &str, locale: &str) -> Result<ScopedCatalog, I18nError> {
        let paths = self.definition(scope)?;
        let snapshot = self.resolver.snapshot(locale);
        let flat = LanguageTree::flatten(&snapshot.messages)?;

        let mut visible = BTreeMap::new();
        for (key, value) in flat {
            if paths.iter().any(|path| {
                key == *path
                    || (key.starts_with(path.as_str())
                        && key.as_bytes().get(path.len()) == Some(&b'.'))
            }) {
                visible.insert(key, value);
            }
        }

        let messages = LanguageTree::nest(&visible)?;
        Ok(ScopedCatalog {
            revision: snapshot.revision,
            scope: Self::scope_id(scope, &paths),
            messages,
        })
    }

    /// Parses `X-Saola-Language: <scope>;<locale>=<revision>;...`, returning an empty map if the
    /// header belongs to another scope or is absent.
    pub fn parse_held_header(held: Option<&str>, expected_scope_id: &str) -> BTreeMap<String, i64> {
        let Some(raw) = held else {
            return BTreeMap::new();
        };
        let mut parts = raw.split(';');
        if parts.next() != Some(expected_scope_id) {
            return BTreeMap::new();
        }
        let mut have = BTreeMap::new();
        for part in parts {
            let Some((code, rev_str)) = part.split_once('=') else {
                continue;
            };
            if !code.is_empty()
                && !rev_str.is_empty()
                && rev_str.bytes().all(|b| b.is_ascii_digit())
                && let Ok(rev) = rev_str.parse::<i64>()
            {
                have.insert(code.to_owned(), rev);
            }
        }
        have
    }

    pub fn client_config(
        &self,
        scope: &str,
        locale: Option<&str>,
        held: Option<&str>,
        dictionary_url: Option<String>,
    ) -> Result<ScopedClientConfig, I18nError> {
        let paths = self.definition(scope)?;
        let scope_id = Self::scope_id(scope, &paths);
        let raw = self.resolver.client_config(locale);
        let have = Self::parse_held_header(held, &scope_id);

        let mut catalogs = BTreeMap::new();
        for (code, cat) in &raw.catalogs {
            if have.get(code).copied() != Some(cat.revision) {
                catalogs.insert(code.clone(), self.snapshot(scope, code)?);
            }
        }

        Ok(ScopedClientConfig {
            locale: raw.locale,
            fallback_locale: raw.fallback_locale,
            scope: scope_id,
            catalogs,
            dictionary: dictionary_url,
        })
    }

    /// Filters out catalogs that the browser already holds at the same revision for this scope,
    /// matching `ClientCatalogs::withoutHeld`.
    pub fn without_held(mut config: ScopedClientConfig, held: Option<&str>) -> ScopedClientConfig {
        let have = Self::parse_held_header(held, &config.scope);
        config
            .catalogs
            .retain(|code, cat| have.get(code).copied() != Some(cat.revision));
        config
    }

    /// Formats `X-Saola-Language-Revision` header when at least one catalog needs syncing.
    pub fn language_revision_header(config: &ScopedClientConfig) -> Option<String> {
        if config.catalogs.is_empty() {
            return None;
        }
        let mut parts = Vec::with_capacity(config.catalogs.len() + 1);
        parts.push(config.scope.clone());
        for (code, catalog) in &config.catalogs {
            parts.push(format!("{code}={}", catalog.revision));
        }
        Some(parts.join(";"))
    }
}