Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: i18n extraction/translation pipeline + studio and RPC refinements
nirholas58bdd49e364c
diff --git a/.i18nrc.json b/.i18nrc.jsonnew file mode 100644index 000000000..b0ad039f3--- /dev/null+++ b/.i18nrc.json@@ -0,0 +1,70 @@+{+ "$schema": "./scripts/i18n-rc.schema.json",+ "entry": "locales/en.json",+ "entryLocale": "en",+ "output": "locales",+ "outputLocales": [+ "es",+ "zh-CN",+ "ja",+ "ko",+ "fr",+ "de",+ "pt-BR",+ "ar",+ "hi",+ "ru"+ ],+ "localeNames": {+ "en": "English",+ "es": "Español",+ "zh-CN": "简体中文",+ "ja": "日本語",+ "ko": "한국어",+ "fr": "Français",+ "de": "Deutsch",+ "pt-BR": "Português (BR)",+ "ar": "العربية",+ "hi": "हिन्दी",+ "ru": "Русский"+ },+ "rtlLocales": ["ar", "he", "fa", "ur"],+ "provider": "gemini",+ "modelName": "gemini-2.5-flash",+ "temperature": 0.2,+ "topP": 0.9,+ "concurrency": 4,+ "splitToken": 1200,+ "saveImmediately": true,+ "reference": "three.ws is a platform to build, animate, rig, and monetize 3D AI agents on-chain. The audience is crypto-native developers and creators. Keep copy punchy and product-grade — match the energy of Vercel, Linear, and Stripe marketing. Prefer the natural, idiomatic phrasing a native speaker in that market would use over a literal word-for-word rendering. Preserve the marketing voice; do not pad or soften.",+ "htmlExtract": {+ "entry": [+ "pages/**/*.html",+ "public/**/*.html"+ ],+ "exclude": [+ "**/node_modules/**",+ "public/chat/**",+ "src/scene-studio/vendor/**"+ ]+ },+ "doNotTranslate": [+ "$THREE",+ "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "three.ws",+ "x402",+ "USDC",+ "Solana",+ "IBM watsonx.ai",+ "watsonx.ai",+ "Granite",+ "ERC-8004",+ "MCP",+ "pump.fun",+ "GLB",+ "glTF",+ "WebGL",+ "Three.js",+ "Forge"+ ]+}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b2f660147..bd1f03f76 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Avatar Studio: full-spectrum color picker and one-tap Looks** — The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast. (`/avatar-studio`) `[feature, improvement]`- **Clearer empty state on the $THREE live-trades feed** — Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in. (`/three-token`) `[improvement]`- **Coin pages stay fast when pump.fun is having a moment** — The /launches coin page pulls creator fee-sharing earnings live from pump.fun. We put that call behind a circuit breaker (built on the well-tested cockatiel library rather than home-grown code): if pump.fun slows down or errors, the breaker trips after a few failures and the page instantly skips that one enrichment instead of every visitor waiting out the timeout. The earnings simply show as unavailable until pump.fun recovers, and the rest of the page — registry, intel, outcome, trader record — was never affected. Same approach is now available platform-wide for other third-party data sources. (`/launches`) `[infra, improvement]`+- **Describe-it-to-3D no longer shows a confusing third-party billing error** — When you turn a text prompt into a 3D avatar, the first step paints a reference image — and that runs on the free NVIDIA lane by default. If that lane was briefly busy, the request could fall through to a paid backstop that had run out of credit, and the backstop's raw "go purchase credit" message leaked onto your screen. That's gone: any billing or out-of-credit hiccup on a backstop now shows a clean "temporarily unavailable — try again later," the free NVIDIA lane stays the primary path, and a third party's billing page never reaches you. (`/create/prompt`) `[fix]`- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`- **Discover and Marketplace now browse the same way** — Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid. (`/discover`) `[improvement]`- **Empty pages now guide you instead of going blank** — Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned. (`/dashboard`) `[improvement]`diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex 8019fa2b5..66bacb40b 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -290,6 +290,22 @@ export async function textToImage(prompt, { aspectRatio = '1:1' } = {}) {},);}+ // Hard out-of-credit / billing failure. Replicate returns this as a 402,+ // but the same "purchase credit at replicate.com/billing" copy can ride in+ // on other 4xx codes too — match on status OR content so a status change+ // upstream can never spill the vendor's billing page onto the buyer. Keep+ // the raw detail for logs (providerDetail); surface a neutral, buyer-safe+ // message the caller maps to "temporarily unavailable" (never "go buy+ // credit"). The free NIM lane is the primary path — this backstop being+ // dry must read as a transient platform issue, not a user-facing dead end.+ if (res.status === 402 || /credit|billing|purchase|payment required/i.test(detail)) {+ if (detail) console.warn(`[text-to-image] replicate billing/credit failure: ${detail}`);+ throw Object.assign(new Error('image provider billing error'), {+ code: 'billing',+ providerStatus: 402,+ providerDetail: detail,+ });+ }throw Object.assign(new Error(detail || `text-to-image returned ${res.status}`), {providerStatus: res.status,});diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 3bc877a0f..9294b65f9 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -997,8 +997,17 @@ const handleReconstruct = wrap(async (req, res) => {if (err?.code === 'provider_unreachable') {return error(res, 503, 'txt2img_unreachable', err.message);}- if (err?.providerStatus === 402) {- return error(res, 402, 'txt2img_billing', err.message || 'image provider billing error');+ if (err?.code === 'billing' || err?.providerStatus === 402) {+ // Never relay the provider's raw "purchase credit at …/billing"+ // copy — even the error_description must be buyer-safe, since a+ // client may surface it verbatim. textToImage already logged the+ // raw detail (providerDetail) for operators.+ return error(+ res,+ 402,+ 'txt2img_billing',+ 'the image engine is temporarily unavailable — please try again later',+ );}return error(res,diff --git a/pages/agent-studio.html b/pages/agent-studio.htmlindex dc3a3138b..b748b3661 100644--- a/pages/agent-studio.html+++ b/pages/agent-studio.html@@ -28,6 +28,15 @@<link rel="stylesheet" href="/memory-studio.css" /><style>+ /* Base reset: this page deliberately skips style.css, so it must carry+ the [hidden] guard itself. Without it, components that toggle the+ `hidden` attribute (brain studio's onboard/editor/modal views, etc.)+ stay visible — their class rules set `display`, which beats the UA+ `[hidden]{display:none}` rule. */+ [hidden] {+ display: none !important;+ }+html,body {margin: 0;diff --git a/pages/home.html b/pages/home.htmlindex 007b7eebe..f12ab4d0b 100644--- a/pages/home.html+++ b/pages/home.html@@ -4,8 +4,8 @@<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />- <title>three.ws — The 3D Agent Layer of the Internet</title>- <meta name="description" content="Make a 3D AI agent from a selfie in 60 seconds. Drop one HTML tag to embed it on any website. Agents think on IBM watsonx.ai (Granite); optionally charge per chat with built-in micropayments." />+ <title data-i18n="home.meta_title">three.ws — The 3D Agent Layer of the Internet</title>+ <meta name="description" data-i18n-attr="content:home.meta_desc" content="Make a 3D AI agent from a selfie in 60 seconds. Drop one HTML tag to embed it on any website. Agents think on IBM watsonx.ai (Granite); optionally charge per chat with built-in micropayments." /><link rel="canonical" href="https://three.ws/" /><link rel="alternate" type="application/rss+xml" title="three.ws announcements" href="https://three.ws/rss/announcements.xml" /><meta name="theme-color" content="#050505" />@@ -2461,22 +2461,22 @@<main id="main-content" tabindex="-1"><section class="hero"><div class="hero-text">- <a class="eyebrow" href="/forge" aria-label="New: Text to 3D is live — open the Forge">New · Text → 3D is live — type a prompt, get a model <span class="eyebrow-arrow" aria-hidden="true">→</span></a>- <h1 class="hero-h">+ <a class="eyebrow" href="/forge" data-i18n-html="home.eyebrow" data-i18n-attr="aria-label:home.eyebrow_aria" aria-label="New: Text to 3D is live — open the Forge">New · Text → 3D is live — type a prompt, get a model <span class="eyebrow-arrow" aria-hidden="true">→</span></a>+ <h1 class="hero-h" data-i18n-html="home.hero_h">The 3D agent<br/>layer of the<br/><em>internet.</em></h1><ul class="hero-bullets">- <li><strong>Create</strong> a 3D AI agent from a text prompt or selfie in about a minute</li>- <li><strong>Embed</strong> it on any website with two lines of HTML</li>- <li><strong>Earn</strong> USDC per chat with x402 micropayments</li>+ <li data-i18n-html="home.bullet_create"><strong>Create</strong> a 3D AI agent from a text prompt or selfie in about a minute</li>+ <li data-i18n-html="home.bullet_embed"><strong>Embed</strong> it on any website with two lines of HTML</li>+ <li data-i18n-html="home.bullet_earn"><strong>Earn</strong> USDC per chat with x402 micropayments</li></ul><div class="hero-cta-row">- <a class="btn btn--primary" href="/create" data-cta="build_agent" data-cta-loc="hero">Build your agent <span class="arrow">→</span></a>- <a class="btn btn--forge" href="/forge" data-cta="text_to_3d" data-cta-loc="hero"><span class="btn-forge-dot" aria-hidden="true"></span>Text → 3D</a>- <a class="btn" href="#embed" data-cta="see_embed" data-cta-loc="hero">See the embed</a>- <a class="btn" href="/tour" id="hero-tour-start" data-cta="guided_tour" data-cta-loc="hero"><span aria-hidden="true">▶</span> Take the tour</a>+ <a class="btn btn--primary" href="/create" data-cta="build_agent" data-cta-loc="hero" data-i18n-html="home.cta_build">Build your agent <span class="arrow">→</span></a>+ <a class="btn btn--forge" href="/forge" data-cta="text_to_3d" data-cta-loc="hero"><span class="btn-forge-dot" aria-hidden="true"></span><span data-i18n="home.cta_text3d">Text → 3D</span></a>+ <a class="btn" href="#embed" data-cta="see_embed" data-cta-loc="hero" data-i18n="home.cta_embed">See the embed</a>+ <a class="btn" href="/tour" id="hero-tour-start" data-cta="guided_tour" data-cta-loc="hero"><span aria-hidden="true">▶</span> <span data-i18n="common.take_tour">Take the tour</span></a></div></div><div class="hero-stage" id="hero-stage">diff --git a/public/changelog.json b/public/changelog.jsonindex 64837e1f7..c805bb4e4 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T11:26:39.172Z",+ "generated_at": "2026-06-21T11:27:12.278Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -181,6 +181,16 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Describe-it-to-3D no longer shows a confusing third-party billing error",+ "summary": "When you turn a text prompt into a 3D avatar, the first step paints a reference image — and that runs on the free NVIDIA lane by default. If that lane was briefly busy, the request could fall through to a paid backstop that had run out of credit, and the backstop's raw \"go purchase credit\" message leaked onto your screen. That's gone: any billing or out-of-credit hiccup on a backstop now shows a clean \"temporarily unavailable — try again later,\" the free NVIDIA lane stays the primary path, and a third party's billing page never reaches you.",+ "link": "/create/prompt",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex e00398d4b..6031806c1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -142,6 +142,14 @@<category>infra</category><description>The /launches coin page pulls creator fee-sharing earnings live from pump.fun. We put that call behind a circuit breaker (built on the well-tested cockatiel library rather than home-grown code): if pump.fun slows down or errors, the breaker trips after a few failures and the page instantly skips that one enrichment instead of every visitor waiting out the timeout. The earnings simply show as unavailable until pump.fun recovers, and the rest of the page — registry, intel, outcome, trader record — was never affected. Same approach is now available platform-wide for other third-party data sources.</description></item>+ <item>+ <title>Describe-it-to-3D no longer shows a confusing third-party billing error</title>+ <link>https://three.ws/create/prompt</link>+ <guid isPermaLink="false">2026-06-21:Describe-it-to-3D no longer shows a confusing third-party billing error</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When you turn a text prompt into a 3D avatar, the first step paints a reference image — and that runs on the free NVIDIA lane by default. If that lane was briefly busy, the request could fall through to a paid backstop that had run out of credit, and the backstop's raw "go purchase credit" message leaked onto your screen. That's gone: any billing or out-of-credit hiccup on a backstop now shows a clean "temporarily unavailable — try again later," the free NVIDIA lane stays the primary path, and a third party's billing page never reaches you.</description>+ </item><item><title>Discover and character feeds load faster under heavy traffic</title><link>https://three.ws/discover</link>diff --git a/public/features.json b/public/features.jsonindex f6aa47048..c7aaee7ac 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T11:26:39.027Z",+ "generated_at": "2026-06-21T11:27:12.118Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/i18n-extract.mjs b/scripts/i18n-extract.mjsnew file mode 100644index 000000000..c19ccb0d7--- /dev/null+++ b/scripts/i18n-extract.mjs@@ -0,0 +1,134 @@+#!/usr/bin/env node+// i18n-extract — scan annotated HTML and build/refresh the source-of-truth+// catalog (locales/en.json).+//+// three.ws ships copy inline in 150+ static HTML pages, so unlike a greenfield+// i18next app there is no pre-existing key catalog. The migration path is to+// annotate markup incrementally and let this script derive the catalog:+//+// <h1 data-i18n="home.title">The 3D agent layer of the internet.</h1>+// <p data-i18n-html="home.lede">Create <strong>living</strong> agents.</p>+// <meta name="description" data-i18n-attr="content:home.meta_desc" content="…">+// <a data-i18n="common.tour" data-i18n-attr="aria-label:common.tour_aria">Take the tour</a>+//+// The English text already in the element IS the source value — no duplication,+// no drift. Existing values are preserved (annotating a page never clobbers a+// reviewed string); pass --force to overwrite from the current HTML, --prune to+// drop keys no element references anymore.++import { readFileSync, writeFileSync } from 'node:fs';+import { resolve, relative } from 'node:path';+import { pathToFileURL } from 'node:url';+import { glob } from 'glob';+import { parse } from 'node-html-parser';+import { ROOT, loadConfig, readJSON, setDeep, getDeep, flatten } from './lib/i18n-shared.mjs';++const collapse = (s) => (s || '').replace(/\s+/g, ' ').trim();++// Pull every (key, sourceValue) pair out of one HTML document. Pure — operates+// on a string so it is unit-testable without the filesystem.+export function extractFromHtml(html) {+ const root = parse(html, { comment: false, blockTextElements: { script: false, style: false } });+ const found = new Map(); // key → value++ for (const el of root.querySelectorAll('[data-i18n]')) {+ const key = el.getAttribute('data-i18n');+ if (key) found.set(key, collapse(el.text));+ }+ for (const el of root.querySelectorAll('[data-i18n-html]')) {+ const key = el.getAttribute('data-i18n-html');+ if (key) found.set(key, el.innerHTML.trim());+ }+ for (const el of root.querySelectorAll('[data-i18n-attr]')) {+ // "content:home.meta_desc;aria-label:common.tour_aria"+ for (const pair of el.getAttribute('data-i18n-attr').split(';')) {+ const [attr, key] = pair.split(':').map((s) => s && s.trim());+ if (attr && key) found.set(key, collapse(el.getAttribute(attr)));+ }+ }+ return found;+}++function deepSort(obj) {+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return obj;+ const out = {};+ for (const k of Object.keys(obj).sort()) out[k] = deepSort(obj[k]);+ return out;+}++async function main() {+ const args = new Set(process.argv.slice(2));+ const FORCE = args.has('--force');+ const PRUNE = args.has('--prune');++ const cfg = loadConfig();+ const entryPath = resolve(ROOT, cfg.entry);+ const existing = readJSON(entryPath, {}) || {};++ const patterns = cfg.htmlExtract?.entry || ['pages/**/*.html', 'public/**/*.html'];+ const ignore = cfg.htmlExtract?.exclude || [];+ const files = (await glob(patterns, { cwd: ROOT, ignore, absolute: true, nodir: true })).sort();++ const catalog = {};+ const seen = new Set();+ const sources = new Map(); // key → first file that defined it+ const collisions = [];+ let added = 0;+ let reused = 0;++ for (const file of files) {+ let pairs;+ try {+ pairs = extractFromHtml(readFileSync(file, 'utf8'));+ } catch (err) {+ console.warn(`! skipped ${relative(ROOT, file)}: ${err.message}`);+ continue;+ }+ for (const [key, value] of pairs) {+ if (seen.has(key)) {+ if (getDeep(catalog, key) !== value) {+ collisions.push(+ `${key}: "${getDeep(catalog, key)}" (${sources.get(key)}) vs "${value}" (${relative(ROOT, file)})`,+ );+ }+ continue;+ }+ seen.add(key);+ sources.set(key, relative(ROOT, file));+ const prior = getDeep(existing, key);+ if (prior !== undefined && !FORCE) {+ setDeep(catalog, key, prior);+ reused++;+ } else {+ setDeep(catalog, key, value);+ added++;+ }+ }+ }++ // Carry over catalog-only keys (strings used from JS via t(), never annotated+ // in HTML) unless --prune is requested.+ if (!PRUNE) {+ for (const [key, value] of Object.entries(flatten(existing))) {+ if (!seen.has(key)) setDeep(catalog, key, value);+ }+ }++ const sorted = deepSort(catalog);+ writeFileSync(entryPath, JSON.stringify(sorted, null, 2) + '\n');++ const total = Object.keys(flatten(sorted)).length;+ console.log(`i18n-extract: ${files.length} files → ${total} keys (${added} new, ${reused} preserved)`);+ if (collisions.length) {+ console.warn(`\n⚠ ${collisions.length} key collision(s) — same key, different English text:`);+ for (const c of collisions) console.warn(' ' + c);+ process.exitCode = 1;+ }+}++if (import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((err) => {+ console.error(err);+ process.exit(1);+ });+}diff --git a/scripts/i18n-rc.schema.json b/scripts/i18n-rc.schema.jsonnew file mode 100644index 000000000..e9b96e732--- /dev/null+++ b/scripts/i18n-rc.schema.json@@ -0,0 +1,31 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "three.ws i18n config",+ "type": "object",+ "required": ["entry", "entryLocale", "output", "outputLocales"],+ "additionalProperties": true,+ "properties": {+ "entry": { "type": "string", "description": "Source-of-truth locale JSON (the entryLocale catalog)." },+ "entryLocale": { "type": "string", "description": "Reference language code, e.g. 'en'." },+ "output": { "type": "string", "description": "Directory holding all locale JSON files." },+ "outputLocales": { "type": "array", "items": { "type": "string" }, "description": "Target language codes to generate." },+ "localeNames": { "type": "object", "description": "code → human-readable display name for the locale switcher." },+ "rtlLocales": { "type": "array", "items": { "type": "string" }, "description": "Locale codes that render right-to-left." },+ "provider": { "enum": ["gemini", "openai", "anthropic"], "description": "Which LLM backend to translate with." },+ "modelName": { "type": "string" },+ "temperature": { "type": "number", "minimum": 0, "maximum": 2 },+ "topP": { "type": "number", "minimum": 0, "maximum": 1 },+ "concurrency": { "type": "integer", "minimum": 1, "description": "Parallel translation requests." },+ "splitToken": { "type": "integer", "minimum": 200, "description": "Approx token budget per chunk before splitting a namespace." },+ "saveImmediately": { "type": "boolean", "description": "Persist each locale as soon as it finishes." },+ "reference": { "type": "string", "description": "Domain context handed to the model for accurate, on-brand translations." },+ "htmlExtract": {+ "type": "object",+ "properties": {+ "entry": { "type": "array", "items": { "type": "string" } },+ "exclude": { "type": "array", "items": { "type": "string" } }+ }+ },+ "doNotTranslate": { "type": "array", "items": { "type": "string" }, "description": "Brand/protocol terms masked verbatim so the model can never alter them." }+ }+}diff --git a/scripts/i18n-translate.mjs b/scripts/i18n-translate.mjsnew file mode 100644index 000000000..5090f7865--- /dev/null+++ b/scripts/i18n-translate.mjs@@ -0,0 +1,318 @@+#!/usr/bin/env node+// i18n-translate — incremental, glossary-locked machine translation of the+// source catalog into every target locale, modeled on LobeHub's lobe-i18n.+//+// Pipeline (matches the LobeHub approach, adapted for three.ws):+// 1. Read the entryLocale catalog (locales/en.json) as the source of truth.+// 2. For each target locale, diff against the committed translation and+// translate ONLY the missing/empty keys — re-runs are nearly free.+// 3. Brand/protocol terms, {{placeholders}}, and HTML tags are masked to+// opaque sentinels before the text reaches the model and restored after,+// so `$THREE`, the contract address, etc. come back byte-for-byte.+// 4. Large namespaces are split under a token budget; chunks run concurrently.+// 5. Output is committed as static JSON — zero runtime translation cost.+//+// Backends (real APIs, selected by `provider` in .i18nrc.json):+// gemini → Generative Language API (GEMINI_API_KEY | GOOGLE_API_KEY)+// openai → Chat Completions (OPENAI_API_KEY [+ OPENAI_BASE_URL])+// anthropic → Messages (ANTHROPIC_API_KEY)+//+// Usage:+// node scripts/i18n-translate.mjs # translate missing keys, all locales+// node scripts/i18n-translate.mjs --locale=es # one locale+// node scripts/i18n-translate.mjs --force # retranslate everything+// node scripts/i18n-translate.mjs --lint # validate only (build gate, no API key needed)+// node scripts/i18n-translate.mjs --dry-run # report what would translate++import { writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import {+ ROOT,+ loadConfig,+ readJSON,+ flatten,+ setDeep,+ getDeep,+ missingKeys,+ mergeOrdered,+ buildMasker,+ lintLocale,+} from './lib/i18n-shared.mjs';++const args = process.argv.slice(2);+const flag = (name) => args.includes(`--${name}`);+const opt = (name) => {+ const hit = args.find((a) => a.startsWith(`--${name}=`));+ return hit ? hit.split('=').slice(1).join('=') : undefined;+};++const cfg = loadConfig();+const sourcePath = resolve(ROOT, cfg.entry);+const source = readJSON(sourcePath);+if (!source) {+ console.error(`Source catalog not found: ${cfg.entry}. Run \`npm run i18n:extract\` first.`);+ process.exit(1);+}++const onlyLocale = opt('locale');+const targets = (onlyLocale ? [onlyLocale] : cfg.outputLocales).filter(Boolean);+const localePath = (code) => resolve(ROOT, cfg.output, `${code}.json`);++// --- lint mode: pure validation, no network, safe to run in CI -------------++function runLint() {+ let problems = 0;+ for (const code of targets) {+ const target = readJSON(localePath(code));+ if (!target) {+ console.error(`✗ ${code}: missing ${cfg.output}/${code}.json`);+ problems++;+ continue;+ }+ const found = lintLocale(source, target, { code, doNotTranslate: cfg.doNotTranslate });+ if (found.length) {+ problems += found.length;+ for (const p of found) console.error('✗ ' + p);+ } else {+ console.log(`✓ ${code}: ${Object.keys(flatten(target)).length} keys OK`);+ }+ }+ if (problems) {+ console.error(`\ni18n lint failed: ${problems} problem(s).`);+ process.exit(1);+ }+ console.log('\ni18n lint passed.');+}++// --- chunking --------------------------------------------------------------++// Split missing keys into chunks whose combined source text stays under the+// token budget (≈4 chars/token) so no single request risks truncation.+function chunkKeys(keys, budgetChars) {+ const chunks = [];+ let cur = [];+ let size = 0;+ for (const k of keys) {+ const len = String(getDeep(source, k) ?? '').length + k.length + 8;+ if (cur.length && size + len > budgetChars) {+ chunks.push(cur);+ cur = [];+ size = 0;+ }+ cur.push(k);+ size += len;+ }+ if (cur.length) chunks.push(cur);+ return chunks;+}++// --- LLM backends ----------------------------------------------------------++function stripFences(text) {+ return text.replace(/^\s*```(?:json)?/i, '').replace(/```\s*$/, '').trim();+}++function buildPrompt(langName, payload) {+ return [+ `You are a professional software localizer translating UI and marketing copy from English to ${langName}.`,+ cfg.reference || '',+ '',+ 'Rules:',+ `- Translate every VALUE in the JSON below into ${langName}. Keep every KEY exactly as-is.`,+ '- Return ONLY a single minified JSON object with the same keys. No prose, no code fences.',+ '- Some values contain sentinel runs of unusual non-Latin control characters (private-use-area glyphs surrounding digits). These are protected tokens for brand names, code, and placeholders. Reproduce every such sentinel EXACTLY, in a natural position for the target language. Never translate, reorder the digits, drop, or add them.',+ '- Preserve meaning, tone, and any HTML that survives as a sentinel. Do not add explanations.',+ '',+ 'JSON to translate:',+ JSON.stringify(payload),+ ]+ .filter(Boolean)+ .join('\n');+}++async function callGemini(prompt) {+ const key = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY || process.env.GOOGLE_GENAI_API_KEY;+ if (!key) throw new Error('GEMINI_API_KEY (or GOOGLE_API_KEY) not set');+ const model = cfg.modelName || 'gemini-2.5-flash';+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${key}`;+ const res = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ contents: [{ role: 'user', parts: [{ text: prompt }] }],+ generationConfig: {+ temperature: cfg.temperature ?? 0.2,+ topP: cfg.topP ?? 0.9,+ responseMimeType: 'application/json',+ },+ }),+ });+ if (!res.ok) throw new Error(`gemini ${res.status}: ${(await res.text()).slice(0, 300)}`);+ const data = await res.json();+ const text = data?.candidates?.[0]?.content?.parts?.map((p) => p.text).join('') || '';+ if (!text) throw new Error('gemini returned empty content');+ return text;+}++async function callOpenAI(prompt) {+ const key = process.env.OPENAI_API_KEY;+ if (!key) throw new Error('OPENAI_API_KEY not set');+ const base = process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1';+ const res = await fetch(`${base}/chat/completions`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },+ body: JSON.stringify({+ model: cfg.modelName || 'gpt-4o-mini',+ temperature: cfg.temperature ?? 0.2,+ top_p: cfg.topP ?? 0.9,+ response_format: { type: 'json_object' },+ messages: [{ role: 'user', content: prompt }],+ }),+ });+ if (!res.ok) throw new Error(`openai ${res.status}: ${(await res.text()).slice(0, 300)}`);+ const data = await res.json();+ return data?.choices?.[0]?.message?.content || '';+}++async function callAnthropic(prompt) {+ const key = process.env.ANTHROPIC_API_KEY;+ if (!key) throw new Error('ANTHROPIC_API_KEY not set');+ const res = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-api-key': key,+ 'anthropic-version': '2023-06-01',+ },+ body: JSON.stringify({+ model: cfg.modelName || 'claude-haiku-4-5-20251001',+ max_tokens: 8192,+ temperature: cfg.temperature ?? 0.2,+ messages: [{ role: 'user', content: prompt }],+ }),+ });+ if (!res.ok) throw new Error(`anthropic ${res.status}: ${(await res.text()).slice(0, 300)}`);+ const data = await res.json();+ return data?.content?.map((b) => b.text || '').join('') || '';+}++const BACKENDS = { gemini: callGemini, openai: callOpenAI, anthropic: callAnthropic };++async function translateChunk(langName, payload, attempt = 0) {+ const call = BACKENDS[cfg.provider || 'gemini'];+ if (!call) throw new Error(`unknown provider: ${cfg.provider}`);+ try {+ const raw = await call(buildPrompt(langName, payload));+ const parsed = JSON.parse(stripFences(raw));+ if (!parsed || typeof parsed !== 'object') throw new Error('non-object response');+ return parsed;+ } catch (err) {+ if (attempt < 2) {+ await new Promise((r) => setTimeout(r, 400 * (attempt + 1)));+ return translateChunk(langName, payload, attempt + 1);+ }+ throw err;+ }+}++// Bounded-concurrency map.+async function pool(items, limit, worker) {+ const results = new Array(items.length);+ let i = 0;+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (i < items.length) {+ const idx = i++;+ results[idx] = await worker(items[idx], idx);+ }+ });+ await Promise.all(runners);+ return results;+}++// --- per-locale translation ------------------------------------------------++const masker = buildMasker(cfg.doNotTranslate);++async function translateLocale(code) {+ const langName = cfg.localeNames?.[code] || code;+ const existing = readJSON(localePath(code), {}) || {};+ const todo = flag('force') ? Object.keys(flatten(source)) : missingKeys(source, existing);++ if (!todo.length) {+ console.log(`• ${code}: up to date`);+ return { code, translated: 0 };+ }+ if (flag('dry-run')) {+ console.log(`• ${code}: would translate ${todo.length} key(s)`);+ return { code, translated: 0 };+ }++ const chunks = chunkKeys(todo, (cfg.splitToken || 1200) * 4);+ console.log(`→ ${code}: ${todo.length} key(s) in ${chunks.length} chunk(s) via ${cfg.provider}`);++ const translatedFlat = {};+ let done = 0;++ await pool(chunks, cfg.concurrency || 4, async (keys) => {+ // Mask source values; remember tokens per key to restore afterwards.+ const payload = {};+ const tokenMap = {};+ for (const k of keys) {+ const { masked, tokens } = masker.mask(String(getDeep(source, k) ?? ''));+ payload[k] = masked;+ tokenMap[k] = tokens;+ }+ const out = await translateChunk(langName, payload, 0);+ for (const k of keys) {+ const val = out[k];+ if (typeof val !== 'string') {+ console.warn(` ! ${code} ${k}: model omitted key, keeping source`);+ translatedFlat[k] = getDeep(source, k);+ continue;+ }+ translatedFlat[k] = masker.unmask(val, tokenMap[k]);+ }+ done += keys.length;+ if (cfg.saveImmediately) {+ persist(code, existing, translatedFlat);+ }+ console.log(` ${code}: ${done}/${todo.length}`);+ });++ persist(code, existing, translatedFlat);+ return { code, translated: todo.length };+}++// Merge fresh translations over prior ones, dropping stale keys (mergeOrdered+// only emits keys that exist in the source), and write committed JSON.+function persist(code, existing, translatedFlat) {+ const translatedNested = {};+ for (const [k, v] of Object.entries(translatedFlat)) setDeep(translatedNested, k, v);+ const merged = mergeOrdered(source, existing, translatedNested);+ writeFileSync(localePath(code), JSON.stringify(merged, null, 2) + '\n');+}++// Refresh the runtime manifest the locale switcher reads.+function writeManifest() {+ const localesList = [cfg.entryLocale, ...cfg.outputLocales].map((code) => ({+ code,+ name: cfg.localeNames?.[code] || code,+ dir: (cfg.rtlLocales || []).includes(code) ? 'rtl' : 'ltr',+ }));+ const manifest = { default: cfg.entryLocale, locales: localesList };+ writeFileSync(resolve(ROOT, cfg.output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');+}++async function main() {+ if (flag('lint')) return runLint();++ writeManifest();+ const results = await pool(targets, 1, translateLocale); // locales sequential; chunks parallel within+ const n = results.reduce((s, r) => s + (r?.translated || 0), 0);+ console.log(`\ni18n-translate: ${n} key(s) translated across ${targets.length} locale(s).`);+}++main().catch((err) => {+ console.error(err.message || err);+ process.exit(1);+});diff --git a/scripts/lib/i18n-shared.mjs b/scripts/lib/i18n-shared.mjsnew file mode 100644index 000000000..0b63dd416--- /dev/null+++ b/scripts/lib/i18n-shared.mjs@@ -0,0 +1,181 @@+// Shared helpers for the three.ws i18n pipeline (extract + translate + lint).+//+// The pipeline mirrors LobeHub's lobe-i18n: a single source-of-truth catalog+// (the entryLocale) is translated incrementally into target locales by an LLM,+// with brand/protocol terms masked so they can never be altered, and the output+// committed as static JSON. This module holds the pure, testable plumbing both+// CLIs depend on.++import { readFileSync, existsSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');++export function loadConfig() {+ const path = resolve(ROOT, '.i18nrc.json');+ if (!existsSync(path)) throw new Error('.i18nrc.json not found at repo root');+ const cfg = JSON.parse(readFileSync(path, 'utf8'));+ cfg.localeNames ||= {};+ cfg.rtlLocales ||= [];+ cfg.doNotTranslate ||= [];+ return cfg;+}++export function readJSON(path, fallback = undefined) {+ if (!existsSync(path)) return fallback;+ return JSON.parse(readFileSync(path, 'utf8'));+}++// --- nested-object key utilities (keyStyle: nested) -----------------------++const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);++// Flatten { a: { b: "x" } } → { "a.b": "x" } for diffing and validation.+export function flatten(obj, prefix = '', out = {}) {+ for (const [k, v] of Object.entries(obj || {})) {+ const key = prefix ? `${prefix}.${k}` : k;+ if (isPlainObject(v)) flatten(v, key, out);+ else out[key] = v;+ }+ return out;+}++export function setDeep(obj, dottedKey, value) {+ const parts = dottedKey.split('.');+ let node = obj;+ for (let i = 0; i < parts.length - 1; i++) {+ if (!isPlainObject(node[parts[i]])) node[parts[i]] = {};+ node = node[parts[i]];+ }+ node[parts[parts.length - 1]] = value;+ return obj;+}++export function getDeep(obj, dottedKey) {+ return dottedKey.split('.').reduce((n, p) => (isPlainObject(n) || Array.isArray(n) ? n[p] : undefined), obj);+}++// Keys present (and non-empty) in `source` but missing/empty in `target`.+export function missingKeys(source, target) {+ const src = flatten(source);+ const tgt = flatten(target || {});+ return Object.keys(src).filter((k) => {+ const v = tgt[k];+ return v === undefined || v === null || (typeof v === 'string' && v.trim() === '');+ });+}++// Keys present in target but no longer in source — stale translations to prune.+export function staleKeys(source, target) {+ const src = flatten(source);+ const tgt = flatten(target || {});+ return Object.keys(tgt).filter((k) => !(k in src));+}++// Deep-merge translated values into an existing target, preserving key order of+// the source so committed diffs stay readable.+export function mergeOrdered(source, existing = {}, translated = {}) {+ const out = Array.isArray(source) ? [] : {};+ for (const [k, v] of Object.entries(source)) {+ if (isPlainObject(v)) {+ out[k] = mergeOrdered(v, existing?.[k] || {}, translated?.[k] || {});+ } else {+ // Prefer a freshly translated value, then a prior translation, else blank.+ out[k] = translated?.[k] ?? existing?.[k] ?? '';+ }+ }+ return out;+}++// --- glossary masking -----------------------------------------------------+//+// Brand/protocol terms (and {{interpolation}} placeholders and HTML tags) are+// swapped for opaque sentinels BEFORE the text reaches the model and restored+// AFTER. This guarantees `$THREE`, the contract address, etc. are returned+// byte-for-byte — the model literally never sees them, so it can't translate,+// localize, or hallucinate around them.++const PLACEHOLDER_RE = /\{\{[^}]+\}\}/g; // {{count}}+const TAG_RE = /<\/?[a-zA-Z][^>]*>/g; // <br/>, <strong>, </strong>++function escapeRe(s) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++export function buildMasker(doNotTranslate = []) {+ // Longer terms first so "IBM watsonx.ai" masks before "watsonx.ai".+ const terms = [...doNotTranslate].sort((a, b) => b.length - a.length);+ const sentinel = (i) => `${i}`; // private-use-area, never in real copy++ function mask(text) {+ if (typeof text !== 'string') return { masked: text, tokens: [] };+ const tokens = [];+ let masked = text;+ const stash = (re) => {+ masked = masked.replace(re, (m) => {+ const id = tokens.length;+ tokens.push(m);+ return sentinel(id);+ });+ };+ // Order matters: placeholders and tags first, then literal glossary terms.+ stash(PLACEHOLDER_RE);+ stash(TAG_RE);+ for (const term of terms) {+ if (!term) continue;+ stash(new RegExp(escapeRe(term), 'g'));+ }+ return { masked, tokens };+ }++ function unmask(text, tokens) {+ if (typeof text !== 'string') return text;+ return text.replace(/(\d+)/g, (_, i) => tokens[Number(i)] ?? '');+ }++ return { mask, unmask };+}++// --- validation (lint) ----------------------------------------------------++// Returns an array of human-readable problems; empty array means the locale is+// structurally sound against the source.+export function lintLocale(source, target, { code, doNotTranslate = [] } = {}) {+ const problems = [];+ const src = flatten(source);+ const tgt = flatten(target || {});++ for (const k of Object.keys(src)) {+ const sv = src[k];+ const tv = tgt[k];+ if (tv === undefined) {+ problems.push(`[${code}] missing key: ${k}`);+ continue;+ }+ if (typeof tv === 'string' && tv.trim() === '') {+ problems.push(`[${code}] empty value: ${k}`);+ continue;+ }+ if (typeof sv !== 'string' || typeof tv !== 'string') continue;++ // Every {{placeholder}} in the source must survive in the translation.+ const srcVars = (sv.match(PLACEHOLDER_RE) || []).sort();+ const tgtVars = (tv.match(PLACEHOLDER_RE) || []).sort();+ if (srcVars.join('|') !== tgtVars.join('|')) {+ problems.push(`[${code}] placeholder drift in ${k}: ${srcVars.join(',') || '∅'} → ${tgtVars.join(',') || '∅'}`);+ }++ // Any do-not-translate term in the source must appear verbatim.+ for (const term of doNotTranslate) {+ if (sv.includes(term) && !tv.includes(term)) {+ problems.push(`[${code}] glossary term dropped in ${k}: "${term}"`);+ }+ }+ }++ for (const k of Object.keys(tgt)) {+ if (!(k in src)) problems.push(`[${code}] stale key (not in source): ${k}`);+ }+ return problems;+}diff --git a/src/dashboard-next/components/topbar.js b/src/dashboard-next/components/topbar.jsindex 490594f9c..96f120891 100644--- a/src/dashboard-next/components/topbar.js+++ b/src/dashboard-next/components/topbar.js@@ -396,7 +396,7 @@ function renderWalkEmptyState(host) {<path d="M5.5 20a6.5 6.5 0 0113 0"/><path d="M19 4v4M21 6h-4"/></svg>`;- btn.onclick = () => { location.href = '/avatar-edit'; };+ btn.onclick = () => { location.href = '/create'; };}// Error: avatar lookup failed (network). Offer a retry rather than a dead frame.@@ -534,7 +534,7 @@ function toggleWalkMenu(btn) {</div><div style="padding:6px 0"><a href="/walk/app?avatar=${encodeURIComponent(_walkAvatar.id)}" class="dn-user-menu-item" role="menuitem">Open Walk</a>- <a href="/avatar-edit?id=${encodeURIComponent(_walkAvatar.id)}" class="dn-user-menu-item" role="menuitem">Edit Avatar</a>+ <a href="/avatars/${encodeURIComponent(_walkAvatar.id)}/edit" class="dn-user-menu-item" role="menuitem">Edit Avatar</a></div>`;diff --git a/src/i18n.js b/src/i18n.jsnew file mode 100644index 000000000..ae95ca353--- /dev/null+++ b/src/i18n.js@@ -0,0 +1,219 @@+// three.ws runtime i18n — client-side locale swap, the LobeHub model.+//+// Copy lives in static HTML annotated with data-i18n attributes; the source+// catalog and machine translations are committed as static JSON under+// /locales/<code>.json (built offline by scripts/i18n-translate.mjs). At+// runtime this module detects the visitor's locale, fetches that catalog once,+// and rewrites the annotated DOM — no per-request API calls, no translation+// cost, fully cacheable.+//+// Annotations (see scripts/i18n-extract.mjs):+// data-i18n="key" → element.textContent+// data-i18n-html="key" → element.innerHTML (values that contain markup)+// data-i18n-attr="attr:key;attr2:key2" → element attributes (aria-label, content, …)+//+// Pure helpers (resolveKey, interpolate, applyCatalog) are exported for tests+// and run without a DOM.++const STORAGE_KEY = 'twx_lang';+const LOCALES_BASE = '/locales';++const hasDOM = typeof document !== 'undefined';+const state = {+ manifest: null,+ current: 'en',+ catalog: {}, // active locale strings (nested)+ fallback: {}, // entryLocale strings, so a missing translation degrades to English+};++// --- pure helpers ----------------------------------------------------------++// Dot-path lookup against a nested catalog: resolveKey({a:{b:'x'}}, 'a.b') → 'x'.+export function resolveKey(catalog, key) {+ return key.split('.').reduce((node, part) => (node && typeof node === 'object' ? node[part] : undefined), catalog);+}++// {{name}} interpolation. Missing vars are left as the literal token so they're+// visible in QA rather than silently blank.+export function interpolate(str, vars) {+ if (typeof str !== 'string' || !vars) return str;+ return str.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (m, k) => (k in vars ? String(vars[k]) : m));+}++// Translate one key with graceful fallback: active locale → entryLocale → key.+export function translate(key, vars, { catalog = state.catalog, fallback = state.fallback } = {}) {+ const hit = resolveKey(catalog, key);+ const value = hit !== undefined && hit !== '' ? hit : resolveKey(fallback, key);+ return interpolate(value !== undefined ? value : key, vars);+}++// Apply a catalog to a DOM subtree. Exported with an injectable root so tests+// can pass a jsdom document fragment.+export function applyCatalog(root, t) {+ if (!root) return;+ root.querySelectorAll?.('[data-i18n]').forEach((el) => {+ const v = t(el.getAttribute('data-i18n'));+ if (v != null) el.textContent = v;+ });+ root.querySelectorAll?.('[data-i18n-html]').forEach((el) => {+ const v = t(el.getAttribute('data-i18n-html'));+ if (v != null) el.innerHTML = v;+ });+ root.querySelectorAll?.('[data-i18n-attr]').forEach((el) => {+ for (const pair of el.getAttribute('data-i18n-attr').split(';')) {+ const [attr, key] = pair.split(':').map((s) => s && s.trim());+ if (!attr || !key) continue;+ const v = t(key);+ if (v != null) {+ el.setAttribute(attr, v);+ if (attr === 'data-i18n-title' || attr === 'title-text') document.title = v;+ }+ }+ });+}++// --- runtime ---------------------------------------------------------------++export const t = (key, vars) => translate(key, vars);++async function fetchJSON(url) {+ const res = await fetch(url, { credentials: 'same-origin' });+ if (!res.ok) throw new Error(`${url} → ${res.status}`);+ return res.json();+}++async function loadManifest() {+ if (state.manifest) return state.manifest;+ try {+ state.manifest = await fetchJSON(`${LOCALES_BASE}/manifest.json`);+ } catch {+ state.manifest = { default: 'en', locales: [{ code: 'en', name: 'English', dir: 'ltr' }] };+ }+ return state.manifest;+}++function supported(code, manifest) {+ return manifest.locales.find((l) => l.code === code);+}++// localStorage → ?lang= → navigator languages → manifest default.+function detectLocale(manifest) {+ if (!hasDOM) return manifest.default;+ const stored = localStorage.getItem(STORAGE_KEY);+ if (stored && supported(stored, manifest)) return stored;+ const q = new URLSearchParams(location.search).get('lang');+ if (q && supported(q, manifest)) return q;+ for (const nav of navigator.languages || [navigator.language || '']) {+ if (!nav) continue;+ if (supported(nav, manifest)) return nav;+ const base = nav.split('-')[0];+ const byBase = manifest.locales.find((l) => l.code === base || l.code.split('-')[0] === base);+ if (byBase) return byBase.code;+ }+ return manifest.default;+}++async function loadCatalog(code, manifest) {+ if (code === manifest.default) return {}; // English text is already in the HTML+ return fetchJSON(`${LOCALES_BASE}/${code}.json`).catch(() => ({}));+}++export async function setLocale(code) {+ const manifest = await loadManifest();+ const entry = supported(code, manifest) ? code : manifest.default;++ // Fallback catalog is always the entryLocale so partial translations don't+ // leave blanks; for the default locale the HTML itself is the source.+ if (entry !== manifest.default && !Object.keys(state.fallback).length) {+ state.fallback = await loadCatalog(manifest.default, manifest).catch(() => ({}));+ }+ state.catalog = await loadCatalog(entry, manifest);+ state.current = entry;++ if (hasDOM) {+ localStorage.setItem(STORAGE_KEY, entry);+ const meta = supported(entry, manifest);+ document.documentElement.lang = entry;+ document.documentElement.dir = meta?.dir === 'rtl' ? 'rtl' : 'ltr';+ applyCatalog(document, t);+ window.dispatchEvent(new CustomEvent('i18n:change', { detail: { locale: entry } }));+ }+ return entry;+}++export function getLocale() {+ return state.current;+}++export async function initI18n() {+ const manifest = await loadManifest();+ await setLocale(detectLocale(manifest));+}++// --- <lang-switcher> web component -----------------------------------------+//+// Accessible language picker for the global nav: a native <select> (keyboard ++// screen-reader friendly out of the box) styled to match the design tokens,+// with hover/focus/active states. Renders nothing until the manifest lists more+// than one locale, so it self-hides on a single-language deploy.++class LangSwitcher extends HTMLElement {+ async connectedCallback() {+ const manifest = await loadManifest();+ if (!manifest.locales || manifest.locales.length < 2) return;++ const root = this.attachShadow({ mode: 'open' });+ root.innerHTML = `+ <style>+ :host { display: inline-flex; }+ .wrap { position: relative; display: inline-flex; align-items: center; }+ svg { position: absolute; left: 8px; width: 14px; height: 14px; opacity: .6; pointer-events: none; }+ select {+ appearance: none; -webkit-appearance: none;+ font: inherit; font-size: 13px; line-height: 1;+ color: var(--text-2, #cfcfd4);+ background: var(--surface-2, rgba(255,255,255,.04));+ border: 1px solid var(--border, rgba(255,255,255,.12));+ border-radius: 8px;+ padding: 7px 26px 7px 28px;+ cursor: pointer;+ transition: border-color .15s ease, background .15s ease, color .15s ease;+ }+ select:hover { color: var(--text, #fff); border-color: var(--border-strong, rgba(255,255,255,.24)); }+ select:focus-visible { outline: 2px solid var(--accent, #6d6dff); outline-offset: 2px; }+ select:active { transform: translateY(1px); }+ .chev { right: 8px; left: auto; }+ option { color: #111; }+ </style>+ <span class="wrap">+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="1.6"/><path d="M3 12h18M12 3c2.5 2.5 3.8 5.7 3.8 9S14.5 18.5 12 21M12 3C9.5 5.5 8.2 8.7 8.2 12S9.5 18.5 12 21" stroke="currentColor" stroke-width="1.4"/></svg>+ <select aria-label="Choose language">+ ${manifest.locales.map((l) => `<option value="${l.code}">${l.name}</option>`).join('')}+ </select>+ <svg class="chev" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="1.6"/></svg>+ </span>`;++ const select = root.querySelector('select');+ select.value = getLocale();+ select.addEventListener('change', () => setLocale(select.value));+ // Keep the control in sync if another instance or code path changes locale.+ window.addEventListener('i18n:change', (e) => {+ if (e.detail?.locale) select.value = e.detail.locale;+ });+ }+}++if (hasDOM && !customElements.get('lang-switcher')) {+ customElements.define('lang-switcher', LangSwitcher);+}++// Auto-initialize on load so any page that ships this script is localized with+// zero per-page wiring.+if (hasDOM) {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => initI18n());+ } else {+ initI18n();+ }+ window.threewsI18n = { t, setLocale, getLocale, initI18n };+}diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.jsindex 09db7d5a3..c06973bc1 100644--- a/tests/api/text-to-image.test.js+++ b/tests/api/text-to-image.test.js@@ -250,6 +250,69 @@ describe('textToImage — Vertex → Replicate fallback', () => {expect(caught.message).not.toMatch(/credit|\$5|throttl|rate limit/i);});+ it('masks a Replicate 402 out-of-credit failure as a buyer-safe billing error', async () => {+ // The incident the user hit: the free NIM lane fell through to the paid+ // Replicate backstop, which had zero credit. Replicate returns the hard+ // "purchase credit at replicate.com/billing" copy on a 402 — that vendor+ // billing page must never reach the buyer. We keep the raw detail for logs+ // (providerDetail) but the surfaced message must be neutral.+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';+ const RAW_DETAIL =+ 'You have insufficient credit to run this model. Go to ' ++ 'https://replicate.com/account/billing#billing to purchase credit. ' ++ 'Once you purchase credit, please wait a few minutes before trying again.';+ stubFetch([+ [+ 'api.replicate.com',+ () =>+ new Response(JSON.stringify({ detail: RAW_DETAIL }), {+ status: 402,+ headers: { 'content-type': 'application/json' },+ }),+ ],+ ]);+ vi.spyOn(console, 'warn').mockImplementation(() => {});++ const textToImage = await freshTextToImage();+ const caught = await textToImage('a red teapot').then(+ () => null,+ (e) => e,+ );+ expect(caught).toBeTruthy();+ expect(caught.code).toBe('billing');+ expect(caught.providerStatus).toBe(402);+ expect(caught.providerDetail).toBe(RAW_DETAIL); // retained for server logs+ expect(caught.message).toBe('image provider billing error');+ // The raw vendor billing page and "buy credit" call-to-action must be gone.+ expect(caught.message).not.toMatch(/credit|replicate\.com|purchase|insufficient/i);+ });++ it('masks a credit/billing message even on a non-402 status', async () => {+ // Defense in depth: if Replicate ever delivers the same billing copy under+ // a different 4xx, the content match must still keep it off the buyer.+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';+ stubFetch([+ [+ 'api.replicate.com',+ () =>+ new Response(+ JSON.stringify({ detail: 'Payment required: please purchase credit to continue.' }),+ { status: 400, headers: { 'content-type': 'application/json' } },+ ),+ ],+ ]);+ vi.spyOn(console, 'warn').mockImplementation(() => {});++ const textToImage = await freshTextToImage();+ const caught = await textToImage('a red teapot').then(+ () => null,+ (e) => e,+ );+ expect(caught.code).toBe('billing');+ expect(caught.providerStatus).toBe(402);+ expect(caught.message).not.toMatch(/credit|purchase|payment/i);+ });+it('persists a Vertex data: URI to object storage and returns the https URL', async () => {process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';vertexState.configured = true;diff --git a/vercel.json b/vercel.jsonindex 30360178b..4688c2419 100644--- a/vercel.json+++ b/vercel.json@@ -2600,6 +2600,14 @@"src": "/avatars/([^/]+)/edit","dest": "/avatar-edit.html?id=$1"},+ {+ "src": "/avatar-edit",+ "dest": "/avatar-edit.html"+ },+ {+ "src": "/avatar-edit/",+ "dest": "/avatar-edit.html"+ },{"src": "/agent/([^/]+)/embed","headers": {diff --git a/vite.config.js b/vite.config.jsindex 2fa3a961c..7b7ffaaf6 100644--- a/vite.config.js+++ b/vite.config.js@@ -1377,11 +1377,20 @@ support: resolve(__dirname, 'pages/support.html'),'window.va=window.va||function(){(window.vaq=window.vaq||[]).push(arguments)};',injectTo: 'head',},- {- tag: 'script',- attrs: { defer: true, src: '/_vercel/insights/script.js' },- injectTo: 'head',- },+ // /_vercel/insights/script.js only exists on a Vercel deploy. Under+ // the Vite dev server (ctx.server present) it 404s with an empty MIME+ // type, which strict MIME checking surfaces as a console error on every+ // page. Inject it only at build time; the `va` queue stub above still+ // no-ops any track() calls fired in dev.+ ...(ctx.server+ ? []+ : [+ {+ tag: 'script',+ attrs: { defer: true, src: '/_vercel/insights/script.js' },+ injectTo: 'head',+ },+ ]),];},},