d3ro-voice/scripts/ci/sync-i18n-locales.mjs

85 lines
2.8 KiB
JavaScript

#!/usr/bin/env node
// scripts/ci/sync-i18n-locales.mjs
// Synchronizes or checks translation keys across all 12 locale files in packages/i18n/src/locales/*.json.
// Master key list is ko.json + en.json (all translation strings live in locales/*.json, never hardcoded here).
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const localesDir = path.resolve(__dirname, '../../packages/i18n/src/locales')
const LOCALES = ['ko', 'en', 'ja', 'zh', 'zh-TW', 'es', 'fr', 'de', 'pt', 'ru', 'vi', 'th']
const checkOnly = process.argv.includes('--check')
function readLocale(code) {
const filePath = path.join(localesDir, `${code}.json`)
return {
filePath,
data: JSON.parse(fs.readFileSync(filePath, 'utf8')),
}
}
const koEntry = readLocale('ko')
const enEntry = readLocale('en')
const ko = koEntry.data
const en = enEntry.data
if (checkOnly) {
const koKeys = Object.keys(ko)
const koKeySet = new Set(koKeys)
const errors = []
for (const code of LOCALES) {
const { data } = readLocale(code)
const keys = Object.keys(data)
const missing = koKeys.filter((k) => !(k in data))
const extra = keys.filter((k) => !koKeySet.has(k))
const empty = koKeys.filter((k) => k in data && (typeof data[k] !== 'string' || data[k].trim().length === 0))
if (missing.length > 0) errors.push(`${code}.json missing ${missing.length} keys (first: ${missing[0]})`)
if (extra.length > 0) errors.push(`${code}.json has ${extra.length} extra keys (first: ${extra[0]})`)
if (empty.length > 0) errors.push(`${code}.json has ${empty.length} empty values (first: ${empty[0]})`)
}
if (errors.length > 0) {
process.stderr.write(`[i18n-sync] FAILED:\n - ${errors.join('\n - ')}\n`)
process.exit(1)
}
process.stdout.write(`[i18n-sync] GREEN (${koKeys.length} keys across ${LOCALES.length} locales)\n`)
process.exit(0)
}
for (const k of Object.keys(ko)) {
if (!(k in en)) en[k] = ko[k]
}
for (const k of Object.keys(en)) {
if (!(k in ko)) ko[k] = en[k]
}
const masterKeys = Object.keys(ko)
function writeOrderedJson(filePath, obj) {
const ordered = {}
for (const k of masterKeys) {
ordered[k] = obj[k]
}
fs.writeFileSync(filePath, JSON.stringify(ordered, null, 2) + '\n', 'utf8')
}
writeOrderedJson(koEntry.filePath, ko)
writeOrderedJson(enEntry.filePath, en)
for (const loc of LOCALES) {
if (loc === 'ko' || loc === 'en') continue
const { filePath, data } = readLocale(loc)
for (const k of masterKeys) {
if (!(k in data) || typeof data[k] !== 'string' || data[k].length === 0) {
data[k] = en[k] ?? ko[k]
}
}
writeOrderedJson(filePath, data)
}
process.stdout.write(`[i18n-sync] Synchronized ${masterKeys.length} keys across ${LOCALES.length} locales.\n`)