trox 0.2.1

Immutable source-authored localization values and deterministic bundle runtime
Documentation

Trox

Trox is a source-extraction localization system for Rust, TypeScript/TSX, and static RON data. Developers write complete English messages beside their use sites; Trox extracts them, expands locale-specific grammar into flat CSV rows, and builds deterministic bundles for Rust and TypeScript runtimes. Messages remain immutable, locale-independent LocalizedString values until an explicit Localizer renders them at the presentation boundary, avoiding text fragments, translator-authored programs, implicit locale state, and runtime morphology.

Here is a Rust message with interpolation, exact-zero wording, and cardinal plural selection:

use trox::prelude::*;

fn cards_remaining(card_count: u32) -> LocalizedString {
    txa(
        plural(card_count, [
            exact(0, "No cards remain."),
            one("{card_count} card remains."),
            other("{card_count} cards remain."),
        ]),
        tx_args![card_count],
        "Status text showing how many cards remain in the deck.",
    )
}

let value = cards_remaining(3);
let localizer = Localizer::for_source(SourceLocale::new("en-US")?)?;
let text = localizer.resolve(&value);
assert_eq!(text, "\u{2068}3\u{2069} cards remain.");
# Ok::<(), Box<dyn std::error::Error>>(())

Install and start

Trox requires Rust 1.89 or newer. Add the runtime library to an application:

cargo add trox

Create a trox.ron at the project root:

(
    source_locale: "en-US",
    terms: "terms.ron",
    source_bundle: ".trox-output/en-US.trox.json",
    source_report: ".trox-output/en-US.csv",
    sources: [(language: Rust, include: ["src/**/*.rs"])],
    locales: {},
    term_forms: {},
)

Create an empty terms.ron containing {} and ignore the disposable output directory:

/.trox-output/

Construct the development localizer from those two human-authored files. Using include_str! is convenient, but applications may load the bytes however they choose:

use trox::prelude::*;

fn source_localizer() -> Result<Localizer, Box<dyn std::error::Error>> {
    let source = SourceLocale::from_project_ron(
        include_str!("../trox.ron"),
        include_str!("../terms.ron"),
    )?;
    Ok(Localizer::for_source(source)?)
}

cargo check, cargo test, cargo clippy, and cargo run now need only the application source, trox.ron, and terms.ron. Changing a tx or txa call changes the rendered source text on the next build; there is no extraction or bundle-generation step in the Rust build.

Install trox-cli separately only when extracting translator material or building release bundles:

cargo install trox-cli
trox check --deny warnings
trox extract
trox release-check

The package installs a binary named trox. Its Rust modules are implementation details of the executable and are not a supported library API. Add a locale's profile, CSV, and bundle paths to trox.ron, then create its initial files with trox locale init LOCALE. The full configuration contract is documented under Project configuration.

Support policy

  • trox and trox-cli support Rust 1.89 and newer.
  • The Rust runtime is tested on Linux, macOS, and Windows.
  • The trox command is tested on Linux, macOS, and Windows. On non-Unix platforms its optional benchmark reports no peak-memory measurement.
  • The trox library follows Cargo semantic versioning. The trox-cli package exposes only the trox executable; its internal Rust modules are not API.
  • Bundle and serialized-value compatibility is versioned explicitly by their embedded format versions and validated when data is loaded.

Capabilities and boundaries

Trox provides:

  • Inline complete English messages.
  • Named placeholders in Rust and TypeScript.
  • Exact, cardinal, ordinal, and semantic selection.
  • RON message and typed-template extraction.
  • Locale-specific row expansion.
  • Non-destructive CSV synchronization.
  • Deterministic JSON bundles.
  • Compatible Rust and TypeScript runtimes.
  • Canonical serialization of unresolved messages.
  • Visible source fallback with diagnostics.

Trox does not provide:

  • String-fragment composition.
  • Translator-authored selector syntax.
  • A general expression language.
  • Automatic articles, case, or morphology.
  • Arbitrary nested localized messages.
  • Implicit global locale discovery.
  • Runtime filesystem or network access.
  • Currency, date, unit, or list formatting.
  • Interpreted HTML or rich-text markup.

Design rules:

  • Every selector leaf is a complete message.
  • Translation files contain text, not programs.
  • Terms are sparse, shallow, and explicit.
  • Application code owns semantic inputs.
  • Locale profiles own locale-private grammar.
  • Deterministic tooling is authoritative.

Repository

.
├── crates/
│   ├── trox/          Rust API, bundles, wire values, resolver
│   └── trox-cli/      `trox` binary, scanners, CSV workflow, bundle builder
├── packages/
│   └── trox/          `@trox/runtime` TypeScript package
├── crates/trox/tests/fixtures/
│   └── conformance/   canonical cross-language fixtures
├── crates/trox-cli/tests/fixtures/
│   └── quest/         multilingual scenario corpus
├── Cargo.toml         Rust workspace
├── package.json       npm workspace
└── README.md          project documentation

