Skip to content

AI Text Translator — JavaScript source

Translate any text between 24 languages with an LLM — auto-detected or explicit source, straight from your browser with your own free Groq key.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

/**
 * text-translator — AI text translator: prompt building + reply cleanup.
 *
 * Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `text-translator` tool, ported from
 * src/lib/translate.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: the translator island is a thin shell over a shared
 * LLM provider, so the portable, testable surface is pure — the curated
 * language list, the [system, user] chat-message construction, and the reply
 * cleanup that strips stray markdown fences. Network I/O stays behind.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/** Source-language sentinel: let the model detect the input language. */
export const AUTO_SOURCE = 'auto';

/** Sentinel entry shown in the "from" select. */
export const AUTO_LANGUAGE = { id: AUTO_SOURCE, label: 'Auto-detect' };

/** Curated common-language list — the single source of truth for both selects. */
export const LANGUAGES = [
  { id: 'en', label: 'English' },
  { id: 'es', label: 'Spanish' },
  { id: 'fr', label: 'French' },
  { id: 'de', label: 'German' },
  { id: 'pt', label: 'Portuguese' },
  { id: 'it', label: 'Italian' },
  { id: 'nl', label: 'Dutch' },
  { id: 'sv', label: 'Swedish' },
  { id: 'pl', label: 'Polish' },
  { id: 'tr', label: 'Turkish' },
  { id: 'ru', label: 'Russian' },
  { id: 'uk', label: 'Ukrainian' },
  { id: 'ar', label: 'Arabic' },
  { id: 'fa', label: 'Persian' },
  { id: 'he', label: 'Hebrew' },
  { id: 'hi', label: 'Hindi' },
  { id: 'bn', label: 'Bengali' },
  { id: 'zh', label: 'Chinese' },
  { id: 'ja', label: 'Japanese' },
  { id: 'ko', label: 'Korean' },
  { id: 'vi', label: 'Vietnamese' },
  { id: 'th', label: 'Thai' },
  { id: 'id', label: 'Indonesian' },
  { id: 'sw', label: 'Swahili' },
];

const MAX_INPUT_CHARS = 12000;

/** Label for a known language id; unknown ids pass through unchanged. */
function languageLabel(id) {
  const hit = LANGUAGES.find((l) => l.id === id);
  return hit ? hit.label : id;
}

/**
 * Build the [system, user] chat messages for the provider layer.
 *
 * Inputs longer than MAX_INPUT_CHARS are cut and marked so the model knows
 * the text ends early (slice counts UTF-16 code units, exactly like the
 * TypeScript original).
 */
export function buildPromptMessages(text, { from, to }) {
  const fromPart =
    from === AUTO_SOURCE
      ? 'Detect the source language yourself.'
      : `The source language is ${languageLabel(from)}.`;
  const truncated = text.length > MAX_INPUT_CHARS;
  const body = truncated ? `${text.slice(0, MAX_INPUT_CHARS)}\n… (text truncated)` : text;
  return [
    {
      role: 'system',
      content: `You are a faithful translator. ${fromPart} Translate the user's text into ${languageLabel(
        to,
      )}. Output ONLY the translation — no preamble, no notes, no backticks, preserving paragraphs, formatting, and code blocks as-is.`,
    },
    { role: 'user', content: body },
  ];
}

/**
 * Clean the model's reply into displayable translation text. No strict
 * format contract — any non-empty cleaned text is the translation; null
 * only when nothing survives. Strips markdown code fences (``` plus an
 * optional lowercase info-string and newline) that models sometimes wrap
 * translations in despite instructions.
 */
export function parseTranslation(text) {
  const cleaned = text.replace(/```[a-z]*\n?/g, '').trim();
  return cleaned.length > 0 ? cleaned : null;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →