laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
use indexmap::IndexMap;
use laravel::config::{Env, Section};

/// The OpenAI translator, `texts.openai` in the PHP package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenAiConfig {
    /// Read from `OPENAI_API_KEY`.
    pub api_key: Option<String>,
    /// Read from `OPENAI_MODEL`.
    pub model: String,
    /// Seconds to wait for an answer.
    pub timeout: u64,
    /// Attempts per request.
    pub retries: u32,
    /// The longest answer asked for, in tokens. The model's own limit caps it, and batches are
    /// sized to fit it.
    pub max_output_tokens: u64,
    /// Overrides the effort sent to a reasoning model.
    pub reasoning_effort: Option<String>,
}

impl Default for OpenAiConfig {
    fn default() -> Self {
        Self {
            api_key: None,
            model: "gpt-5.4-nano".to_owned(),
            timeout: 60,
            retries: 3,
            max_output_tokens: 4096,
            reasoning_effort: None,
        }
    }
}

/// The Claude (Anthropic) translator, `texts.claude` in the PHP package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeConfig {
    /// Read from `ANTHROPIC_API_KEY`.
    pub api_key: Option<String>,
    /// Read from `ANTHROPIC_MODEL`.
    pub model: String,
    /// Seconds to wait for an answer.
    pub timeout: u64,
    /// Attempts per request.
    pub retries: u32,
    /// The longest answer asked for, in tokens. The model's own limit caps it.
    pub max_tokens: u64,
}

impl Default for ClaudeConfig {
    fn default() -> Self {
        Self {
            api_key: None,
            model: "claude-haiku-4-5".to_owned(),
            timeout: 60,
            retries: 3,
            max_tokens: 4096,
        }
    }
}

/// The Google Translate translator, `texts.google` in the PHP package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GoogleConfig {
    /// Read from `GOOGLE_TRANSLATOR_API_KEY`.
    pub api_key: Option<String>,
    /// Seconds to wait for an answer.
    pub timeout: u64,
    /// Attempts per request.
    pub retries: u32,
}

impl Default for GoogleConfig {
    fn default() -> Self {
        Self {
            api_key: None,
            timeout: 20,
            retries: 3,
        }
    }
}

/// The Translatorio translator, `texts.translatorio` in the PHP package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranslatorioConfig {
    /// Read from `TRANSLATORIO_API_KEY`.
    pub api_key: Option<String>,
    /// Read from `TRANSLATORIO_URL`. It only changes for a self-hosted or local instance.
    pub url: String,
    /// The slug of a glossary on your account. Read from `TRANSLATORIO_GLOSSARY`.
    pub glossary: Option<String>,
    /// `default`, `formal` or `informal`. Read from `TRANSLATORIO_FORMALITY`.
    pub formality: Option<String>,
    /// `default`, `low`, `medium` or `high`, which picks the model. Read from `TRANSLATORIO_EFFORT`.
    pub effort: Option<String>,
    /// `auto` sends the strings with HTML tags as `html` and the rest as `text`. `text`, `html` or
    /// `markdown` sends every string that way.
    pub format: String,
    /// Seconds to wait for an answer.
    pub timeout: u64,
    /// Retries after the first attempt.
    pub retries: u32,
}

impl Default for TranslatorioConfig {
    fn default() -> Self {
        Self {
            api_key: None,
            url: "https://translatorio.com".to_owned(),
            glossary: None,
            formality: None,
            effort: None,
            format: "auto".to_owned(),
            timeout: 180,
            retries: 3,
        }
    }
}

/// A row of `texts.models`: what a project says about a model, by its name or a prefix of it.
///
/// A field left as `None` keeps what the package knows about the model, or the cautious defaults
/// of a model it does not know.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModelOverride {
    /// The most tokens one answer may hold.
    pub max_output_tokens: Option<u64>,
    /// Whether `temperature` may be sent.
    pub temperature: Option<bool>,
    /// `schema`, `object` or `none`.
    pub json: Option<String>,
    /// Whether the model thinks before answering, spending output tokens.
    pub reasoning: Option<bool>,
    /// The effort to ask for.
    pub reasoning_effort: Option<String>,
}

impl ModelOverride {
    /// A row that changes nothing yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// The most tokens one answer may hold.
    #[must_use]
    pub fn max_output_tokens(mut self, tokens: u64) -> Self {
        self.max_output_tokens = Some(tokens);

        self
    }

    /// Whether `temperature` may be sent.
    #[must_use]
    pub fn temperature(mut self, accepted: bool) -> Self {
        self.temperature = Some(accepted);

        self
    }

    /// `schema`, `object` or `none`.
    #[must_use]
    pub fn json(mut self, mode: impl Into<String>) -> Self {
        self.json = Some(mode.into());

        self
    }

    /// Whether the model thinks before answering.
    #[must_use]
    pub fn reasoning(mut self, reasons: bool) -> Self {
        self.reasoning = Some(reasons);

        self
    }

    /// The effort to ask for.
    #[must_use]
    pub fn reasoning_effort(mut self, effort: impl Into<String>) -> Self {
        self.reasoning_effort = Some(effort.into());

        self
    }
}