Build and test:

cargo test --workspace
npm install
npm run typecheck
npm test
npm run build

Run the Quest workflow:

cargo run --release -p trox-cli --bin trox -- \
  --config crates/trox-cli/tests/fixtures/quest/trox.ron extract

cargo run --release -p trox-cli --bin trox -- \
  --config crates/trox-cli/tests/fixtures/quest/trox.ron check

cargo run --release -p trox-cli --bin trox -- \
  --config crates/trox-cli/tests/fixtures/quest/trox.ron bundle --allow-missing

Typical application workflow:

  1. Add tx or txa calls to Rust or TypeScript.
  2. Add flat Tx(...) records to configured RON data.
  3. Declare runtime grammatical terms only when needed.
  4. Use Localizer::for_source for normal builds, tests, and local runs.
  5. Configure ignored localization outputs in trox.ron.
  6. Run trox check without requiring any generated output to exist.
  7. Run trox extract in localization automation and hand off its CSV/workbook.
  8. Translate the generated rows outside the application source checkout.
  9. Run trox release-check in localization or packaging automation.
  10. Load the generated source and target bundles in production.
  11. Resolve messages only at the presentation boundary.

Source-development localization

Localizer::for_source deliberately does not look up message entries or rows. It selects directly from the live LocalizedString identity, then applies the source locale's pinned cardinal rules, ordinal rules, decimal formatting, text direction, isolation policy, and term surfaces. Checked and recovering resolution APIs are both available, but ordinary source messages never produce missing-message or missing-row diagnostics.

SourceLocale::new("en-US") is sufficient when the application has no terms. SourceLocale::from_project_ron additionally reads the existing source locale, term-form declarations, source fallback policy, term values, numbered forms, and optional source term facets from human-authored RON. It does not scan Rust, TypeScript, or RON message sources and it does not read the filesystem.

Source mode is for in-process values authored by the application. Canonical wire decoding still requires a generated SourceCatalog because accepting a self-consistent message hash is not an authorization boundary.

Rust syntax

Use the prelude in ordinary authoring modules:

use trox::prelude::*;

It exports:

  • LocalizedString, Localizer, and TermId.
  • tx, txa, meaning, ls, and tx_args!.
  • plural, ordinal, and select.
  • exact, zero, one, two, few, many, and other.
  • when, otherwise, and TroxSelector.
  • term, indefinite, counted, and opaque.

Static text

Use tx when there are no visible placeholders:

fn close_label() -> LocalizedString {
    tx(
        "Close deck browser",
        "Accessible label that closes the deck browser.",
    )
}

The final argument is required translator context. The result is not a host String:

let value: LocalizedString = close_label();
let text: String = localizer.resolve(&value);

Intentionally untranslated text

Use ls when runtime text is intentionally safe to display without translation:

fn player_name(raw_string: &str) -> LocalizedString {
    ls(raw_string)
}

Appropriate uses are:

  • Migrations, while existing text is being moved behind LocalizedString APIs.
  • Raw user input that must be displayed verbatim, such as a player name.
  • Tests that need a lightweight LocalizedString value.
  • Developer-only surfaces whose text is not translated.

Calling ls asserts that this text does not need translation at this call site. Do not use it for ordinary user-facing product copy. The extractor deliberately ignores these calls, and the value resolves to the supplied text in every locale, including text containing braces. Replace migration uses with tx or txa as localization work is completed.

Interpolation

Use txa for visible placeholders:

fn deck_label(deck_name: &str) -> LocalizedString {
    txa(
        "Deck: {deck_name}",
        tx_args![deck_name],
        "Label followed by the user-defined deck name.",
    )
}

Bind multiple values or map a different expression:

fn progress(owned_count: u32, total_count: u32) -> LocalizedString {
    txa(
        "Collection: {owned_count}/{total_count}",
        tx_args![
            owned_count,
            total_count => total_count,
        ],
        "Owned cards followed by total available cards.",
    )
}

tx_args! evaluates each expression once and converts it into an owned Trox value. It borrows ordinary input variables by default.

Placeholder names match:

[a-z][a-z0-9]*(?:_[a-z0-9]+)*

Valid:

{name}
{card_name}
{player_2_name}

Rejected:

{0}
{CardName}
{cardName}
{card.name}
{card-name}
{cárd_name}

Rules:

  • Names use lowercase ASCII snake case.
  • Names are at most 64 ASCII bytes.
  • Every visible placeholder has one binding.
  • Every binding appears in at least one leaf.
  • Target rows may move, repeat, or omit declared placeholders.
  • Target rows cannot invent placeholders.
  • {{ and }} render literal braces.
tx(
    "Write {{card_name}} to show a placeholder.",
    "Help text showing placeholder notation.",
)

Meaning

Disambiguate identical text with a semantic meaning key:

