Files
ui/scripts/i18n-translate.mjs
zeekayGitHubCursor Agentzhanzo-agentHanzo Devhanzo-platform[bot] <201622097+hanzo-platform[bot]@users.noreply.github.com>
fcedaff5b5 Localize built-in UI copy and the docs site (#266)
* @hanzo/ui 8.30.0: every word the package authors is the reader's language

- The consumer installs every peer of the train it pins
- @hanzo/ui 8.30.0: every word the package authors is the reader's language
- i18n: one English fallback, the footer's doors through t, and a typed header cell
- agents: the elements i18n touched draw with gui props, not style
- i18n: @hanzo/ui/product/pure still depends on nothing
- i18n: the framework's collections, records and media say their words in the reader's language
- i18n: one English fallback for the pure modules that build a sentence
- i18n: the builder workspace says its words in the reader's language
- i18n: settings, the catalogue shelf and the backdrop presets
- i18n: the masthead's tree is marked for translation and drawn through t
- i18n: the product layer says its words in the reader's language
- i18n: mockups and market widgets say their words in the reader's language
- i18n: the gui controls say their words in the reader's language
- picker: each choosable option wears the field's own ink
- consent: the bar's fit width is a gui prop
- i18n: onboarding, chat, the model picker, sign-in, consent and the corner speak the reader's language
- i18n: @hanzo/ui peer-depends on @hanzo/i18n

* feat(i18n): localize built-in UI copy and the docs site

English stays the default. A locale on Hanzo or LocaleProvider switches
built-in labels, chat copy, and dates, and Arabic sets dir=rtl. Missing
keys render in English. The docs site adds a language switcher, prefixed
routes, hreflang, and a localized sitemap.

Co-authored-by: z <[email protected]>

* docs: translate every page into the 16 target locales

Each English doc now has a locale file under data/i18n. Code fences,
previews, links, and product names stay as written. A missing file still
falls back to English.

Co-authored-by: z <[email protected]>

* Unfinished: these files still contain <<<<<<< / ======= / >>>>>>> conflict markers on origin/agent/i18n-locales-0366: pk…

Run: sess_498ba60a49b5870a63d042e97f565728

* No conflict markers remain. Now: pull origin agent/i18n-locales-0366 (merge), run pnpm install --frozen-lockfile (if it…

Run: sess_0a7901763139b331895f48f02df95b94

* CI on agent/i18n-locales-0366 head 362214f fails @hanzo/ui tests 1-8, ui browser/vite/webpack. Concrete errors: (a) pkg/…

Run: sess_79bff23928c2986ee61768a243fc6dfa

* fix(ui): Dial RING from look; drop duplicate useI18n in Masthead

Unblocks pkg/ui build on #266: RING lives in ./look (not ./ring); Masthead had a duplicate const { t } = useI18n() after the #254/#287 merge.

* fix(ui): rtl.test ALLOWED counts for Masthead/DiffViewer/SlideOver

Align ALLOWED physical-side budgets with current source after the i18n merge: Masthead 2, DiffViewer 5, SlideOver 1.

* fix(ui): RepoSelect test expects default note + troubleshoot

Co-authored-by: Hanzo Dev <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: z <[email protected]>
Co-authored-by: hanzo-agent <[email protected]>
Co-authored-by: Hanzo Dev <[email protected]>
Co-authored-by: hanzo-platform[bot] <201622097+hanzo-platform[bot]@users.noreply.github.com>
2026-11-05 04:11:17 -08:00

144 lines
4.9 KiB
JavaScript

/**
* Fill missing catalog strings from an OpenAI-compatible chat API.
*
* English in `pkg/ui/src/i18n/source.ts` is the source. This writes only keys
* a locale file lacks, so a reviewed translation is never overwritten.
* Nothing here is a secret: the key comes from the environment.
*
* HANZO_API_KEY=… node scripts/i18n-translate.mjs
* HANZO_API_KEY=… HANZO_API_BASE=https://api.hanzo.ai/v1 node scripts/i18n-translate.mjs --locale es
*
* `HANZO_API_BASE` defaults to https://api.hanzo.ai/v1. `HANZO_I18N_MODEL`
* defaults to `gpt-4o-mini`. Product names (Hanzo, Enso, Kai, Lux, Zoo, Zen),
* `{placeholders}`, code and URLs must be copied unchanged. The model is
* asked for that, and this script refuses a reply that drops a placeholder.
*/
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const sourcePath = join(root, 'pkg/ui/src/i18n/source.ts')
const catalogDir = join(root, 'pkg/ui/src/i18n/catalogs')
/** Path tag → catalog file `@hanzo/i18n` negotiates it to. */
const FILES = {
es: 'es-ES.json',
fr: 'fr-FR.json',
de: 'de-DE.json',
it: 'it-IT.json',
'pt-BR': 'pt-BR.json',
ru: 'ru.json',
tr: 'tr.json',
ar: 'ar.json',
hi: 'hi-IN.json',
id: 'id-ID.json',
vi: 'vi.json',
th: 'th.json',
ja: 'ja-JP.json',
ko: 'ko-KR.json',
'zh-CN': 'zh-Hans.json',
'zh-TW': 'zh-Hant.json',
}
const NAMES = {
es: 'Spanish (Spain)',
fr: 'French (France)',
de: 'German',
it: 'Italian',
'pt-BR': 'Brazilian Portuguese',
ru: 'Russian',
tr: 'Turkish',
ar: 'Arabic',
hi: 'Hindi',
id: 'Indonesian',
vi: 'Vietnamese',
th: 'Thai',
ja: 'Japanese',
ko: 'Korean',
'zh-CN': 'Simplified Chinese',
'zh-TW': 'Traditional Chinese',
}
const keys = [...readFileSync(sourcePath, 'utf8').matchAll(/^ {2}'(.*)',?$/gm)].map((m) => m[1])
const only = process.argv.includes('--locale') ? process.argv[process.argv.indexOf('--locale') + 1] : null
const targets = only ? [only] : Object.keys(FILES)
const base = (process.env.HANZO_API_BASE || 'https://api.hanzo.ai/v1').replace(/\/$/, '')
const key = process.env.HANZO_API_KEY || process.env.OPENAI_API_KEY
const model = process.env.HANZO_I18N_MODEL || 'gpt-4o-mini'
if (!key) {
console.error('Set HANZO_API_KEY (or OPENAI_API_KEY). No request was sent.')
process.exit(1)
}
const tokens = (s) => s.match(/\{[a-zA-Z]+\}/g) ?? []
async function translate(locale, batch) {
const res = await fetch(`${base}/chat/completions`, {
method: 'POST',
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
model,
temperature: 0.2,
response_format: { type: 'json_object' },
messages: [
{
role: 'system',
content: [
`Translate UI strings into ${NAMES[locale] || locale}.`,
'Return a JSON object whose keys are the English source strings and whose values are the translations.',
'Keep {placeholders} exactly, including the braces.',
'Do not translate Hanzo, Enso, Kai, Lux, Zoo, Zen, URLs, code, or file names.',
'Natural interface copy, not a gloss. Preserve punctuation the English uses to address a person.',
].join(' '),
},
{ role: 'user', content: JSON.stringify(Object.fromEntries(batch.map((k) => [k, k]))) },
],
}),
})
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
const body = await res.json()
const raw = body.choices?.[0]?.message?.content
if (!raw) throw new Error('empty completion')
return JSON.parse(raw)
}
for (const locale of targets) {
const file = FILES[locale]
if (!file) {
console.error(`unknown locale ${locale}`)
process.exit(1)
}
const path = join(catalogDir, file)
const catalog = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {}
const missing = keys.filter((k) => typeof catalog[k] !== 'string' || catalog[k].length === 0)
if (!missing.length) {
console.log(`${locale}: complete`)
continue
}
console.log(`${locale}: ${missing.length} missing`)
for (let i = 0; i < missing.length; i += 40) {
const batch = missing.slice(i, i + 40)
const got = await translate(locale, batch)
for (const k of batch) {
const value = got[k]
if (typeof value !== 'string' || !value) {
console.error(` no translation for ${JSON.stringify(k)}`)
continue
}
for (const token of tokens(k)) {
if (!value.includes(token)) {
console.error(` refused ${JSON.stringify(k)} (dropped ${token})`)
continue
}
}
catalog[k] = value
}
}
const ordered = {}
for (const k of keys) if (typeof catalog[k] === 'string') ordered[k] = catalog[k]
writeFileSync(path, JSON.stringify(ordered, null, 2) + '\n')
console.log(`${locale}: wrote ${file}`)
}