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 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` and/or one file per group,
/// `<dir>/<locale>/<group>.json`, whose file stem becomes the top-level key (`admin.json` -> `{"admin": ..}`).
/// Group files win over keys of the same name in `<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 mut files = vec![self.dir.join(format!("{locale}.json"))];
        let mut groups: Vec<PathBuf> = std::fs::read_dir(self.dir.join(locale))
            .map(|rd| rd.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).collect())
            .unwrap_or_default();
        groups.sort();
        files.extend(groups.iter().cloned());

        let mut tree = serde_json::Map::new();
        let mut revision = 0_i64;
        let mut found = false;
        for path in &files {
            let Ok(contents) = std::fs::read_to_string(path) else { continue };
            let value: serde_json::Value = match serde_json::from_str(&contents) {
                Ok(v) => v,
                Err(error) => {
                    tracing::error!(locale, path = %path.display(), error = %error, "Failed to parse language JSON");
                    return LanguageSnapshot::default();
                }
            };
            let is_group = path.parent().is_some_and(|p| p != self.dir);
            match (is_group, value) {
                (true, v) => { tree.insert(path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), v); }
                (false, serde_json::Value::Object(map)) => tree.extend(map),
                (false, _) => return LanguageSnapshot::default(),
            }
            found = true;
            revision = revision.max(
                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),
            );
        }
        if !found {
            return LanguageSnapshot::default();
        }
        match LanguageJson::decode_default(&serde_json::Value::Object(tree).to_string()) {
            Ok(messages) => LanguageSnapshot { revision, messages },
            Err(error) => {
                tracing::error!(locale, error = %error, "Failed to parse language tree");
                LanguageSnapshot::default()
            }
        }
    }
}

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
}