fn open_button() -> LocalizedString {
    tx(
        meaning("open-action", "Open"),
        "Button label that opens the selected deck.",
    )
}

fn open_state() -> LocalizedString {
    tx(
        meaning("open-state", "Open"),
        "Status adjective for a room accepting players.",
    )
}

The meaning key changes message identity. It is not an arbitrary developer message ID. Extraction includes it at the start of the translator-facing description as Meaning: <key>.

Cardinal selection

Use plural for locale-dependent cardinal categories:

fn cards_remaining(card_count: u32) -> LocalizedString {
    txa(
        plural(card_count, [
            exact(0, "No cards remain."),
            one("{card_count} card remains."),
            other("{card_count} cards remain."),
        ]),
        tx_args![card_count],
        "Status text showing cards remaining in the deck.",
    )
}

Selection order:

  1. Exact integer branch.
  2. Target locale's CLDR category.
  3. Matching category branch.
  4. Required other branch.

Extraction adds target-only categories. A Russian CSV can receive one, few, many, and other rows from an English source pattern.

The count need not be visible:

tx(
    plural(card_count, [
        one("A card remains."),
        other("Cards remain."),
    ]),
    "Status indicating whether one or multiple cards remain.",
)

Ordinal selection

fn turn_position(turn_number: u32) -> LocalizedString {
    txa(
        ordinal(turn_number, [
            one("{turn_number}st turn"),
            two("{turn_number}nd turn"),
            few("{turn_number}rd turn"),
            other("{turn_number}th turn"),
        ]),
        tx_args![turn_number],
        "Label for a turn's ordinal position.",
    )
}

Plural and ordinal selectors accept nonnegative integers from zero through 2^53 - 1. Fractions, negative values, NaN, and infinities are invalid.

Semantic selection

Define explicit stable keys:

#[derive(Clone, Copy, PartialEq, Eq)]
enum BattleZone {
    Deck,
    Hand,
    Void,
}

impl TroxSelector for BattleZone {
    fn trox_key(&self) -> &'static str {
        match self {
            Self::Deck => "deck",
            Self::Hand => "hand",
            Self::Void => "void",
        }
    }
}

Select complete messages:

fn search_zone(zone: BattleZone) -> LocalizedString {
    tx(
        select(zone, [
            when(BattleZone::Deck, "Search your deck."),
            when(BattleZone::Hand, "Search your hand."),
            when(BattleZone::Void, "Search your void."),
            otherwise("Search that zone."),
        ]),
        "Rules text directing the player to search a zone.",
    )
}

Rules:

  • otherwise is mandatory.
  • Keys are stable serialization contracts.
  • Keys are unique within the selector.
  • Keys use one uniform string or boolean type.
  • Generic select is not a numeric plural operation.
  • Ordinary application branching stays in ordinary control flow.

Nested selectors are supported. Every final leaf must still contain the full sentence, including articles, verbs, and punctuation.

Terms and atoms

Map domain values to explicit term IDs:

impl CardSubtype {
    fn term_id(self) -> TermId {
        match self {
            Self::Warrior => TermId::new("card-subtype.warrior"),
            Self::Relic => TermId::new("card-subtype.relic"),
            Self::Event => TermId::new("card-subtype.event"),
        }
    }
}

Request an indefinite form:

txa(
    "Change {card_name} to become {subtype}.",
    tx_args![
        card_name => opaque(card_name),
        subtype => indefinite(subtype.term_id()),
    ],
    "Card transformation with an indefinite subtype.",
)

indefinite(id) is shorthand for:

term(id).form("indefinite")

It does not generate a versus an from spelling.

Request a counted form:

txa(
    "Create {creature_count} {creature_noun}.",
    tx_args![
        creature_count,
        creature_noun => counted(
            subtype.term_id(),
            creature_count,
        ),
    ],
    "Creation rule with a runtime-selected counted noun.",
)

counted(id, number) is shorthand for:

term(id).form("counted").number(number)

The count selects the term surface. The separate placeholder renders the number.

Keep fixed vocabulary inline:

txa(
    plural(card_count, [
        one("Draw {card_count} card."),
        other("Draw {card_count} cards."),
    ]),
    tx_args![card_count],
    "Rules text instructing the player to draw cards.",
)

Create a term only when a runtime-selected concept needs a form, count, locale facet, or deliberately centralized proper name.

opaque(value) inserts an atomic localized value. The nested value must be one text leaf with no arguments or selectors. If it needs grammatical interaction, model it as a term.

Application-annotated placeholders

Trox translations remain plain text. Translators cannot author HTML, Markdown, component syntax, or other interpreted rich-text markup. Applications can, however, attach opaque metadata to a message's existing named placeholders and use that metadata at the final presentation boundary. This is structured placeholder resolution, not rich-text parsing.

In Rust, annotate a still-lazy LocalizedString without a Localizer:

use trox::prelude::*;

