1 const fs = require("fs")
2 const path = require("path")
3
4 const pluralConfig = require("../../src/i18n/plural-config.json")
5
6 const translationsDir = path.join(__dirname, "../../src/i18n/translations")
7 const PLURAL_SUFFIX = /^(.+)_(zero|one|two|few|many|other)$/
8 const IGNORED_KEYS = new Set(["$schema"])
9
10 function isObject(value) {
11 return typeof value === "object" && value !== null && !Array.isArray(value)
12 }
13
14 function readJson(filePath) {
15 return JSON.parse(fs.readFileSync(filePath, "utf-8"))
16 }
17
18 function writeJson(filePath, data) {
19 fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n")
20 }
21
22 function getLocales() {
23 return fs
24 .readdirSync(translationsDir)
25 .filter((file) => file.endsWith(".json") && file !== "$schema.json")
26 .map((file) => file.replace(".json", ""))
27 .filter((locale) => locale !== "en")
28 .sort()
29 }
30
31 function getPlaceholders(value, isPlural) {
32 return (value.match(/{{\s*[^}]+?\s*}}|<\/?\d+\s*\/?>/g) || [])
33 .map((placeholder) => placeholder.replace(/\s/g, ""))
34 .filter((placeholder) => !isPlural || placeholder !== "{{count}}")
35 .sort()
36 }
37
38 function getExpectedEntries(enObj, forms) {
39 const entries = []
40 const seenPluralGroups = new Set()
41
42 Object.entries(enObj).forEach(([key, value]) => {
43 if (IGNORED_KEYS.has(key)) {
44 return
45 }
46
47 const pluralMatch = key.match(PLURAL_SUFFIX)
48
49 if (!pluralMatch || isObject(value)) {
50 entries.push([key, value])
51 return
52 }
53
54 const baseKey = pluralMatch[1]
55 if (seenPluralGroups.has(baseKey)) {
56 return
57 }
58 seenPluralGroups.add(baseKey)
59
60 forms.forEach((form) => {
61 entries.push([
62 `${baseKey}_${form}`,
63 `${baseKey}_${form}` in enObj
64 ? enObj[`${baseKey}_${form}`]
65 : enObj[`${baseKey}_other`],
66 ])
67 })
68 })
69
70 return entries
71 }
72
73 function findMissing(enObj, localeObj, forms) {
74 const missing = {}
75 let count = 0
76
77 getExpectedEntries(enObj, forms).forEach(([key, enValue]) => {
78 const localeValue = localeObj ? localeObj[key] : undefined
79
80 if (isObject(enValue)) {
81 const nested = findMissing(
82 enValue,
83 isObject(localeValue) ? localeValue : undefined,
84 forms
85 )
86
87 if (nested.count > 0) {
88 missing[key] = nested.missing
89 count += nested.count
90 }
91 return
92 }
93
94 if (typeof localeValue !== "string" || localeValue.trim() === "") {
95 missing[key] = enValue
96 count++
97 }
98 })
99
100 return { missing, count }
101 }
102
103 // New keys go after their closest preceding en.json sibling so existing key order is kept.
104 function mergeLevel(enObj, localeObj, translated, forms, keyPath, errors) {
105 const expected = getExpectedEntries(enObj, forms)
106 const result = Object.entries(isObject(localeObj) ? localeObj : {})
107
108 Object.keys(translated).forEach((key) => {
109 if (!expected.some(([expectedKey]) => expectedKey === key)) {
110 errors.push(`Unknown key "${[...keyPath, key].join(".")}"`)
111 }
112 })
113
114 expected.forEach(([key, enValue], index) => {
115 if (!(key in translated)) {
116 return
117 }
118
119 const fullKey = [...keyPath, key].join(".")
120 const translatedValue = translated[key]
121 const existingIndex = result.findIndex(([k]) => k === key)
122 let value
123
124 if (isObject(enValue)) {
125 if (!isObject(translatedValue)) {
126 errors.push(`Expected an object at "${fullKey}"`)
127 return
128 }
129
130 value = mergeLevel(
131 enValue,
132 existingIndex === -1 ? undefined : result[existingIndex][1],
133 translatedValue,
134 forms,
135 [...keyPath, key],
136 errors
137 )
138
139 if (existingIndex === -1 && Object.keys(value).length === 0) {
140 return
141 }
142 } else {
143 if (existingIndex !== -1) {
144 errors.push(`"${fullKey}" is already translated`)
145 return
146 }
147
148 if (typeof translatedValue !== "string" || !translatedValue.trim()) {
149 errors.push(`Expected a non-empty string at "${fullKey}"`)
150 return
151 }
152
153 // Plural forms other than the English ones may legitimately add or drop {{count}}.
154 const isPlural = PLURAL_SUFFIX.test(key)
155 const expectedPlaceholders = getPlaceholders(enValue, isPlural).join(",")
156 const actualPlaceholders = getPlaceholders(
157 translatedValue,
158 isPlural
159 ).join(",")
160
161 if (expectedPlaceholders !== actualPlaceholders) {
162 errors.push(
163 `Placeholder mismatch at "${fullKey}": expected [${expectedPlaceholders}], got [${actualPlaceholders}]`
164 )
165 return
166 }
167
168 value = translatedValue
169 }
170
171 if (existingIndex !== -1) {
172 result[existingIndex] = [key, value]
173 return
174 }
175
176 let insertAt = result.length && result[0][0] === "$schema" ? 1 : 0
177 for (let i = index - 1; i >= 0; i--) {
178 const previousIndex = result.findIndex(([k]) => k === expected[i][0])
179 if (previousIndex !== -1) {
180 insertAt = previousIndex + 1
181 break
182 }
183 }
184
185 result.splice(insertAt, 0, [key, value])
186 })
187
188 return Object.fromEntries(result)
189 }
190
191 function parseArgs(argv) {
192 const args = {}
193 for (let i = 0; i < argv.length; i++) {
194 if (argv[i].startsWith("--")) {
195 args[argv[i].slice(2)] = argv[i + 1]
196 i++
197 }
198 }
199 return args
200 }
201
202 function runMissing({ output }) {
203 const en = readJson(path.join(translationsDir, "en.json"))
204 const report = {}
205 let total = 0
206
207 getLocales().forEach((locale) => {
208 const forms = pluralConfig[locale]
209 if (!forms) {
210 throw new Error(`Language "${locale}" not found in plural-config.json`)
211 }
212
213 const localeJson = readJson(path.join(translationsDir, `${locale}.json`))
214 const { missing, count } = findMissing(en, localeJson, forms)
215
216 if (count > 0) {
217 report[locale] = { count, pluralForms: forms, missing }
218 total += count
219 }
220 console.log(`${locale}: ${count} missing`)
221 })
222
223 console.log(`Total: ${total} missing translations`)
224
225 if (output) {
226 writeJson(output, report)
227 console.log(`Report written to ${output}`)
228 }
229 }
230
231 function runApply({ input }) {
232 if (!input) {
233 console.error("Please provide --input <directory of <locale>.json files>")
234 process.exit(1)
235 }
236
237 const en = readJson(path.join(translationsDir, "en.json"))
238 const locales = new Set(getLocales())
239 const files = fs.existsSync(input)
240 ? fs
241 .readdirSync(input)
242 .filter((file) => file.endsWith(".json"))
243 .sort()
244 : []
245 files.forEach((file) => {
246 const locale = file.split(".")[0]
247
248 if (!locales.has(locale)) {
249 console.warn(`Skipping ${file}: no matching translation file`)
250 return
251 }
252
253 let translations
254 try {
255 translations = readJson(path.join(input, file))
256 } catch (e) {
257 console.warn(`Skipping ${file}: invalid JSON (${e.message})`)
258 return
259 }
260
261 const localePath = path.join(translationsDir, `${locale}.json`)
262 const errors = []
263 const merged = mergeLevel(
264 en,
265 readJson(localePath),
266 translations,
267 pluralConfig[locale],
268 [],
269 errors
270 )
271
272 if (errors.length > 0) {
273 console.warn(`Skipped keys in ${file}:\n ${errors.join("\n ")}`)
274 }
275
276 writeJson(localePath, merged)
277 console.log(`Updated ${locale}.json`)
278 })
279 }
280
281 function main() {
282 const [command, ...rest] = process.argv.slice(2)
283 const args = parseArgs(rest)
284
285 if (command === "missing") {
286 runMissing(args)
287 } else if (command === "apply") {
288 runApply(args)
289 } else {
290 console.error("Usage: sync-translations.js <missing|apply> [options]")
291 process.exit(1)
292 }
293 }
294
295 if (require.main === module) {
296 main()
297 }
298
299 module.exports = { findMissing, getPlaceholders, mergeLevel }