/// Where the scanner looks for `text()` calls in JavaScript, TypeScript, Vue and Svelte,
/// `texts.scan.scripts` in the PHP package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptScanSettings {
    /// The folders to read, relative to the application's base path. Only these folders are read,
    /// so the bundles Vite writes to `public/build` and `bootstrap/ssr` are never taken for source.
    pub paths: Vec<String>,
    /// The extensions of the files to read.
    pub extensions: Vec<String>,
    /// The names the calls use. Add `t` if your components call it that.
    pub functions: Vec<String>,
}

impl Default for ScriptScanSettings {
    fn default() -> Self {
        Self {
            paths: Vec::new(),
            extensions: ["js", "jsx", "ts", "tsx", "vue", "svelte"].map(str::to_owned).to_vec(),
            functions: ["text", "$text"].map(str::to_owned).to_vec(),
        }
    }
}

/// `texts.scan` in the PHP package.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScanSettings {
    /// JavaScript, TypeScript, Vue and Svelte files.
    pub scripts: ScriptScanSettings,
}

/// The package's configuration, the equivalent of `config/texts.php`.
///
/// The keys and the defaults are the PHP package's, in snake case. The API keys and the OpenAI,
/// Claude and Translatorio models read the same environment variables as there; everything else is
/// set in `src/app.rs` with `with_config`:
///
/// ```ignore
/// use laratext::TextsConfig;
///
/// Application::configure().with_config(|config, _| {
///     let texts = config.section_mut::<TextsConfig>();
///
///     texts.default_translator = "claude".to_owned();
///     texts.context = "A real estate CRM. Address the user formally.".to_owned();
///     texts.scan.scripts.paths = vec!["resources/js".to_owned()];
/// })
/// ```
#[derive(Debug, Clone, Section)]
pub struct TextsConfig {
    /// The translator `laratext:scan` uses when `--translator` is not given: a name from the
    /// translators registered in the provider. `openai`, `claude`, `google` and `translatorio`
    /// ship with the package.
    #[section(default = "openai")]
    pub default_translator: String,

    /// The OpenAI translator.
    #[env(with = openai_from_env)]
    pub openai: OpenAiConfig,

    /// The Claude translator.
    #[env(with = claude_from_env)]
    pub claude: ClaudeConfig,

    /// The Google Translate translator.
    #[env(with = google_from_env)]
    pub google: GoogleConfig,

    /// The Translatorio translator.
    #[env(with = translatorio_from_env)]
    pub translatorio: TranslatorioConfig,

    /// Corrections to what the package knows about OpenAI and Claude models, by name or prefix.
    pub models: IndexMap<String, ModelOverride>,

    /// The languages the texts are translated into: code and readable name.
    #[section(default = default_languages())]
    pub languages: IndexMap<String, String>,

    /// The language the texts in the code are written in. When `None`, the application's default
    /// locale, `locale` in laralocale's `LocaleConfig`, is used.
    pub source_locale: Option<String>,

    /// Sent to the translator with every batch, so it knows what it is translating. Translators
    /// without a prompt, such as Google Translate, ignore it.
    pub context: String,

    /// What the scanner reads besides Rust and template files.
    pub scan: ScanSettings,

    /// The folder holding the `{locale}.json` files, relative to the application's base path.
    ///
    /// Not in the PHP package, where `lang_path()` decides: Laravel Rust has no such helper.
    #[section(default = "lang")]
    pub lang_path: String,
}

fn default_languages() -> IndexMap<String, String> {
    [("en", "English"), ("es", "Spanish"), ("fr", "French")]
        .into_iter()
        .map(|(code, name)| (code.to_owned(), name.to_owned()))
        .collect()
}

fn present(env: &Env, key: &str) -> Option<String> {
    env.get::<String>(key).filter(|value| !value.is_empty())
}

fn openai_from_env(env: &Env) -> Option<OpenAiConfig> {
    let defaults = OpenAiConfig::default();

    Some(OpenAiConfig {
        api_key: present(env, "OPENAI_API_KEY"),
        model: present(env, "OPENAI_MODEL").unwrap_or(defaults.model),
        ..OpenAiConfig::default()
    })
}

fn claude_from_env(env: &Env) -> Option<ClaudeConfig> {
    let defaults = ClaudeConfig::default();

    Some(ClaudeConfig {
        api_key: present(env, "ANTHROPIC_API_KEY"),
        model: present(env, "ANTHROPIC_MODEL").unwrap_or(defaults.model),
        ..ClaudeConfig::default()
    })
}

fn google_from_env(env: &Env) -> Option<GoogleConfig> {
    Some(GoogleConfig {
        api_key: present(env, "GOOGLE_TRANSLATOR_API_KEY"),
        ..GoogleConfig::default()
    })
}

fn translatorio_from_env(env: &Env) -> Option<TranslatorioConfig> {
    let defaults = TranslatorioConfig::default();

    Some(TranslatorioConfig {
        api_key: present(env, "TRANSLATORIO_API_KEY"),
        url: present(env, "TRANSLATORIO_URL").unwrap_or(defaults.url),
        glossary: present(env, "TRANSLATORIO_GLOSSARY"),
        formality: present(env, "TRANSLATORIO_FORMALITY"),
        effort: present(env, "TRANSLATORIO_EFFORT"),
        ..TranslatorioConfig::default()
    })
}