#[derive(Debug)]
struct EntityAnnotation {
    entity_id: String,
}

let message = txa(
    "Gain {offered_card}.",
    tx_args![offered_card => opaque(card_name)],
    "An effect granting the displayed card.",
);
let annotated = message.annotate([(
    "offered_card",
    EntityAnnotation { entity_id: "card-7".into() },
)])?;

let parts = localizer.resolve_parts_checked(&annotated)?;

Rust's annotate consumes the cheap-to-clone LocalizedString and accepts any IntoIterator of (name, metadata) pairs, including arrays, Vec, and owned BTreeMap values. Duplicate names are rejected instead of being silently overwritten.

ResolvedLocalizedPart::Literal contains translator-authored literal runs. ResolvedLocalizedPart::Placeholder contains the semantic placeholder name, its display-ready localized surface, and Option<&EntityAnnotation>.

The TypeScript lifecycle is equivalent:

const message = txa(
  "Gain {offered_card}.",
  { offered_card: opaque(cardName) },
  "An effect granting the displayed card.",
);
const annotated = message.annotate({
  offered_card: { kind: "entity", entityId: "card-7" },
});

const parts = localizer.resolvePartsChecked(annotated);

Construction, annotation, view-model storage, and application-layer transport remain locale independent. Only resolve_parts_checked / resolvePartsChecked and their recovering counterparts require the active Localizer. A target row may reorder, repeat, or omit declared placeholders: the part sequence follows that target row exactly, repeated occurrences reference the same annotation, and omitted occurrences produce no part. Other placeholders resolve normally with no annotation.

Placeholder value fields are display-ready and include FSI/PDI controls when the bundle enables bidirectional isolation. Concatenating every part's value is therefore exactly equal to resolve_checked / resolveChecked (and likewise for recovering resolution). Scalar text, formatted numbers, terms, and opaque nested localized values use the same formatting and recovery path as ordinary string resolution.

Annotations are application data, not localization data. The Rust wrapper owns its metadata and resolved parts borrow it; the TypeScript wrapper retains the application values by reference in a shallow-frozen name map. Neither wrapper implements Trox canonical serialization, and TypeScript JSON.stringify rejects it explicitly. To cross a process or persistence boundary, serialize the underlying LocalizedString through its existing canonical wire format and serialize application metadata through an application-owned protocol, then validate the names again by calling .annotate(...) on the decoded LocalizedString. Unknown annotation names fail immediately with trox.unknown-annotation.

Resolution and rejected forms

let text = localizer.resolve(&value);
let checked = localizer.resolve_checked(&value)?;
let json = value.to_canonical_json()?;
let decoded = localizer.localized_string_from_json(&json)?;

Decoding validates IDs, schemas, selectors, numeric ranges, terms, and limits. Patterns, branches, arguments, and descriptions must stay inline. Dynamic patterns, concatenation, missing descriptions, numeric select, concat!, and arbitrary localized nesting are rejected.

TypeScript syntax

import {
  Localizer,
  counted,
  exact,
  few,
  indefinite,
  assertLocalized,
  one,
  opaque,
  ordinal,
  other,
  otherwise,
  plural,
  select,
  termId,
  two,
  tx,
  txa,
  when,
  type LocalizedString,
  type TermId,
} from "@trox/runtime";

Static and interpolated messages mirror Rust:

export function closeLabel(): LocalizedString {
  return tx(
    "Close deck browser",
    "Accessible label that closes the deck browser.",
  );
}

export function deckLabel(deck_name: string): LocalizedString {
  return txa(
    "Deck: {deck_name}",
    { deck_name },
    "Label followed by the user-defined deck name.",
  );
}

Use assertLocalized(rawString) for migrations, verbatim user input, tests, and developer-only surfaces. It returns a LocalizedString that resolves to rawString in every locale and is deliberately not extracted:

export function playerName(rawString: string): LocalizedString {
  return assertLocalized(rawString);
}

Calling it asserts that the text does not need translation at that call site; do not use it for ordinary user-facing product copy. Replace migration uses with tx or txa as localization work is completed.

The argument object must be inline. Spreads and prebuilt objects are not extractable.

Cardinal and ordinal selection:

export function cardsRemaining(
  card_count: number,
): LocalizedString {
  return txa(
    plural(card_count, [
      exact(0, "No cards remain."),
      one("{card_count} card remains."),
      other("{card_count} cards remain."),
    ]),
    { card_count },
    "Status text showing cards remaining in the deck.",
  );
}

export function turnPosition(
  turn_number: number,
): LocalizedString {
  return txa(
    ordinal(turn_number, [
      one("{turn_number}st turn"),
      two("{turn_number}nd turn"),
      few("{turn_number}rd turn"),
      other("{turn_number}th turn"),
    ]),
    { turn_number },
    "Label for a turn's ordinal position.",
  );
}

Semantic selection uses finite literal unions:

