translomatic
v2.0.0
Published
Official SDK for the Translomatic Translation API — translate text, detect languages, and stream translations with a single API key.
Downloads
828
Maintainers
Readme
Translomatic SDK
Official JavaScript/TypeScript SDK for the Translomatic Translation API.
Zero dependencies. Works in Node.js 18+, Deno, Bun, and modern browsers.
Install
npm install translomaticQuick Start
import { Translomatic } from "translomatic";
const t = new Translomatic({ apiKey: "tr_live_YOUR_API_KEY" });
// Translate text
const result = await t.translate({
text: "Hello, world!",
targetLang: "ja",
});
console.log(result.translation); // "こんにちは、世界!"
// Batch translate
const batch = await t.translateBatch({
texts: ["Hello", "Goodbye", "Thank you"],
targetLang: "fr",
});
console.log(batch.translations); // ["Bonjour", "Au revoir", "Merci"]
// Detect language
const detected = await t.detect("Bonjour le monde");
console.log(detected.primary); // "fr"
// Stream long texts paragraph-by-paragraph
for await (const chunk of t.translateStream({
text: longArticle,
targetLang: "es",
})) {
process.stdout.write(chunk.text + chunk.separator);
}
// Check usage
const usage = await t.usage();
console.log(`${usage.characters.remaining} characters remaining`);Placeholder Protection
Protect i18n placeholders like {{variable}}, {name}, %s from being translated:
// Option 1: Use built-in patterns
const t = new Translomatic({
apiKey: "tr_live_...",
defaultPreservePatterns: [Translomatic.PLACEHOLDER_PATTERNS.MUSTACHE],
});
await t.translate({
text: "Còn {{seconds}} giây",
targetLang: "en",
});
// → "{{seconds}} seconds remaining" ✅ (not "{{giây}} seconds")
// Option 2: Custom regex per-request
await t.translate({
text: "Hello {name}, you have {count} items",
targetLang: "ja",
preservePatterns: [/\{[a-zA-Z_]\w*\}/g],
});
// → "こんにちは {name}、{count} 個のアイテムがあります" ✅Built-in patterns (Translomatic.PLACEHOLDER_PATTERNS):
| Pattern | Matches | Example |
|---------|---------|---------|
| MUSTACHE | {{...}} | {{count}}, {{user.name}} |
| ICU | {name} | {count}, {username} |
| PRINTF | %s, %d, %f | %s items, %d files |
| I18NEXT | $t(key) | $t(common.hello) |
| HTML | <tag>, </tag> | <b>bold</b> |
Brand Name Protection
Prevent brand names and proper nouns from being translated:
const t = new Translomatic({
apiKey: "tr_live_...",
defaultDoNotTranslate: ["GitHub", "VNPay", "MoMo", "StoreWebview"],
});
await t.translate({
text: "Download from GitHub or pay with VNPay",
targetLang: "vi",
});
// → "Tải xuống từ GitHub hoặc thanh toán bằng VNPay" ✅
// Per-request override
await t.translate({
text: "Sign in with OAuth",
targetLang: "ja",
doNotTranslate: ["OAuth", "SSO"],
});
// → "OAuth でサインイン" ✅Works with all models (not just TransloAI). Terms are protected by replacing them with tokens before translation and restoring after.
Batch Progress Callback
Track real-time progress when translating multiple texts:
const result = await t.translateBatch({
texts: fiftyTexts,
targetLang: "vi",
onProgress: ({ completed, total, percent }) => {
progressBar.update(percent);
console.log(`${completed}/${total} texts translated`);
},
});When onProgress is provided, texts are translated individually with
concurrency (5 parallel) instead of a single batch request.
Without onProgress, uses the efficient single batch API call.
Translate i18n Objects
Translate entire i18n locale files with a single call:
const en = {
common: { greeting: "Hello", farewell: "Goodbye" },
auth: { login: "Sign In", logout: "Sign Out" },
product: { price: "Price: {{amount}}", free: "Free" },
};
const result = await client.translateI18nObject({
object: en,
targetLang: "ja",
preservePatterns: [/\{\{.*?\}\}/g],
doNotTranslate: ["OAuth"],
onProgress: ({ completed, total, percent }) => {
console.log(`${percent}% complete`);
},
});
console.log(result.translated);
// {
// common: { greeting: "こんにちは", farewell: "さようなら" },
// auth: { login: "サインイン", logout: "サインアウト" },
// product: { price: "価格:{{amount}}", free: "無料" },
// }
console.log(result.stats);
// { total: 5, translated: 5, unchanged: 0, failed: 0, skipped: 0 }
console.log(result.warnings);
// [] (or ["common.free: translation_unchanged"] if any failed)Streaming per-key progress
For real-time per-key updates (e.g. CMS live preview):
for await (const chunk of client.translateI18nObjectStream({
object: enLocale,
targetLang: "ja",
})) {
console.log(`[${chunk.index + 1}/${chunk.total}] ${chunk.key} → ${chunk.translation}`);
// [1/520] common.greeting → こんにちは
// [2/520] common.farewell → さようなら
// ...
}Uses small batches (10 texts/request) for frequent progress updates.
Context-Aware Translation
By default, short UI strings like "Free" or "Home" may be translated literally ("Tự do", "Nhà") instead of contextually ("Miễn phí", "Trang chủ"). Use context and glossary to fix this.
Option A: Auto-Analyze (Recommended)
Let the AI read your website's content and auto-generate context + glossary:
const client = new Translomatic({ apiKey: "tr_live_..." });
// 1. Send sample texts from your website
const analysis = await client.analyzeContext({
texts: ["Free", "Home", "Download", "Settings", "App Store",
"Music & Audio", "Sign In", "Top Charts", "New Releases"],
targetLangs: ["vi", "ja", "ko"],
});
// 2. AI auto-detects: "This is a mobile app store..."
console.log(analysis.domain); // "mobile app store"
console.log(analysis.context); // Full context description
// 3. Get glossary for Vietnamese
const viGlossary = Translomatic.getGlossary(analysis, "vi");
// → { "Free": "Miễn phí", "Home": "Trang chủ", "Download": "Tải xuống" }
// 4. Create context-aware client
const smartClient = new Translomatic({
apiKey: "tr_live_...",
defaultModel: analysis.recommendedModel,
defaultContext: analysis.context,
defaultGlossary: viGlossary,
});
// 5. All translations now use the context automatically
const result = await smartClient.translate({
text: "Free Download",
targetLang: "vi",
});
// → "Miễn phí Tải xuống" ✅Option B: Manual Context
Set context and glossary manually in the constructor:
const client = new Translomatic({
apiKey: "tr_live_...",
defaultModel: "transloai-pro", // AI model for context-awareness
defaultContext: `This is a mobile app store website.
"Free" means free-of-charge, not freedom.
"Home" means homepage, not house.
Use natural software UI language.`,
defaultGlossary: {
"Free": "Miễn phí",
"Home": "Trang chủ",
"Settings": "Cài đặt",
"Download": "Tải xuống",
},
});How It Works
| Feature | Description |
|---------|-------------|
| defaultModel | Use "transloai-pro" for AI-powered context-aware translation |
| defaultContext | Domain description the AI reads before translating |
| defaultGlossary | Forced term mappings (AI must use these exact translations) |
| analyzeContext() | AI auto-generates context + glossary from sample texts |
Context and glossary require a TransloAI model (transloai-*).
Per-request params override constructor defaults. Glossaries are merged
(per-request entries win over defaults).
Choose a Model
List available models and pick the best one for your use case:
const { models, tiers } = await t.models();
for (const m of models) {
console.log(`${m.id} — ${m.quality} quality, ${m.speed} speed, ${m.supportedLanguages} langs`);
if (m.contextAware) console.log(" ✓ Supports context + glossary");
}Available Models:
| Model | Family | Speed | Quality | Languages | Context & Glossary |
|-------|--------|-------|---------|-----------|-------------------|
| transloflash-lite | TransloFlash | Fastest | Good | 144 | No |
| transloflash | TransloFlash | Fast | High | 144 | No |
| translomax | TransloMax | Moderate | Very High | 144 | No |
| transloai-nano | TransloAI | Fast | Good | 452 | Yes |
| transloai-lite | TransloAI | Fast | High | 452 | Yes |
| transloai-base | TransloAI | Moderate | Very High | 452 | Yes |
| transloai-pro | TransloAI | Moderate | Excellent | 452 | Yes |
| transloai-ultra | TransloAI | Slow | Best | 452 | Yes |
Use a specific model per-request or set a default:
// Per-request model
const result = await t.translate({
text: "Hello",
targetLang: "vi",
model: "transloai-pro", // Use AI model for this request
});
// Default model for all requests
const client = new Translomatic({
apiKey: "tr_live_...",
defaultModel: "transloai-pro",
});API Reference
new Translomatic(options)
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | required | Your API key (tr_live_...) |
| baseUrl | string | https://api.translomatic.com | API base URL |
| timeout | number | 120000 | Request timeout (ms) |
| maxRetries | number | 3 | Auto-retries on 429/5xx |
| defaultModel | string | — | Default model for all requests |
| defaultContext | string | — | Default context for AI translation |
| defaultGlossary | Record<string, string> | — | Default glossary for all requests |
| defaultPreservePatterns | RegExp[] | [] | Patterns to protect from translation |
| defaultDoNotTranslate | string[] | [] | Terms to never translate (brand names) |
Methods
| Method | Description |
|--------|-------------|
| translate(params) | Translate a single text |
| translateBatch(params) | Translate up to 50 texts (with optional progress) |
| translateStream(params) | Stream translation via SSE |
| translateFile(params) | Translate a file (txt, docx, pdf, etc.) |
| translateI18nObject(params) | Translate an entire i18n JSON object |
| translateI18nObjectStream(params) | Stream-translate i18n object per-key |
| analyzeContext(params) | Auto-analyze texts to generate context + glossary |
| models() | List all available translation models |
| detect(text) | Detect language |
| languages() | List 450+ supported languages |
| usage() | Check quota and usage |
translate(params) / translateBatch(params)
| Param | Type | Description |
|-------|------|-------------|
| text / texts | string / string[] | Text(s) to translate |
| targetLang | string | Target language code |
| sourceLang | string | Source language (auto-detected if omitted) |
| model | string | Model ID (overrides default) |
| context | string | Translation context (AI models only) |
| glossary | Record<string, string> | Term glossary (AI models only) |
| preservePatterns | RegExp[] | Regex patterns to protect |
| doNotTranslate | string[] | Terms to keep untranslated |
| onProgress | (progress) => void | Progress callback (batch only) |
translateI18nObject(params)
| Param | Type | Description |
|-------|------|-------------|
| object | Record<string, any> | Nested i18n JSON object |
| targetLang | string | Target language code |
| sourceLang | string | Source language (auto-detected if omitted) |
| model | string | Model ID |
| context | string | Translation context (AI models only) |
| glossary | Record<string, string> | Term glossary (AI models only) |
| preservePatterns | RegExp[] | Regex patterns to protect |
| doNotTranslate | string[] | Terms to keep untranslated |
| onProgress | (progress) => void | Progress callback (per batch of 50) |
Returns I18nTranslateResult with translated (object), stats,
warnings[], timeMs, and charactersUsed.
translateI18nObjectStream(params)
Same params as translateI18nObject. Yields I18nStreamChunk per key:
| Field | Type | Description |
|-------|------|-------------|
| key | string | Dot-separated key path |
| value | string | Original source value |
| translation | string | Translated value |
| index | number | 0-based key index |
| total | number | Total keys |
| done | boolean | True if last chunk |
| error | boolean | True if translation failed |
analyzeContext(params)
| Param | Type | Description |
|-------|------|-------------|
| texts | string[] | Sample texts from your website (20-100 recommended) |
| targetLangs | string[] | Target languages, e.g. ["vi", "ja"] |
| sourceLang | string | Source language (default: "en") |
Returns AnalyzeContextResult with domain, context, glossaries[],
and recommendedModel.
models()
Returns all available translation models with capabilities, speed ratings, quality ratings, and plan tier requirements. No parameters needed.
Returns ModelsResult with models[] (array of ModelInfo), total,
and tiers (plan → model IDs mapping).
Static Helpers
| Helper | Description |
|--------|-------------|
| Translomatic.getGlossary(result, lang) | Extract glossary for a language from analysis result |
| Translomatic.PLACEHOLDER_PATTERNS | Built-in regex patterns for common placeholder formats |
Smart Translation Warnings
The SDK automatically detects potential translation issues:
// 1. Same language → skipped (no API call, no quota used)
const result = await t.translate({
text: "Hello",
sourceLang: "en",
targetLang: "en",
});
console.log(result.warning); // "same_language: Source and target language are identical. Skipped API call."
console.log(result.engine); // "skip"
console.log(result.charactersUsed); // 0
// 2. Translation unchanged → warning from server
const result2 = await t.translate({
text: "Miễn phí",
sourceLang: "vi",
targetLang: "en",
});
if (result2.warning?.startsWith("translation_unchanged")) {
console.log("⚠ Translation may have failed — output matches source text");
}| Warning | Meaning |
|---------|---------|
| same_language | Source and target are the same. SDK returned original text without API call. |
| translation_unchanged | Output is identical to source text. Translation may have failed. |
| null | No issues detected. |
Error Handling
import { Translomatic, RateLimitError, QuotaExceededError } from "translomatic";
try {
await t.translate({ text: "Hello", targetLang: "es" });
} catch (err) {
if (err instanceof RateLimitError) {
console.log(`Rate limited. Retry in ${err.retryAfter}s`);
} else if (err instanceof QuotaExceededError) {
console.log("Monthly quota exceeded. Upgrade your plan.");
}
}License
MIT
