saola-kit 0.1.0

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::UNIX_EPOCH;

use serde::Serialize;

use super::json::LanguageJson;
use super::tree::{I18nError, LanguageNode, LanguageTree};

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

/// Source of locale translation snapshots.
pub trait LanguageStore: Send + Sync {
    fn snapshot(&self, locale: &str) -> LanguageSnapshot;
}

/// In-memory translation store, useful for tests and bundled dictionaries.
#[derive(Debug, Clone, Default)]
pub struct MemoryLanguageStore {
    locales: Arc<RwLock<BTreeMap<String, LanguageSnapshot>>>,
}

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

    pub fn insert(
        &self,
        locale: impl Into<String>,
        revision: i64,
        messages: BTreeMap<String, LanguageNode>,
    ) -> &Self {
        if let Ok(mut map) = self.locales.write() {
            map.insert(locale.into(), LanguageSnapshot { revision, messages });
        }
        self
    }

    pub fn insert_json(
        &self,
        locale: impl Into<String>,
        revision: i64,
        json: &str,
    ) -> Result<&Self, I18nError> {
        let messages = LanguageJson::decode_default(json)?;
        Ok(self.insert(locale, revision, messages))
    }
}

impl LanguageStore for MemoryLanguageStore {
    fn snapshot(&self, locale: &str) -> LanguageSnapshot {
        self.locales
            .read()
            .ok()
            .and_then(|map| map.get(locale).cloned())
            .unwrap_or_default()
    }
}

/// Directory-backed JSON translation store (`<dir>/<locale>.json`).
#[derive(Debug, Clone)]
pub struct FileLanguageStore {
    dir: PathBuf,
    cache: Arc<RwLock<BTreeMap<String, LanguageSnapshot>>>,
}

impl FileLanguageStore {
    pub fn new(dir: impl AsRef<Path>) -> Self {
        Self {
            dir: dir.as_ref().to_path_buf(),
            cache: Arc::new(RwLock::new(BTreeMap::new())),
        }
    }

    pub fn reload(&self) {
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
    }

    fn load_locale(&self, locale: &str) -> LanguageSnapshot {
        if !is_safe_locale(locale) {
            return LanguageSnapshot::default();
        }
        let path = self.dir.join(format!("{locale}.json"));
        let Ok(contents) = std::fs::read_to_string(&path) else {
            return LanguageSnapshot::default();
        };
        let messages = match LanguageJson::decode_default(&contents) {
            Ok(tree) => tree,
            Err(error) => {
                tracing::error!(locale, path = %path.display(), error = %error, "Failed to parse language JSON");
                return LanguageSnapshot::default();
            }
        };
        let revision = std::fs::metadata(&path)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs() as i64)
            .unwrap_or(1);

        LanguageSnapshot { revision, messages }
    }
}

impl LanguageStore for FileLanguageStore {
    fn snapshot(&self, locale: &str) -> LanguageSnapshot {
        if let Ok(cache) = self.cache.read()
            && let Some(snapshot) = cache.get(locale)
        {
            return snapshot.clone();
        }
        let snapshot = self.load_locale(locale);
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(locale.to_owned(), snapshot.clone());
        }
        snapshot
    }
}

fn is_safe_locale(locale: &str) -> bool {
    !locale.is_empty()
        && locale
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
}

#[derive(Debug, Clone, Serialize)]
pub struct ClientI18nConfig {
    pub locale: String,
    #[serde(rename = "fallbackLocale")]
    pub fallback_locale: String,
    pub catalogs: BTreeMap<String, LanguageSnapshot>,
}

/// Resolves localized strings and builds base client i18n configurations.
#[derive(Clone)]
pub struct TextResolver {
    store: Arc<dyn LanguageStore>,
    default_locale: String,
    fallback_locale: String,
}

impl std::fmt::Debug for TextResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextResolver")
            .field("default_locale", &self.default_locale)
            .field("fallback_locale", &self.fallback_locale)
            .finish()
    }
}

impl TextResolver {
    pub fn new(
        store: Arc<dyn LanguageStore>,
        default_locale: impl Into<String>,
        fallback_locale: impl Into<String>,
    ) -> Self {
        Self {
            store,
            default_locale: default_locale.into(),
            fallback_locale: fallback_locale.into(),
        }
    }

    pub fn default_locale(&self) -> &str {
        &self.default_locale
    }

    pub fn fallback_locale(&self) -> &str {
        &self.fallback_locale
    }

    pub fn snapshot(&self, locale: &str) -> LanguageSnapshot {
        self.store.snapshot(locale)
    }

    pub fn text(
        &self,
        key: &str,
        replace: &[(&str, &str)],
        default: Option<&str>,
        locale: Option<&str>,
    ) -> String {
        let active = locale.unwrap_or(&self.default_locale);
        let primary_snap = self.snapshot(active);
        let mut resolved = LanguageTree::get(&primary_snap.messages, key).map(str::to_owned);

        if resolved.is_none() && active != self.fallback_locale {
            let fallback_snap = self.snapshot(&self.fallback_locale);
            resolved = LanguageTree::get(&fallback_snap.messages, key).map(str::to_owned);
        }

        let template = resolved
            .or_else(|| default.map(str::to_owned))
            .unwrap_or_else(|| key.to_owned());

        if replace.is_empty() {
            return template;
        }

        apply_replacements(&template, replace)
    }

    pub fn client_config(&self, locale: Option<&str>) -> ClientI18nConfig {
        let active = locale.unwrap_or(&self.default_locale).to_owned();
        let mut catalogs = BTreeMap::new();
        catalogs.insert(active.clone(), self.snapshot(&active));
        if self.fallback_locale != active {
            catalogs.insert(
                self.fallback_locale.clone(),
                self.snapshot(&self.fallback_locale),
            );
        }
        ClientI18nConfig {
            locale: active,
            fallback_locale: self.fallback_locale.clone(),
            catalogs,
        }
    }
}

fn apply_replacements(template: &str, replace: &[(&str, &str)]) -> String {
    let mut pairs: Vec<(String, String)> = Vec::with_capacity(replace.len() * 3);
    for &(name, val) in replace {
        pairs.push((format!(":{name}"), val.to_owned()));
        pairs.push((format!(":{}", ucfirst_unicode(name)), ucfirst_unicode(val)));
        pairs.push((format!(":{}", name.to_uppercase()), val.to_uppercase()));
    }
    // Longest-key-first single-pass scan (matches PHP strtr semantics).
    pairs.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));

    let mut out = String::with_capacity(template.len());
    let mut idx = 0;
    while idx < template.len() {
        let rest = &template[idx..];
        if rest.starts_with(':')
            && let Some((needle, replacement)) =
                pairs.iter().find(|(needle, _)| rest.starts_with(needle.as_str()))
        {
            out.push_str(replacement);
            idx += needle.len();
            continue;
        }
        if let Some(ch) = rest.chars().next() {
            out.push(ch);
            idx += ch.len_utf8();
        } else {
            break;
        }
    }
    out
}

fn ucfirst_unicode(s: &str) -> String {
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return String::new();
    };
    let mut out = String::with_capacity(s.len());
    for upper in first.to_uppercase() {
        out.push(upper);
    }
    out.push_str(chars.as_str());
    out
}