type BattleZone = "deck" | "hand" | "void";

export function searchZone(zone: BattleZone): LocalizedString {
  return tx(
    select(zone, [
      when("deck", "Search your deck."),
      when("hand", "Search your hand."),
      when("void", "Search your void."),
      otherwise("Search that zone."),
    ]),
    "Rules text directing the player to search a zone.",
  );
}

Map application values to explicit TermId values, then use indefinite, counted, or opaque exactly as in Rust. Resolve and serialize explicitly:

const text: string = localizer.resolve(value);
const json: string = value.toCanonicalJSON();
const decoded = localizer.localizedStringFromJSON(json);

LocalizedString is not assignable to string. Host interpolation, prebuilt or spread argument objects, and dynamic descriptions are rejected. Single and double quotes and template literals without interpolation are accepted. The scanner handles .ts and .tsx without module resolution.

RON source extraction

RON supports flat static messages and text templates with explicitly typed placeholders:

(
    internal_id: "close-deck-browser",
    label: Tx("Close deck browser"),
    accessibility_label: Tx(
        text: "Close deck browser",
        description: "Accessible label that closes the browser.",
    ),
    open_state: Tx(
        text: "Open",
        meaning: "open-state",
        description: "Status for a room accepting players.",
    ),
    deck_summary: Tx(
        text: "Deck: {deck_name} ({count})",
        description: "Deck label followed by its card count.",
        placeholders: {
            "deck_name": Opaque,
            "count": Scalar,
        },
    ),
)

Rules:

  • Only Tx records are extracted.
  • Use the short Tx("text") form for plain static text.
  • Use the named form when supplying description or meaning; text is required.
  • description, meaning, and placeholders are optional named fields.
  • Every placeholder in text must have exactly one declaration. Use Scalar for text, finite numbers, or booleans; Opaque for an atomic localized value; and Term(form: "counted", number: true) for a term with an exact form and number-presence contract.
  • Generated descriptions include the structural RON field path, such as Path: CardDefinition.ability_text. Array indexes are omitted so every value in the same field shares a stable path.
  • Unwrapped strings are ignored.
  • Selectors are rejected. RON templates are text patterns only.
  • Runtime argument values are not embedded in RON; only their schemas are declared.
  • {{ and }} render visible braces.

Rejected by source extraction:

(
    ignored: "Close deck browser",
    undeclared: Tx(text: "Deck: {deck_name}"),
    extra: Tx(text: "Deck", placeholders: { "deck_name": Opaque }),
)

Configure description defaults for authored data:

ron_description_defaults: {
    "data/cards.ron": "Rules text for a game card.",
    "data/**/*.ron": "Player-authored game data label.",
},

An explicit description overrides a matching path default. The structural RON field path is appended to either description; when neither is present, the path itself supplies the description.

Serde round-tripping

Application-owned Rust types may contain LocalizedString fields and derive Serde normally:

#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Record {
    label: LocalizedString,
}

let record = Record {
    label: tx("Foo", "Example label."),
};
let encoded = ron::to_string(&record)?;
assert_eq!(encoded, r#"(label:Tx("Foo"))"#);

let decoded: Record = ron::from_str(&encoded)?;
assert_eq!(decoded, record);

This application-data representation uses the same Tx forms as source extraction. A value without a meaning serializes as Tx("Foo"); a value with a meaning uses the named form Tx(text: "Open", meaning: "open-state") so the meaning survives the round trip. Selectors and already-bound dynamic values return a RON serialization error.

A placeholder-bearing Tx deserializes as an unbound template. Bind its runtime values before canonical serialization or localization:

let template: LocalizedString = ron::from_str(
    r#"Tx(
        text: "Deck: {deck_name} ({count})",
        placeholders: { "deck_name": Opaque, "count": Scalar },
    )"#,
)?;
let value = template.bind_ron_template(tx_args![
    deck_name => opaque(tx("Night Garden", "Deck name.")),
    count => 40_u32,
])?;
let rendered = localizer.resolve_checked(&value)?;

Transporting RON messages without text lowering

Use a SourceMessageRef when application data must cross a Rust-to-TypeScript boundary before runtime arguments are available. The reference contains only stable entry, identity, and contract signatures. It contains neither English source text nor runtime argument values.

let template: LocalizedString = ron::from_str(
    r#"Tx(text: "Erode {count}", placeholders: { "count": Scalar })"#,
)?;
let source_ref = template.source_message_ref()?;
let json = source_ref.to_canonical_json()?;

Authorize the parsed reference with the deployed source bundle, then bind its exact typed argument contract:

const message = sourceCatalog.sourceMessageFromJSON(json);
const localized = message.bind({ count: 3 });
const rendered = localizer.resolve(localized);

sourceMessageFromValue accepts an already-parsed JSON value. A SourceMessage exposes an immutable argumentSchemas record and rejects missing, extra, wrong-kind, unauthorized term-form, and non-atomic opaque bindings. Static references bind with an empty record. Rust provides the same catalog authorization and SourceMessage::bind contract.

The bound argument names and kinds must exactly match their declarations. Term bindings must also match the declared form and whether a number is present.

Descriptions do not round-trip through LocalizedString. They are authoring metadata and are not retained in the runtime value or message identity. For example, Tx(text: "Foo", description: "Example label.") can be read, but serializing the resulting value produces Tx("Foo").

Term catalog

terms.ron is one top-level map:

{
    "card-subtype.warrior": (
        description: "The Warrior card subtype.",
        value: "Warrior",
        forms: {
            "indefinite": "a Warrior",
            "counted": Number([
                One("Warrior"),
                Other("Warriors"),
            ]),
        },
    ),
}

Rules:

  • A term has one stable ID and default value.
  • Named forms are declared by project configuration.
  • Numbered forms contain CLDR cardinal surfaces.
  • Terms do not reference terms or messages.
  • Source calls authorize exact form and number contracts.
  • Fixed vocabulary stays in complete messages.

Project configuration

Minimal complete trox.ron:

(
    source_locale: "en-US",
    terms: "terms.ron",
    source_bundle: ".trox-output/bundles/en-US.trox.json",
    source_report: ".trox-output/reports/en-US.csv",

    sources: [
        (
            language: Rust,
            include: ["src/**/*.rs"],
            exclude: [],
        ),
        (
            language: TypeScript,
            include: ["web/**/*.ts", "web/**/*.tsx"],
            exclude: [],
        ),
        (
            language: Ron,
            include: ["data/**/*.ron"],
            exclude: [],
        ),
    ],

    locales: {
        "es": (
            profile: "locales/es.ron",
            csv: ".trox-output/reports/es.csv",
            bundle: ".trox-output/bundles/es.trox.json",
        ),
    },

    max_expanded_rows_per_entry: 256,

    term_forms: {
        "counted": (
            description: "Term inflected for a cardinal count.",
            number: Required,
        ),
        "indefinite": (
            description: "Nonspecific singular noun phrase.",
            source_fallback: Default,
        ),
    },

    ron_description_defaults: {
        "data/**/*.ron": "Player-authored game data label.",
    },
)

The CLI discovers the nearest parent trox.ron. Select another complete configuration with:

trox --config path/to/trox.ron check

Locale profiles

Spanish example:

(
    locale: "es",
    direction: Ltr,
    isolation: Isolate,
    fallbacks: ["en-US"],

    facets: {
        "gender": (
            scope: Message,
            values: ["masculine", "feminine"],
        ),
    },

    term_facets: {
        "card-subtype.warrior": {
            "gender": "masculine",
        },
        "card-subtype.relic": {
            "gender": "feminine",
        },
    },
)

Profiles own:

  • Locale identifier and fallback chain.
  • Left-to-right or right-to-left direction.
  • Placeholder isolation behavior.
  • Locale-private facet IDs and values.
  • Term classification under those facets.

Message-scoped facets expand containing messages into rows. Term-scoped facets remain term context. Application code passes stable term IDs, not Spanish gender or other locale-private metadata.

Trox does not guess grammar from spelling, person names, or machine translation. Pass explicit semantic values when agreement requires them.

Extraction and CSV

Commands:

# Validate without writes.
trox check
trox check --deny warnings
trox --json check

# Synchronize every locale or one locale.
trox extract
trox extract --locale ru

# Scaffold a locale.
trox locale init pl

# Build strict or development bundles.
trox bundle
trox bundle --locale es
trox bundle --allow-missing

# Extract, generate, and validate all production artifacts in one release job.
trox release-check
trox release-check --allow-missing

# Remove reviewed obsolete rows.
trox prune --locale es

# Create and merge a curated translator workbook.
trox handoff export --locale es --output localization/handoff/es.xlsx
trox handoff import --locale es --input localization/handoff/es.xlsx

Extraction is transactional:

  • It validates every requested output before replacement.
  • Any failure leaves all requested outputs unchanged.
  • Successful replacements are atomic.
  • Repeated extraction without changes is byte-identical.
  • Parallel scanning does not change output order.
  • Message rows follow source path, then numeric line and column. When the same message appears more than once, its earliest occurrence determines its position.

trox check always validates source code, terms, locale profiles, expansion, and lint policy. When a configured CSV exists it validates that managed state too; a missing generated CSV or JSON bundle is not an error. trox extract creates catalogs from scratch, and trox release-check performs extraction followed by production bundle generation and validation. Keep its configured destinations in an ignored output directory and publish them from localization or packaging automation instead of committing them.

Extraction preserves:

  • Existing translations.
  • Translator notes.
  • Unknown workflow columns.
  • Previous translations for changed rows.
  • Removed rows as obsolete records in target-locale CSVs.

Row state:

  • New untranslated rows are missing.
  • Translator-relevant source changes make rows stale.
  • Removed source or expansion rows become obsolete in target-locale CSVs.
  • Obsolete rows are removed automatically from the English source report; target CSVs retain them until explicit pruning.

Representative translator-facing CSV columns (managed metadata follows):

english,description,translation
{count} card,"Card count label.\n\nConditions: count.plural=one",
{count} cards,"Card count label.\n\nConditions: count.plural=other",

Managed IDs are tool-owned. Selector conditions are included in the description so translators can read all source context in one column; translators edit surface text and notes, not selectors.

For an external translator, use trox handoff export instead of sending the canonical CSV. The .xlsx handoff contains active rows only; obsolete rows and unknown workflow columns remain in the canonical CSV as translation memory. Only the Translation and Translator note columns are editable. Managed metadata is hidden and protected, and every cell is written as spreadsheet text so source strings beginning with =, +, -, or @ cannot become formulas.

trox handoff import rejects formulas, added or removed rows and columns, modified IDs, source metadata, or placeholder declarations, a changed source catalog, and canonical CSV edits made after export. Imported translations also run the project's normal placeholder and localization lint policy. A hidden manifest binds the workbook to the locale, source locale, active row set, and catalog fingerprint. Worksheet protection is for editing guidance; import validation is the integrity boundary.

Condition examples:

card_count.exact=0
card_count.plural=few
turn_number.ordinal=other
zone.select=deck
subtype.gender=feminine

An exact translation cell containing ^ inherits the resolved translation from the immediately preceding active row of the same entry:

description,translation
"Conditions: subtype.gender=masculine",Crear {count} Guerrero.
"Conditions: subtype.gender=feminine",^

Caret rules:

  • ^ cannot cross an entry boundary.
  • Blank cells remain missing.
  • Consecutive carets resolve through prior active rows.
  • Bundles materialize inherited text.
  • Extraction protects meaning when adjacency changes.

Rows become stale when text, description, selector context, argument schema, term-form request, or locale expansion changes. The old translation is kept in previous_translation.

Run extraction before pruning. prune rejects a CSV that no longer matches the current catalog, so a row that became active again is not deleted.

Lint policy

lint: (
    default_warning: Warn,
    rules: {
        "trox.unchanged-translation": (
            level: Deny,
        ),
        "trox.human-row-expansion": (
            level: Allow,
            reason: "Reviewed translator cost in issue 123.",
        ),
    },
),

Rules:

  • Warn reports a warning.
  • Deny promotes a warning to an error.
  • Allow requires a nonempty review reason.
  • Reasons on Warn or Deny are invalid.
  • Expansion above 32 rows requires reasoned suppression.
  • The configured row limit remains a hard cap.

One-run overrides:

trox --lint trox.unchanged-translation=deny check

trox --allow \
  'trox.human-row-expansion=Reviewed translator cost in issue 123.' \
  check

JSON diagnostics include a stable rule ID, severity, path, source span when known, explanation, and suggested correction. trox.internal means an implementation failure, not an ordinary authoring error.

Bundles and runtime

Production bundle operations emit:

  • The configured source bundle.
  • Every selected target bundle.

Deploy one source bundle and one active target bundle:

source bundle ─┐
               ├─> Localizer ─> resolve(LocalizedString) ─> String
target bundle ─┘

Applications retain ownership of filesystem, asset, or network I/O:

let source_json = load_asset("locales/en-US.trox.json")?;
let target_json = load_asset("locales/es.trox.json")?;
let source = trox::Bundle::from_canonical_json(&source_json)?;
let target = trox::Bundle::from_canonical_json(&target_json)?;
let localizer = trox::Localizer::new_strict(target, source)?;
# Ok::<(), Box<dyn std::error::Error>>(())
# fn load_asset(_: &str) -> Result<String, std::io::Error> { unreachable!() }

Localizer::new retains entry-level compatible fallback during a catalog mismatch; Localizer::new_strict rejects the mismatch. Replace the explicit Localizer value to change the active runtime locale. Trox performs no implicit locale discovery and holds no global locale state.

Bundles are canonical JSON containing:

  • Explicit format version.
  • Pinned locale-data version.
  • Source-catalog fingerprint.
  • Canonical entry and row IDs.
  • Target plural and ordinal behavior.
  • Direction and isolation settings.
  • Validated term forms and facet metadata.

The source bundle authorizes message identities, full signatures, visible argument schemas, terms, and forms. Version 1.1 bundles also carry a contract signature derived from the identity and argument schemas. Target bundles contain translated rows and compatibility data.

Loading rejects unknown major versions, unsupported features, noncanonical JSON, duplicate IDs, irreproducible IDs, invalid paths, and invalid signatures.

A catalog mismatch can preserve entry-level compatibility in normal mode. Version 1.1 entries require matching contract signatures; version 1.0 entries use their stable source signatures. Incompatible entries use source fallback. Strict construction rejects any catalog-fingerprint mismatch.

Runtime responsibilities:

  • Resolve selectors with target locale rules.
  • Format numeric placeholders as locale decimals.
  • Resolve terms and message-scoped facets.
  • Apply configured directional isolation.
  • Reorder, repeat, or omit declared placeholders.
  • Emit diagnostics with visible source fallback.

Application responsibilities:

  • Load bundle bytes.
  • Choose the active target locale.
  • Construct and distribute the Localizer.
  • Keep LocalizedString unresolved in non-presentation layers.
  • Use checked resolution for tests and validation.

The runtime does not read files, fetch resources, discover locale state, mutate globals, parse CSV, run extraction, or evaluate translator-authored code.

Identity and compatibility

Entry IDs hash canonical JSON containing the identity version, meaning key, pattern structure, source leaves, and branch order. Descriptions, locations, runtime values, dynamic term IDs, and host predicates do not define identity.

Descriptions and argument contracts still affect source revision or signature, so their changes can stale translations without changing the entry ID.

Stable IDs are at most 96 ASCII bytes and match:

[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*

Numeric branches use exact values in ascending order, followed by zero, one, two, few, many, and other. Generic select keeps authored order and puts otherwise last.

Validation and conformance

trox check validates:

  • Configuration and source globs.
  • Rust, TypeScript, TSX, and RON syntax.
  • Terms and named forms.
  • Locale profiles and term classifications.
  • Existing managed CSV state when present; generated artifacts are optional.
  • Placeholders and selector branches.
  • Target row expansion.
  • Lint policy and reasons.

Runtime loading validates:

  • Bundle and wire versions.
  • Canonical encoding.
  • Catalog fingerprints.
  • Entry signatures and argument schemas.
  • Selector values and paths.
  • Term authorization.
  • Expansion row IDs.

Shared fixtures cover static and dynamic identities, canonical wire bytes, source-message references, argument authorization, nested selectors, lookup, legacy version upgrades, and fallback.

Before changing identity, bundle, or wire behavior, run:

cargo test --workspace
npm run typecheck
npm test

trox --config crates/trox-cli/tests/fixtures/quest/trox.ron extract
trox --config crates/trox-cli/tests/fixtures/quest/trox.ron check
trox --config crates/trox-cli/tests/fixtures/quest/trox.ron bundle --allow-missing

Confirm that a second extraction is byte-identical. The benchmark uses 100 MiB of equal Rust, TypeScript, TSX, and RON source with 10,000 calls:

trox benchmark \
  --synthetic-mib 100 \
  --iterations 5

Gates are warm startup below 50 ms, throughput of at least 200 MiB/s, peak RSS below twice the source size, and an optional 15 percent median regression cap.

Terminology

  • Argument: runtime value bound to a visible placeholder.
  • Atomic localized value: text leaf with no arguments or selectors, inserted explicitly through opaque.
  • Bundle: deterministic runtime JSON for source or target locale data.
  • Cardinal: quantity category selected by plural.
  • Caret inheritance: CSV ^ shorthand for the preceding active row.
  • Catalog fingerprint: digest pairing compatible source and target bundles.
  • Condition: read-only CSV label for one selector or facet choice.
  • Description: translator context attached to a message or term.
  • Entry: one extracted message family or term-form family.
  • Entry ID: content-derived versioned message identifier.
  • Exact branch: numeric branch checked before a CLDR category.
  • Facet: locale-owned term metadata such as grammatical gender.
  • Fallback: visible source text used when target data is unusable.
  • Form: declared semantic term surface such as indefinite.
  • Identity descriptor: canonical structure hashed into an entry ID.
  • Locale profile: direction, isolation, fallback, and facet configuration.
  • LocalizedString: immutable unresolved message value.
  • Localizer: resolver built from one source and one target bundle.
  • Meaning key: discriminator for identical text with different semantics.
  • NFC: required Unicode Normalization Form C.
  • Opaque: assertion that a localized value is grammatically atomic.
  • Ordinal: position category selected by ordinal.
  • Pattern: text leaf or finite selector tree of complete leaves.
  • Placeholder: named insertion point such as {card_name}.
  • RON: Rusty Object Notation used for checked static data.
  • Row: one translation unit after locale-specific expansion.
  • Scalar: visible text, finite number, or boolean argument.
  • Select: finite semantic branch using a stable application value.
  • Selector: plural, ordinal, or semantic pattern node.
  • Source catalog: runtime authority for identities and argument contracts.
  • Source report: source-locale CSV describing extracted rows.
  • Source revision: translator context that may stale a row.
  • Source signature: digest proving exact source compatibility.
  • Stale row: active row whose source context changed.
  • Term: stable lexical concept used for runtime grammar.
  • Translation row: flat CSV record containing one editable pattern.
  • Wire value: canonical serialized LocalizedString.